unix.pp 34 KB

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