2
0

unix.pp 33 KB

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