unix.pp 32 KB

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