unix.pp 32 KB

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