unix.pp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Michael Van Canneyt,
  4. BSD parts (c) 2000 by Marco van de Voort
  5. members of the Free Pascal development team.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY;without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. Unit Unix;
  13. Interface
  14. Uses BaseUnix,UnixType;
  15. {$i aliasptp.inc}
  16. { Get Types and Constants only exported in this unit }
  17. {$i unxconst.inc}
  18. // We init to zero to be able to put timezone stuff under IFDEF, and still
  19. // keep the code working.
  20. // We can't do this hear, since unixutil functions access this.
  21. // var
  22. // Tzseconds : Longint = 0;
  23. {********************
  24. File
  25. ********************}
  26. Const
  27. P_IN = 1; // pipes (?)
  28. P_OUT = 2;
  29. Const
  30. LOCK_SH = 1; // flock constants ?
  31. LOCK_EX = 2;
  32. LOCK_UN = 8;
  33. LOCK_NB = 4;
  34. Type
  35. Tpipe = baseunix.tfildes; // compability.
  36. {******************************************************************************
  37. Procedure/Functions
  38. ******************************************************************************}
  39. {**************************
  40. Time/Date Handling
  41. ***************************}
  42. var
  43. tzdaylight : boolean;
  44. tzname : array[boolean] of pchar;
  45. {$IFNDEF DONT_READ_TIMEZONE} // allows to disable linking in and trying for platforms
  46. // it doesn't (yet) work for.
  47. { timezone support }
  48. procedure GetLocalTimezone(timer:cint;var leap_correct,leap_hit:cint);
  49. procedure GetLocalTimezone(timer:cint);
  50. procedure ReadTimezoneFile(fn:string);
  51. function GetTimezoneFile:string;
  52. {$ENDIF}
  53. {**************************
  54. Process Handling
  55. ***************************}
  56. //
  57. // These are much better, in nearly all ways.
  58. //
  59. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  60. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  61. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  62. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  63. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  64. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  65. Function Shell (const Command:String):cint;
  66. Function Shell (const Command:AnsiString):cint;
  67. Function fpSystem(const Command:AnsiString):cint;
  68. Function WaitProcess (Pid:cint):cint; { like WaitPid(PID,@result,0) Handling of Signal interrupts (errno=EINTR), returning the Exitcode of Process (>=0) or -Status if terminated}
  69. Function WIFSTOPPED (Status: Integer): Boolean;
  70. Function W_EXITCODE (ReturnCode, Signal: Integer): Integer;
  71. Function W_STOPCODE (Signal: Integer): Integer;
  72. {**************************
  73. File Handling
  74. ***************************}
  75. {$ifndef FPC_USE_LIBC} // defined using cdecl for libc.
  76. Function fsync (fd : cint) : cint;
  77. Function fpFlock (fd,mode : cint) : cint ;
  78. Function fStatFS (Fd: cint;Var Info:tstatfs):cint;
  79. Function StatFS (Path:pchar;Var Info:tstatfs):cint;
  80. {$endif}
  81. Function fpFlock (var T : text;mode : cint) : cint;
  82. Function fpFlock (var F : File;mode : cint) : cint;
  83. Function SelectText (var T:Text;TimeOut :PTimeVal):cint;
  84. Function SelectText (var T:Text;TimeOut :cint):cint;
  85. {**************************
  86. Directory Handling
  87. ***************************}
  88. procedure SeekDir(p:pdir;loc:clong);
  89. function TellDir(p:pdir):clong;
  90. {**************************
  91. Pipe/Fifo/Stream
  92. ***************************}
  93. Function AssignPipe (var pipe_in,pipe_out:cint):cint;
  94. Function AssignPipe (var pipe_in,pipe_out:text):cint;
  95. Function AssignPipe (var pipe_in,pipe_out:file):cint;
  96. //Function PClose (Var F:text) : cint;
  97. //Function PClose (Var F:file) : cint;
  98. Function POpen (var F:text;const Prog:String;rw:char):cint;
  99. Function POpen (var F:file;const Prog:String;rw:char):cint;
  100. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  101. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  102. Function GetDomainName:String;
  103. Function GetHostName:String;
  104. {**************************
  105. Memory functions
  106. ***************************}
  107. const
  108. PROT_READ = $1; { page can be read }
  109. PROT_WRITE = $2; { page can be written }
  110. PROT_EXEC = $4; { page can be executed }
  111. PROT_NONE = $0; { page can not be accessed }
  112. MAP_SHARED = $1; { Share changes }
  113. // MAP_PRIVATE = $2; { Changes are private }
  114. MAP_TYPE = $f; { Mask for type of mapping }
  115. MAP_FIXED = $10; { Interpret addr exactly }
  116. // MAP_ANONYMOUS = $20; { don't use a file }
  117. {$ifdef Linux}
  118. MAP_GROWSDOWN = $100; { stack-like segment }
  119. MAP_DENYWRITE = $800; { ETXTBSY }
  120. MAP_EXECUTABLE = $1000; { mark it as an executable }
  121. MAP_LOCKED = $2000; { pages are locked }
  122. MAP_NORESERVE = $4000; { don't check for reservations }
  123. {$else}
  124. {$ifdef FreeBSD}
  125. // FreeBSD defines MAP_COPY=MAP_PRIVATE=$2;
  126. MAP_FILE = $0000; { map from file (default) }
  127. MAP_ANON = $1000; { allocated from memory, swap space }
  128. MAP_RENAME = $0020; { Sun: rename private pages to file }
  129. MAP_NORESERVE = $0040; { Sun: don't reserve needed swap area }
  130. MAP_INHERIT = $0080; { region is retained after exec }
  131. MAP_NOEXTEND = $0100; { for MAP_FILE, don't change file size }
  132. MAP_HASSEMAPHORE = $0200; { region may contain semaphores }
  133. MAP_STACK = $0400; { region grows down, like a stack }
  134. MAP_NOSYNC = $0800; { page to but do not sync underlying file}
  135. MAP_NOCORE = $20000;{ dont include these pages in a coredump}
  136. {$endif}
  137. {$endif}
  138. {**************************
  139. Utility functions
  140. ***************************}
  141. Type
  142. TFSearchOption = (NoCurrentDirectory,
  143. CurrentDirectoryFirst,
  144. CurrentDirectoryLast);
  145. Function FSearch (const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  146. Function FSearch (const path:AnsiString;dirlist:AnsiString):AnsiString;
  147. procedure SigRaise (sig:integer);
  148. {$ifdef FPC_USE_LIBC}
  149. const clib = 'c';
  150. {$i unxdeclh.inc}
  151. {$else}
  152. {$i unxsysch.inc} // calls used in system and not reexported from baseunix
  153. {$endif}
  154. {******************************************************************************
  155. Implementation
  156. ******************************************************************************}
  157. {$i unxovlh.inc}
  158. Implementation
  159. Uses UnixUtil, // tzseconds
  160. Strings {$ifndef FPC_USE_LIBC},Syscall{$endif};
  161. {$i unxovl.inc}
  162. {$ifndef FPC_USE_LIBC}
  163. {$i syscallh.inc}
  164. {$i unxsysc.inc}
  165. {$endif}
  166. { Get the definitions of textrec and filerec }
  167. {$i textrec.inc}
  168. {$i filerec.inc}
  169. {$i unxfunc.inc} { Platform specific implementations }
  170. Function getenv(name:string):Pchar; external name 'FPC_SYSC_FPGETENV';
  171. {******************************************************************************
  172. Process related calls
  173. ******************************************************************************}
  174. { Most calls of WaitPID do not handle the result correctly, this funktion treats errors more correctly }
  175. Function WaitProcess(Pid:cint):cint; { like WaitPid(PID,@result,0) Handling of Signal interrupts (errno=EINTR), returning the Exitcode of Process (>=0) or -Status if terminated}
  176. var
  177. r,s : cint;
  178. begin
  179. s:=$7F00;
  180. repeat
  181. r:=fpWaitPid(Pid,@s,0);
  182. if (r=-1) and (fpgeterrno=ESysEIntr) Then
  183. r:=0;
  184. until (r<>0);
  185. if (r=-1) or (r=0) then // 0 is not a valid return and should never occur (it means status invalid when using WNOHANG)
  186. WaitProcess:=-1 // return -1 to indicate an error. fpwaitpid updated it.
  187. else
  188. begin
  189. if wifexited(s) then
  190. WaitProcess:=wexitstatus(s)
  191. else if (s>0) then // Until now there is not use of the highest bit , but check this for the future
  192. WaitProcess:=-s // normal case
  193. else
  194. WaitProcess:=s; // s<0 should not occur, but wie return also a negativ value
  195. end;
  196. end;
  197. function intFpExecVEMaybeP (Const PathName:AnsiString;Args,MyEnv:ppchar;SearchPath:Boolean):cint;
  198. // does an ExecVE, but still has to handle P
  199. // execv variants call this directly, execl variants indirectly via
  200. // intfpexecl
  201. Var
  202. NewCmd : ansistring;
  203. ThePath : AnsiString;
  204. Begin
  205. If SearchPath and (pos('/',pathname)=0) Then
  206. Begin
  207. // The above could be better. (check if not escaped/quoted '/'s) ?
  208. // (Jilles says this is ok)
  209. // Stevens says only search if newcmd contains no '/'
  210. // fsearch is not ansistring clean yet.
  211. ThePath:=fpgetenv('PATH');
  212. if thepath='' then
  213. thepath:='.'; // FreeBSD uses _PATH_DEFPATH = /usr/bin:/bin
  214. // but a quick check showed that _PATH_DEFPATH
  215. // varied from OS to OS
  216. newcmd:=FSearch(pathname,thepath,NoCurrentDirectory);
  217. // FreeBSD libc keeps on trying till a file is successfully run.
  218. // Stevens says "try each path prefix"
  219. // execp puts newcmd here.
  220. args^:=pchar(newcmd);
  221. End else
  222. newcmd:=pathname;
  223. // repeat
  224. // if searchpath then args^:=pchar(commandtorun)
  225. IntFpExecVEMaybeP:=fpExecVE(newcmd,Args,MyEnv);
  226. {
  227. // Code that if exec fails due to permissions, tries to run it with sh
  228. // Should we deallocate p on fail? -> no fpexit is run no matter what
  229. //
  230. }
  231. // if intfpexecvemaybep=-1 then zoekvolgende file.
  232. // until (Goexit) or SearchExit;
  233. {
  234. If IntFpExec=-1 Then
  235. Begin
  236. Error:=fpGetErrno
  237. Case Error of
  238. ESysE2Big : Exit(-1);
  239. ESysELoop,
  240. : Exit(-1);
  241. }
  242. end;
  243. function intFpExecl (Const PathName:AnsiString;const s:array of ansistring;MyEnv:ppchar;SearchPath:Boolean):cint;
  244. { Handles the array of ansistring -> ppchar conversion.
  245. Base for the the "l" variants.
  246. }
  247. var p:ppchar;
  248. begin
  249. If PathName='' Then
  250. Begin
  251. fpsetErrno(ESysEnoEnt);
  252. Exit(-1); // Errno?
  253. End;
  254. p:=ArrayStringToPPchar(s,1);
  255. if p=NIL Then
  256. Begin
  257. GetMem(p,2*sizeof(pchar));
  258. if p=nil then
  259. begin
  260. {$ifdef xunix}
  261. fpseterrno(ESysEnoMem);
  262. {$endif}
  263. fpseterrno(ESysEnoEnt);
  264. exit(-1);
  265. end;
  266. p[1]:=nil;
  267. End;
  268. p^:=pchar(PathName);
  269. IntFPExecL:=intFpExecVEMaybeP(PathName,p,MyEnv,SearchPath);
  270. // If we come here, no attempts were executed successfully.
  271. Freemem(p);
  272. end;
  273. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  274. Begin
  275. FpExecLE:=intFPExecl(PathName,s,MyEnv,false);
  276. End;
  277. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  278. Begin
  279. FpExecL:=intFPExecl(PathName,S,EnvP,false);
  280. End;
  281. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  282. Begin
  283. FpExecLP:=intFPExecl(PathName,S,EnvP,True);
  284. End;
  285. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  286. Begin
  287. fpexecV:=intFpExecVEMaybeP (PathName,args,envp,false);
  288. End;
  289. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  290. Begin
  291. fpexecVP:=intFpExecVEMaybeP (PathName,args,envp,true);
  292. End;
  293. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  294. Begin
  295. fpexecVPE:=intFpExecVEMaybeP (PathName,args,env,true);
  296. End;
  297. // exect and execvP (ExecCapitalP) are not implement
  298. // Non POSIX anyway.
  299. // Exect turns on tracing for the process
  300. // execvP has the searchpath as array of ansistring ( const char *search_path)
  301. {$define FPC_USE_FPEXEC}
  302. Function Shell(const Command:String):cint;
  303. {
  304. Executes the shell, and passes it the string Command. (Through /bin/sh -c)
  305. The current environment is passed to the shell.
  306. It waits for the shell to exit, and returns its exit status.
  307. If the Exec call failed exit status 127 is reported.
  308. }
  309. { Changed the structure:
  310. - the previous version returns an undefinied value if fork fails
  311. - it returns the status of Waitpid instead of the Process returnvalue (see the doc to Shell)
  312. - it uses exit(127) not ExitProc (The Result in pp386: going on Compiling in 2 processes!)
  313. - ShellArgs are now released
  314. - The Old CreateShellArg gives back pointers to a local var
  315. }
  316. var
  317. {$ifndef FPC_USE_FPEXEC}
  318. p : ppchar;
  319. {$endif}
  320. pid : cint;
  321. begin
  322. {$ifndef FPC_USE_FPEXEC}
  323. p:=CreateShellArgv(command);
  324. {$endif}
  325. pid:=fpfork;
  326. if pid=0 then // We are in the Child
  327. begin
  328. {This is the child.}
  329. {$ifndef FPC_USE_FPEXEC}
  330. fpExecve(p^,p,envp);
  331. {$else}
  332. fpexecl('/bin/sh',['-c',Command]);
  333. {$endif}
  334. fpExit(127); // was Exit(127)
  335. end
  336. else if (pid<>-1) then // Successfull started
  337. Shell:=WaitProcess(pid)
  338. else // no success
  339. Shell:=-1; // indicate an error
  340. {$ifndef FPC_USE_FPEXEC}
  341. FreeShellArgV(p);
  342. {$endif}
  343. end;
  344. Function Shell(const Command:AnsiString):cint;
  345. {
  346. AnsiString version of Shell
  347. }
  348. var
  349. {$ifndef FPC_USE_FPEXEC}
  350. p : ppchar;
  351. {$endif}
  352. pid : cint;
  353. begin { Changes as above }
  354. {$ifndef FPC_USE_FPEXEC}
  355. p:=CreateShellArgv(command);
  356. {$endif}
  357. pid:=fpfork;
  358. if pid=0 then // We are in the Child
  359. begin
  360. {$ifdef FPC_USE_FPEXEC}
  361. fpexecl('/bin/sh',['-c',Command]);
  362. {$else}
  363. fpExecve(p^,p,envp);
  364. {$endif}
  365. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  366. end
  367. else if (pid<>-1) then // Successfull started
  368. Shell:=WaitProcess(pid)
  369. else // no success
  370. Shell:=-1;
  371. {$ifndef FPC_USE_FPEXEC}
  372. FreeShellArgV(p);
  373. {$ENDIF}
  374. end;
  375. {$ifdef FPC_USE_LIBC}
  376. function xfpsystem(p:pchar):cint; cdecl; external clib name 'system';
  377. Function fpSystem(const Command:AnsiString):cint;
  378. begin
  379. fpsystem:=xfpsystem(pchar(command));
  380. end;
  381. {$else}
  382. Function fpSystem(const Command:AnsiString):cint;
  383. {
  384. AnsiString version of Shell
  385. }
  386. var
  387. pid,savedpid : cint;
  388. pstat : cint;
  389. ign,intact,
  390. quitact : SigactionRec;
  391. newsigblock,
  392. oldsigblock : tsigset;
  393. begin { Changes as above }
  394. if command='' then exit(1);
  395. ign.sa_handler:=SigActionHandler(SIG_IGN);
  396. fpsigemptyset(ign.sa_mask);
  397. ign.sa_flags:=0;
  398. fpsigaction(SIGINT, @ign, @intact);
  399. fpsigaction(SIGQUIT, @ign, @quitact);
  400. fpsigemptyset(newsigblock);
  401. fpsigaddset(newsigblock,SIGCHLD);
  402. fpsigprocmask(SIG_BLOCK,newsigblock,oldsigblock);
  403. pid:=fpfork;
  404. if pid=0 then // We are in the Child
  405. begin
  406. fpsigaction(SIGINT,@intact,NIL);
  407. fpsigaction(SIGQUIT,@quitact,NIL);
  408. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  409. fpexecl('/bin/sh',['-c',Command]);
  410. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  411. end
  412. else if (pid<>-1) then // Successfull started
  413. begin
  414. savedpid:=pid;
  415. repeat
  416. pid:=fpwaitpid(savedpid,@pstat,0);
  417. until (pid<>-1) and (fpgeterrno()<>ESysEintr);
  418. if pid=-1 Then
  419. fpsystem:=-1
  420. else
  421. fpsystem:=pstat;
  422. end
  423. else // no success
  424. fpsystem:=-1;
  425. fpsigaction(SIGINT,@intact,NIL);
  426. fpsigaction(SIGQUIT,@quitact,NIL);
  427. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  428. end;
  429. {$endif}
  430. Function WIFSTOPPED(Status: Integer): Boolean;
  431. begin
  432. WIFSTOPPED:=((Status and $FF)=$7F);
  433. end;
  434. Function W_EXITCODE(ReturnCode, Signal: Integer): Integer;
  435. begin
  436. W_EXITCODE:=(ReturnCode shl 8) or Signal;
  437. end;
  438. Function W_STOPCODE(Signal: Integer): Integer;
  439. begin
  440. W_STOPCODE:=(Signal shl 8) or $7F;
  441. end;
  442. {$IFNDEF DONT_READ_TIMEZONE}
  443. { Include timezone handling routines which use /usr/share/timezone info }
  444. {$i timezone.inc}
  445. {$endif}
  446. {******************************************************************************
  447. FileSystem calls
  448. ******************************************************************************}
  449. Function fpFlock (var T : text;mode : cint) : cint;
  450. begin
  451. fpFlock:=fpFlock(TextRec(T).Handle,mode);
  452. end;
  453. Function fpFlock (var F : File;mode : cint) :cint;
  454. begin
  455. fpFlock:=fpFlock(FileRec(F).Handle,mode);
  456. end;
  457. Function SelectText(var T:Text;TimeOut :PTimeval):cint;
  458. Var
  459. F:TfdSet;
  460. begin
  461. if textrec(t).mode=fmclosed then
  462. begin
  463. fpseterrno(ESysEBADF);
  464. exit(-1);
  465. end;
  466. FpFD_ZERO(f);
  467. fpFD_SET(textrec(T).handle,f);
  468. if textrec(T).mode=fminput then
  469. SelectText:=fpselect(textrec(T).handle+1,@f,nil,nil,TimeOut)
  470. else
  471. SelectText:=fpselect(textrec(T).handle+1,nil,@f,nil,TimeOut);
  472. end;
  473. Function SelectText(var T:Text;TimeOut :cint):cint;
  474. var
  475. p : PTimeVal;
  476. tv : TimeVal;
  477. begin
  478. if TimeOut=-1 then
  479. p:=nil
  480. else
  481. begin
  482. tv.tv_Sec:=Timeout div 1000;
  483. tv.tv_Usec:=(Timeout mod 1000)*1000;
  484. p:=@tv;
  485. end;
  486. SelectText:=SelectText(T,p);
  487. end;
  488. {******************************************************************************
  489. Directory
  490. ******************************************************************************}
  491. procedure SeekDir(p:pdir;loc:clong);
  492. begin
  493. if p=nil then
  494. begin
  495. fpseterrno(ESysEBADF);
  496. exit;
  497. end;
  498. {$ifndef bsd}
  499. p^.dd_nextoff:=fplseek(p^.dd_fd,loc,seek_set);
  500. {$endif}
  501. p^.dd_size:=0;
  502. p^.dd_loc:=0;
  503. end;
  504. function TellDir(p:pdir):clong;
  505. begin
  506. if p=nil then
  507. begin
  508. fpseterrno(ESysEBADF);
  509. telldir:=-1;
  510. exit;
  511. end;
  512. telldir:=fplseek(p^.dd_fd,0,seek_cur)
  513. { We could try to use the nextoff field here, but on my 1.2.13
  514. kernel, this gives nothing... This may have to do with
  515. the readdir implementation of libc... I also didn't find any trace of
  516. the field in the kernel code itself, So I suspect it is an artifact of libc.
  517. Michael. }
  518. end;
  519. {******************************************************************************
  520. Pipes/Fifo
  521. ******************************************************************************}
  522. Procedure OpenPipe(var F:Text);
  523. begin
  524. case textrec(f).mode of
  525. fmoutput :
  526. if textrec(f).userdata[1]<>P_OUT then
  527. textrec(f).mode:=fmclosed;
  528. fminput :
  529. if textrec(f).userdata[1]<>P_IN then
  530. textrec(f).mode:=fmclosed;
  531. else
  532. textrec(f).mode:=fmclosed;
  533. end;
  534. end;
  535. Function IOPipe(var F:text):cint;
  536. begin
  537. IOPipe:=0;
  538. case textrec(f).mode of
  539. fmoutput :
  540. begin
  541. { first check if we need something to write, else we may
  542. get a SigPipe when Close() is called (PFV) }
  543. if textrec(f).bufpos>0 then
  544. IOPipe:=fpwrite(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufpos);
  545. end;
  546. fminput : Begin
  547. textrec(f).bufend:=fpread(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufsize);
  548. IOPipe:=textrec(f).bufend;
  549. End;
  550. end;
  551. textrec(f).bufpos:=0;
  552. end;
  553. Function FlushPipe(var F:Text):cint;
  554. begin
  555. FlushPipe:=0;
  556. if (textrec(f).mode=fmoutput) and (textrec(f).bufpos<>0) then
  557. FlushPipe:=IOPipe(f);
  558. textrec(f).bufpos:=0;
  559. end;
  560. Function ClosePipe(var F:text):cint;
  561. begin
  562. textrec(f).mode:=fmclosed;
  563. ClosePipe:=fpclose(textrec(f).handle);
  564. end;
  565. Function AssignPipe(var pipe_in,pipe_out:text):cint;
  566. {
  567. Sets up a pair of file variables, which act as a pipe. The first one can
  568. be read from, the second one can be written to.
  569. }
  570. var
  571. f_in,f_out : cint;
  572. begin
  573. if AssignPipe(f_in,f_out)=-1 then
  574. exit(-1);
  575. { Set up input }
  576. Assign(Pipe_in,'');
  577. Textrec(Pipe_in).Handle:=f_in;
  578. Textrec(Pipe_in).Mode:=fmInput;
  579. Textrec(Pipe_in).userdata[1]:=P_IN;
  580. TextRec(Pipe_in).OpenFunc:=@OpenPipe;
  581. TextRec(Pipe_in).InOutFunc:=@IOPipe;
  582. TextRec(Pipe_in).FlushFunc:=@FlushPipe;
  583. TextRec(Pipe_in).CloseFunc:=@ClosePipe;
  584. { Set up output }
  585. Assign(Pipe_out,'');
  586. Textrec(Pipe_out).Handle:=f_out;
  587. Textrec(Pipe_out).Mode:=fmOutput;
  588. Textrec(Pipe_out).userdata[1]:=P_OUT;
  589. TextRec(Pipe_out).OpenFunc:=@OpenPipe;
  590. TextRec(Pipe_out).InOutFunc:=@IOPipe;
  591. TextRec(Pipe_out).FlushFunc:=@FlushPipe;
  592. TextRec(Pipe_out).CloseFunc:=@ClosePipe;
  593. AssignPipe:=0;
  594. end;
  595. Function AssignPipe(var pipe_in,pipe_out:file):cint;
  596. {
  597. Sets up a pair of file variables, which act as a pipe. The first one can
  598. be read from, the second one can be written to.
  599. If the operation was unsuccesful,
  600. }
  601. var
  602. f_in,f_out : cint;
  603. begin
  604. if AssignPipe(f_in,f_out)=-1 then
  605. exit(-1);
  606. { Set up input }
  607. Assign(Pipe_in,'');
  608. Filerec(Pipe_in).Handle:=f_in;
  609. Filerec(Pipe_in).Mode:=fmInput;
  610. Filerec(Pipe_in).recsize:=1;
  611. Filerec(Pipe_in).userdata[1]:=P_IN;
  612. { Set up output }
  613. Assign(Pipe_out,'');
  614. Filerec(Pipe_out).Handle:=f_out;
  615. Filerec(Pipe_out).Mode:=fmoutput;
  616. Filerec(Pipe_out).recsize:=1;
  617. Filerec(Pipe_out).userdata[1]:=P_OUT;
  618. AssignPipe:=0;
  619. end;
  620. Function PCloseText(Var F:text):cint;
  621. {
  622. May not use @PClose due overloading
  623. }
  624. begin
  625. PCloseText:=PClose(f);
  626. end;
  627. function POpen(var F:text;const Prog:String;rw:char):cint;
  628. {
  629. Starts the program in 'Prog' and makes it's input or out put the
  630. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  631. F, will be read from stdin by the program in 'Prog'. The inverse is true
  632. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  633. read from 'f'.
  634. }
  635. var
  636. pipi,
  637. pipo : text;
  638. pid : pid_t;
  639. pl : ^cint;
  640. {$ifndef FPC_USE_FPEXEC}
  641. pp : ppchar;
  642. {$endif not FPC_USE_FPEXEC}
  643. ret : cint;
  644. begin
  645. rw:=upcase(rw);
  646. if not (rw in ['R','W']) then
  647. begin
  648. FpSetErrno(ESysEnoent);
  649. exit(-1);
  650. end;
  651. if AssignPipe(pipi,pipo)=-1 Then
  652. Exit(-1);
  653. pid:=fpfork; // vfork in FreeBSD.
  654. if pid=-1 then
  655. begin
  656. close(pipi);
  657. close(pipo);
  658. exit(-1);
  659. end;
  660. if pid=0 then
  661. begin
  662. { We're in the child }
  663. if rw='W' then
  664. begin
  665. close(pipo);
  666. ret:=fpdup2(pipi,input);
  667. close(pipi);
  668. if ret=-1 then
  669. halt(127);
  670. end
  671. else
  672. begin
  673. close(pipi);
  674. ret:=fpdup2(pipo,output);
  675. close(pipo);
  676. if ret=-1 then
  677. halt(127);
  678. end;
  679. {$ifdef FPC_USE_FPEXEC}
  680. fpexecl('/bin/sh',['-c',Prog]);
  681. {$else}
  682. pp:=createshellargv(prog);
  683. fpExecve(pp^,pp,envp);
  684. {$endif}
  685. halt(127);
  686. end
  687. else
  688. begin
  689. { We're in the parent }
  690. if rw='W' then
  691. begin
  692. close(pipi);
  693. f:=pipo;
  694. textrec(f).bufptr:=@textrec(f).buffer;
  695. end
  696. else
  697. begin
  698. close(pipo);
  699. f:=pipi;
  700. textrec(f).bufptr:=@textrec(f).buffer;
  701. end;
  702. {Save the process ID - needed when closing }
  703. pl:=@(textrec(f).userdata[2]);
  704. pl^:=pid;
  705. textrec(f).closefunc:=@PCloseText;
  706. end;
  707. ret:=0;
  708. end;
  709. Function POpen(var F:file;const Prog:String;rw:char):cint;
  710. {
  711. Starts the program in 'Prog' and makes it's input or out put the
  712. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  713. F, will be read from stdin by the program in 'Prog'. The inverse is true
  714. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  715. read from 'f'.
  716. }
  717. var
  718. pipi,
  719. pipo : file;
  720. pid : cint;
  721. pl : ^cint;
  722. {$ifndef FPC_USE_FPEXEC}
  723. p,pp : ppchar;
  724. temp : string[255];
  725. {$endif not FPC_USE_FPEXEC}
  726. ret : cint;
  727. begin
  728. rw:=upcase(rw);
  729. if not (rw in ['R','W']) then
  730. begin
  731. FpSetErrno(ESysEnoent);
  732. exit(-1);
  733. end;
  734. ret:=AssignPipe(pipi,pipo);
  735. if ret=-1 then
  736. exit(-1);
  737. pid:=fpfork;
  738. if pid=-1 then
  739. begin
  740. close(pipi);
  741. close(pipo);
  742. exit(-1);
  743. end;
  744. if pid=0 then
  745. begin
  746. { We're in the child }
  747. if rw='W' then
  748. begin
  749. close(pipo);
  750. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  751. close(pipi);
  752. if ret=-1 then
  753. halt(127);
  754. end
  755. else
  756. begin
  757. close(pipi);
  758. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  759. close(pipo);
  760. if ret=1 then
  761. halt(127);
  762. end;
  763. {$ifdef FPC_USE_FPEXEC}
  764. fpexecl('/bin/sh',['-c',Prog]);
  765. {$else}
  766. getmem(pp,sizeof(pchar)*4);
  767. temp:='/bin/sh'#0'-c'#0+prog+#0;
  768. p:=pp;
  769. p^:=@temp[1];
  770. inc(p);
  771. p^:=@temp[9];
  772. inc(p);
  773. p^:=@temp[12];
  774. inc(p);
  775. p^:=Nil;
  776. fpExecve(ansistring('/bin/sh'),pp,envp);
  777. {$endif}
  778. halt(127);
  779. end
  780. else
  781. begin
  782. { We're in the parent }
  783. if rw='W' then
  784. begin
  785. close(pipi);
  786. f:=pipo;
  787. end
  788. else
  789. begin
  790. close(pipo);
  791. f:=pipi;
  792. end;
  793. {Save the process ID - needed when closing }
  794. pl:=@(filerec(f).userdata[2]);
  795. pl^:=pid;
  796. end;
  797. POpen:=0;
  798. end;
  799. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  800. {
  801. Starts the program in 'Prog' and makes its input and output the
  802. other end of two pipes, which are the stdin and stdout of a program
  803. specified in 'Prog'.
  804. streamout can be used to write to the program, streamin can be used to read
  805. the output of the program. See the following diagram :
  806. Parent Child
  807. STreamout --> Input
  808. Streamin <-- Output
  809. Return value is the process ID of the process being spawned, or -1 in case of failure.
  810. }
  811. var
  812. pipi,
  813. pipo : text;
  814. pid : cint;
  815. pl : ^cint;
  816. begin
  817. AssignStream:=-1;
  818. if AssignPipe(streamin,pipo)=-1 Then
  819. exit(-1);
  820. if AssignPipe(pipi,streamout)=-1 Then // shouldn't this close streamin and pipo?
  821. exit(-1);
  822. pid:=fpfork;
  823. if pid=-1 then
  824. begin
  825. close(pipi);
  826. close(pipo);
  827. close (streamin);
  828. close (streamout);
  829. exit;
  830. end;
  831. if pid=0 then
  832. begin
  833. { We're in the child }
  834. { Close what we don't need }
  835. close(streamout);
  836. close(streamin);
  837. if fpdup2(pipi,input)=-1 Then
  838. halt(127);
  839. close(pipi);
  840. If fpdup2(pipo,output)=-1 Then
  841. halt (127);
  842. close(pipo);
  843. fpExecl(Prog,args);
  844. halt(127);
  845. end
  846. else
  847. begin
  848. { we're in the parent}
  849. close(pipo);
  850. close(pipi);
  851. {Save the process ID - needed when closing }
  852. pl:=@(textrec(StreamIn).userdata[2]);
  853. pl^:=pid;
  854. textrec(StreamIn).closefunc:=@PCloseText;
  855. {Save the process ID - needed when closing }
  856. pl:=@(textrec(StreamOut).userdata[2]);
  857. pl^:=pid;
  858. textrec(StreamOut).closefunc:=@PCloseText;
  859. AssignStream:=Pid;
  860. end;
  861. end;
  862. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  863. {
  864. Starts the program in 'prog' and makes its input, output and error output the
  865. other end of three pipes, which are the stdin, stdout and stderr of a program
  866. specified in 'prog'.
  867. StreamOut can be used to write to the program, StreamIn can be used to read
  868. the output of the program, StreamErr reads the error output of the program.
  869. See the following diagram :
  870. Parent Child
  871. StreamOut --> StdIn (input)
  872. StreamIn <-- StdOut (output)
  873. StreamErr <-- StdErr (error output)
  874. }
  875. var
  876. PipeIn, PipeOut, PipeErr: text;
  877. pid: cint;
  878. pl: ^cint;
  879. begin
  880. AssignStream := -1;
  881. // Assign pipes
  882. if AssignPipe(StreamIn, PipeOut)=-1 Then
  883. Exit(-1);
  884. If AssignPipe(StreamErr, PipeErr)=-1 Then
  885. begin
  886. Close(StreamIn);
  887. Close(PipeOut);
  888. exit(-1);
  889. end;
  890. if AssignPipe(PipeIn, StreamOut)=-1 Then
  891. begin
  892. Close(StreamIn);
  893. Close(PipeOut);
  894. Close(StreamErr);
  895. Close(PipeErr);
  896. exit(-1);
  897. end;
  898. // Fork
  899. pid := fpFork;
  900. if pid=-1 then begin
  901. Close(StreamIn);
  902. Close(PipeOut);
  903. Close(StreamErr);
  904. Close(PipeErr);
  905. Close(PipeIn);
  906. Close(StreamOut);
  907. exit(-1);
  908. end;
  909. if pid = 0 then begin
  910. // *** We are in the child ***
  911. // Close what we don not need
  912. Close(StreamOut);
  913. Close(StreamIn);
  914. Close(StreamErr);
  915. // Connect pipes
  916. if fpdup2(PipeIn, Input)=-1 Then
  917. Halt(127);
  918. Close(PipeIn);
  919. if fpdup2(PipeOut, Output)=-1 Then
  920. Halt(127);
  921. Close(PipeOut);
  922. if fpdup2(PipeErr, StdErr)=-1 Then
  923. Halt(127);
  924. Close(PipeErr);
  925. // Execute program
  926. fpExecl(Prog,args);
  927. Halt(127);
  928. end else begin
  929. // *** We are in the parent ***
  930. Close(PipeErr);
  931. Close(PipeOut);
  932. Close(PipeIn);
  933. // Save the process ID - needed when closing
  934. pl := @(TextRec(StreamIn).userdata[2]);
  935. pl^ := pid;
  936. TextRec(StreamIn).closefunc := @PCloseText;
  937. // Save the process ID - needed when closing
  938. pl := @(TextRec(StreamOut).userdata[2]);
  939. pl^ := pid;
  940. TextRec(StreamOut).closefunc := @PCloseText;
  941. // Save the process ID - needed when closing
  942. pl := @(TextRec(StreamErr).userdata[2]);
  943. pl^ := pid;
  944. TextRec(StreamErr).closefunc := @PCloseText;
  945. AssignStream := pid;
  946. end;
  947. end;
  948. {******************************************************************************
  949. General information calls
  950. ******************************************************************************}
  951. {$ifdef Linux}
  952. Function GetDomainName:String; { linux only!}
  953. // domainname is a glibc extension.
  954. {
  955. Get machines domain name. Returns empty string if not set.
  956. }
  957. Var
  958. Sysn : utsname;
  959. begin
  960. If fpUname(sysn)<>0 then
  961. getdomainname:=''
  962. else
  963. getdomainname:=strpas(@Sysn.domain[0]);
  964. end;
  965. {$endif}
  966. {$ifdef BSD}
  967. function intGetDomainName(Name:PChar; NameLen:Cint):cint;
  968. {$ifndef FPC_USE_LIBC}
  969. external name 'FPC_SYSC_GETDOMAINNAME';
  970. {$else FPC_USE_LIBC}
  971. cdecl; external clib name 'getdomainname';
  972. {$endif FPC_USE_LIBC}
  973. Function GetDomainName:String; { linux only!}
  974. // domainname is a glibc extension.
  975. {
  976. Get machines domain name. Returns empty string if not set.
  977. }
  978. begin
  979. if intGetDomainName(@getdomainname[1],255)=-1 then
  980. getdomainname:=''
  981. else
  982. getdomainname[0]:=chr(strlen(@getdomainname[1]));
  983. end;
  984. {$endif}
  985. Function GetHostName:String;
  986. {
  987. Get machines name. Returns empty string if not set.
  988. }
  989. Var
  990. Sysn : utsname;
  991. begin
  992. If fpuname(sysn)=-1 then
  993. gethostname:=''
  994. else
  995. gethostname:=strpas(@Sysn.nodename[0]);
  996. end;
  997. {******************************************************************************
  998. Signal handling calls
  999. ******************************************************************************}
  1000. procedure SigRaise(sig:integer);
  1001. begin
  1002. fpKill(fpGetPid,Sig);
  1003. end;
  1004. {******************************************************************************
  1005. Utility calls
  1006. ******************************************************************************}
  1007. Function FSearch(const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  1008. {
  1009. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1010. returns an empty string if not found. Wildcards are NOT allowed.
  1011. If dirlist is empty, it is set to '.'
  1012. This function tries to make FSearch use ansistrings, and decrease
  1013. stringhandling overhead at the same time.
  1014. }
  1015. Var
  1016. mydir,NewDir : ansistring;
  1017. p1 : cint;
  1018. Info : Stat;
  1019. i,j : cint;
  1020. p : pchar;
  1021. Begin
  1022. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1023. Dirlist:='.:'+dirlist; {Make sure current dir is first to be searched.}
  1024. if CurrentDirStrategy=CurrentDirectoryLast Then
  1025. Dirlist:=dirlist+':.'; {Make sure current dir is last to be searched.}
  1026. {Replace ':' and ';' with #0}
  1027. for p1:=1 to length(dirlist) do
  1028. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1029. dirlist[p1]:=#0;
  1030. {Check for WildCards}
  1031. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1032. FSearch:='' {No wildcards allowed in these things.}
  1033. Else
  1034. Begin
  1035. p:=pchar(dirlist);
  1036. i:=length(dirlist);
  1037. j:=1;
  1038. Repeat
  1039. mydir:=ansistring(p);
  1040. if (length(mydir)>0) and (mydir[length(mydir)]<>'/') then
  1041. mydir:=mydir+'/';
  1042. NewDir:=mydir+Path;
  1043. if (FpStat(NewDir,Info)>=0) and
  1044. (not fpS_ISDIR(Info.st_Mode)) then
  1045. Begin
  1046. If Pos('./',NewDir)=1 Then
  1047. Delete(NewDir,1,2);
  1048. {DOS strips off an initial .\}
  1049. End
  1050. Else
  1051. NewDir:='';
  1052. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1053. if p^=#0 then inc(p);
  1054. Until (j>=i) or (Length(NewDir) > 0);
  1055. FSearch:=NewDir;
  1056. End;
  1057. End;
  1058. Function FSearch(const path:AnsiString;dirlist:Ansistring):AnsiString;
  1059. Begin
  1060. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1061. End;
  1062. {--------------------------------
  1063. Stat.Mode Macro's
  1064. --------------------------------}
  1065. Initialization
  1066. {$IFNDEF DONT_READ_TIMEZONE}
  1067. InitLocalTime;
  1068. {$endif}
  1069. finalization
  1070. {$IFNDEF DONT_READ_TIMEZONE}
  1071. DoneLocalTime;
  1072. {$endif}
  1073. End.