unix.pp 34 KB

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