unix.pp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  1. {
  2. $Id$
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by Michael Van Canneyt,
  5. BSD parts (c) 2000 by Marco van de Voort
  6. members of the Free Pascal development team.
  7. See the file COPYING.FPC, included in this distribution,
  8. for details about the copyright.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY;without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  12. **********************************************************************}
  13. Unit Unix;
  14. Interface
  15. Uses UnixUtil,BaseUnix;
  16. {$define POSIXWORKAROUND}
  17. { Get Types and Constants }
  18. {$i sysconst.inc}
  19. {$ifdef FreeBSD}
  20. {$i systypes.inc}
  21. {$else}
  22. {$ifndef FPC_USE_LIBC}
  23. {$i systypes.inc}
  24. {$endif FPC_USE_LIBC}
  25. {$endif}
  26. {Get error numbers, some more signal definitions and other OS dependant
  27. types (that are not POSIX) }
  28. {i errno.inc}
  29. {$I signal.inc}
  30. {$i ostypes.inc}
  31. {********************
  32. File
  33. ********************}
  34. Const
  35. P_IN = 1; // pipes (?)
  36. P_OUT = 2;
  37. Const
  38. LOCK_SH = 1; // flock constants ?
  39. LOCK_EX = 2;
  40. LOCK_UN = 8;
  41. LOCK_NB = 4;
  42. Type
  43. Tpipe = baseunix.tfildes; // compability.
  44. pglob = ^tglob;
  45. tglob = record
  46. name : pchar;
  47. next : pglob;
  48. end;
  49. {******************************************************************************
  50. Procedure/Functions
  51. ******************************************************************************}
  52. {**************************
  53. Time/Date Handling
  54. ***************************}
  55. var
  56. tzdaylight : boolean;
  57. tzname : array[boolean] of pchar;
  58. { timezone support }
  59. procedure GetLocalTimezone(timer:cint;var leap_correct,leap_hit:cint);
  60. procedure GetLocalTimezone(timer:cint);
  61. procedure ReadTimezoneFile(fn:string);
  62. function GetTimezoneFile:string;
  63. Function GetEpochTime: cint;
  64. procedure GetTime (var hour,min,sec,msec,usec:word);
  65. procedure GetTime (var hour,min,sec,sec100:word);
  66. procedure GetTime (var hour,min,sec:word);
  67. Procedure GetDate (Var Year,Month,Day:Word);
  68. Procedure GetDateTime (Var Year,Month,Day,hour,minute,second:Word);
  69. function SetTime (Hour,Min,Sec:word) : Boolean;
  70. function SetDate (Year,Month,Day:Word) : Boolean;
  71. function SetDateTime (Year,Month,Day,hour,minute,second:Word) : Boolean;
  72. {**************************
  73. Process Handling
  74. ***************************}
  75. function CreateShellArgV (const prog:string):ppchar;
  76. function CreateShellArgV (const prog:Ansistring):ppchar;
  77. procedure FreeShellArgV(p:ppchar);
  78. // These are superceded by the fpExec functions that are more pascallike
  79. // and have less limitations. However I'll leave them in for a while, to
  80. // not frustrate things too much
  81. // but they might not make it to 2.0
  82. Function Execv (const path:pathstr;args:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  83. Function Execv (const path: AnsiString;args:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  84. Function Execvp (Path: Pathstr;Args:ppchar;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  85. Function Execvp (Path: AnsiString; Args:ppchar;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  86. Function Execl (const Todo: String):cint; {$ifndef ver1_0}deprecated; {$endif}
  87. Function Execl (const Todo: Ansistring):cint; {$ifndef ver1_0}deprecated; {$endif}
  88. Function Execle (Todo: String;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  89. Function Execle (Todo: AnsiString;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  90. Function Execlp (Todo: string;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  91. Function Execlp (Todo: Ansistring;Ep:ppchar):cint; {$ifndef ver1_0}deprecated; {$endif}
  92. //
  93. // These are much better, in nearly all ways.
  94. //
  95. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  96. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  97. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  98. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  99. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  100. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  101. Function Shell (const Command:String):cint;
  102. Function Shell (const Command:AnsiString):cint;
  103. Function fpSystem(const Command:AnsiString):cint;
  104. 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}
  105. Function WIFSTOPPED (Status: Integer): Boolean;
  106. Function W_EXITCODE (ReturnCode, Signal: Integer): Integer;
  107. Function W_STOPCODE (Signal: Integer): Integer;
  108. {**************************
  109. File Handling
  110. ***************************}
  111. {$ifndef FPC_USE_LIBC} // defined using cdecl for libc.
  112. Function fsync (fd : cint) : cint;
  113. Function Flock (fd,mode : cint) : cint ;
  114. Function fStatFS (Fd: cint;Var Info:tstatfs):cint;
  115. Function StatFS (Path:pchar;Var Info:tstatfs):cint;
  116. {$endif}
  117. Function Flock (var T : text;mode : cint) : cint;
  118. Function Flock (var F : File;mode : cint) : cint;
  119. Function SelectText (var T:Text;TimeOut :PTimeVal):cint;
  120. Function SelectText (var T:Text;TimeOut :cint):cint;
  121. {**************************
  122. Directory Handling
  123. ***************************}
  124. procedure SeekDir(p:pdir;loc:clong);
  125. function TellDir(p:pdir):clong;
  126. {**************************
  127. Pipe/Fifo/Stream
  128. ***************************}
  129. Function AssignPipe (var pipe_in,pipe_out:cint):cint;
  130. Function AssignPipe (var pipe_in,pipe_out:text):cint;
  131. Function AssignPipe (var pipe_in,pipe_out:file):cint;
  132. //Function PClose (Var F:text) : cint;
  133. //Function PClose (Var F:file) : cint;
  134. Function POpen (var F:text;const Prog:String;rw:char):cint;
  135. Function POpen (var F:file;const Prog:String;rw:char):cint;
  136. function AssignStream(Var StreamIn,Streamout:text;Const Prog:String) : cint;
  137. function AssignStream(var StreamIn, StreamOut, StreamErr: Text; const prog: String): cint;
  138. {$ifndef BSD}
  139. Function GetDomainName:String;
  140. Function GetHostName:String;
  141. {$endif}
  142. {**************************
  143. Memory functions
  144. ***************************}
  145. const
  146. PROT_READ = $1; { page can be read }
  147. PROT_WRITE = $2; { page can be written }
  148. PROT_EXEC = $4; { page can be executed }
  149. PROT_NONE = $0; { page can not be accessed }
  150. MAP_SHARED = $1; { Share changes }
  151. // MAP_PRIVATE = $2; { Changes are private }
  152. MAP_TYPE = $f; { Mask for type of mapping }
  153. MAP_FIXED = $10; { Interpret addr exactly }
  154. // MAP_ANONYMOUS = $20; { don't use a file }
  155. {$ifdef Linux}
  156. MAP_GROWSDOWN = $100; { stack-like segment }
  157. MAP_DENYWRITE = $800; { ETXTBSY }
  158. MAP_EXECUTABLE = $1000; { mark it as an executable }
  159. MAP_LOCKED = $2000; { pages are locked }
  160. MAP_NORESERVE = $4000; { don't check for reservations }
  161. {$else}
  162. {$ifdef FreeBSD}
  163. // FreeBSD defines MAP_COPY=MAP_PRIVATE=$2;
  164. MAP_FILE = $0000; { map from file (default) }
  165. MAP_ANON = $1000; { allocated from memory, swap space }
  166. MAP_RENAME = $0020; { Sun: rename private pages to file }
  167. MAP_NORESERVE = $0040; { Sun: don't reserve needed swap area }
  168. MAP_INHERIT = $0080; { region is retained after exec }
  169. MAP_NOEXTEND = $0100; { for MAP_FILE, don't change file size }
  170. MAP_HASSEMAPHORE = $0200; { region may contain semaphores }
  171. MAP_STACK = $0400; { region grows down, like a stack }
  172. MAP_NOSYNC = $0800; { page to but do not sync underlying file}
  173. MAP_NOCORE = $20000;{ dont include these pages in a coredump}
  174. {$endif}
  175. {$endif}
  176. {**************************
  177. Utility functions
  178. ***************************}
  179. Type
  180. TFSearchOption = (NoCurrentDirectory,
  181. CurrentDirectoryFirst,
  182. CurrentDirectoryLast);
  183. Function FExpand (Const Path: PathStr):PathStr;
  184. Function FSearch (const path:pathstr;dirlist:string):pathstr;
  185. Function FSearch (const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  186. Function FSearch (const path:AnsiString;dirlist:AnsiString):AnsiString;
  187. Function Glob (Const path:pathstr):pglob;
  188. Procedure Globfree (var p:pglob);
  189. procedure SigRaise (sig:integer);
  190. {$ifdef FPC_USE_LIBC}
  191. const clib = 'c';
  192. {$i unxdeclh.inc}
  193. {$else}
  194. {$i unxsysch.inc} // calls used in system and not reexported from baseunix
  195. {$endif}
  196. {******************************************************************************
  197. Implementation
  198. ******************************************************************************}
  199. {$i unxovlh.inc}
  200. Implementation
  201. Uses Strings{$ifndef FPC_USE_LIBC},Syscall{$endif};
  202. {$i unxovl.inc}
  203. {$ifndef FPC_USE_LIBC}
  204. {$i syscallh.inc}
  205. {$i ossysch.inc}
  206. {$i unxsysc.inc}
  207. {$endif}
  208. { Get the definitions of textrec and filerec }
  209. {$i textrec.inc}
  210. {$i filerec.inc}
  211. {$ifndef FPC_USE_LIBC}
  212. { Raw System calls are in Syscalls.inc}
  213. {$ifdef Linux} // Linux has more "oldlinux" compability.
  214. {$i sysc11.inc}
  215. {$else}
  216. {$i syscalls.inc}
  217. {$endif}
  218. {$endif}
  219. {$i unixsysc.inc} {Has platform specific libc part under ifdef, besides
  220. syscalls}
  221. Function getenv(name:string):Pchar; external name 'FPC_SYSC_FPGETENV';
  222. {******************************************************************************
  223. Process related calls
  224. ******************************************************************************}
  225. { Most calls of WaitPID do not handle the result correctly, this funktion treats errors more correctly }
  226. 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}
  227. var ret,r,s : cint;
  228. begin
  229. s:=$7F00;
  230. repeat
  231. r:=fpWaitPid(Pid,@s,0);
  232. if (r=-1) and (fpgeterrno=ESysEIntr) Then
  233. r:=0;
  234. until (r<>0);
  235. if (r=-1) or (r=0) then // 0 is not a valid return and should never occur (it means status invalid when using WNOHANG)
  236. WaitProcess:=-1 // return -1 to indicate an error. fpwaitpid updated it.
  237. else
  238. begin
  239. {$ifndef Solaris}
  240. { at least correct for Linux and Darwin (JM) }
  241. if (s and $7F)=0 then // Only this is a valid returncode
  242. {$else}
  243. if (s and $FF)=0 then // Only this is a valid returncode
  244. {$endif}
  245. WaitProcess:=s shr 8
  246. else if (s>0) then // Until now there is not use of the highest bit , but check this for the future
  247. WaitProcess:=-s // normal case
  248. else
  249. WaitProcess:=s; // s<0 should not occur, but wie return also a negativ value
  250. end;
  251. end;
  252. function InternalCreateShellArgV(cmd:pChar; len:cint):ppchar;
  253. {
  254. Create an argv which executes a command in a shell using /bin/sh -c
  255. }
  256. const Shell = '/bin/sh'#0'-c'#0;
  257. var
  258. pp,p : ppchar;
  259. // temp : string; !! Never pass a local var back!!
  260. begin
  261. getmem(pp,4*4);
  262. p:=pp;
  263. p^:=@Shell[1];
  264. inc(p);
  265. p^:=@Shell[9];
  266. inc(p);
  267. getmem(p^,len+1);
  268. move(cmd^,p^^,len);
  269. pchar(p^)[len]:=#0;
  270. inc(p);
  271. p^:=Nil;
  272. InternalCreateShellArgV:=pp;
  273. end;
  274. function CreateShellArgV(const prog:string):ppchar;
  275. begin
  276. CreateShellArgV:=InternalCreateShellArgV(@prog[1],length(prog));
  277. end;
  278. function CreateShellArgV(const prog:Ansistring):ppchar;
  279. {
  280. Create an argv which executes a command in a shell using /bin/sh -c
  281. using a AnsiString;
  282. }
  283. begin
  284. CreateShellArgV:=InternalCreateShellArgV(@prog[1],length(prog)); // if ppc works like delphi this also work when @prog[1] is invalid (len=0)
  285. end;
  286. procedure FreeShellArgV(p:ppchar);
  287. begin
  288. if (p<>nil) then begin
  289. freemem(p[2]);
  290. freemem(p);
  291. end;
  292. end;
  293. Function Execv(const path: AnsiString;args:ppchar):cint;
  294. {
  295. Overloaded ansistring version.
  296. }
  297. begin
  298. Execv:=fpExecVe(Path,Args,envp);
  299. end;
  300. Function Execvp(Path: AnsiString; Args:ppchar;Ep:ppchar):cint;
  301. {
  302. Overloaded ansistring version
  303. }
  304. var
  305. thepath : Ansistring;
  306. begin
  307. if path[1]<>'/' then
  308. begin
  309. Thepath:=strpas(fpgetenv('PATH'));
  310. if thepath='' then
  311. thepath:='.';
  312. Path:=FSearch(path,thepath)
  313. end
  314. else
  315. Path:='';
  316. if Path='' then
  317. Begin
  318. fpsetErrno(ESysEnoEnt);
  319. Exit(-1);
  320. end
  321. else
  322. Execvp:=fpExecve(Path,args,ep);
  323. end;
  324. Function Execv(const path:pathstr;args:ppchar):cint;
  325. {
  326. Replaces the current program by the program specified in path,
  327. arguments in args are passed to Execve.
  328. the current environment is passed on.
  329. }
  330. begin
  331. Execv:=fpExecve(path,args,envp);
  332. end;
  333. Function Execvp(Path:Pathstr;Args:ppchar;Ep:ppchar):cint;
  334. {
  335. This does the same as Execve, only it searches the PATH environment
  336. for the place of the Executable, except when Path starts with a slash.
  337. if the PATH environment variable is unavailable, the path is set to '.'
  338. }
  339. var
  340. thepath : string;
  341. begin
  342. if path[1]<>'/' then
  343. begin
  344. Thepath:=strpas(fpgetenv('PATH'));
  345. if thepath='' then
  346. thepath:='.';
  347. Path:=FSearch(path,thepath)
  348. end
  349. else
  350. Path:='';
  351. if Path='' then
  352. Begin
  353. fpsetErrno(ESysEnoEnt);
  354. Exit(-1);
  355. end
  356. else
  357. execvp:=fpExecve(Path,args,ep);
  358. end;
  359. Function Execle(Todo:string;Ep:ppchar):cint;
  360. {
  361. This procedure takes the string 'Todo', parses it for command and
  362. command options, and Executes the command with the given options.
  363. The string 'Todo' shoud be of the form 'command options', options
  364. separated by commas.
  365. the PATH environment is not searched for 'command'.
  366. The specified environment(in 'ep') is passed on to command
  367. }
  368. var
  369. p : ppchar;
  370. begin
  371. p:=StringToPPChar(ToDo,0);
  372. if (p=nil) or (p^=nil) then
  373. Begin
  374. fpsetErrno(ESysEnoEnt);
  375. Exit(-1);
  376. end
  377. else
  378. execle:=fpExecVE(p^,p,EP);
  379. end;
  380. function Execle(Todo:AnsiString;Ep:ppchar):cint;
  381. {
  382. This procedure takes the string 'Todo', parses it for command and
  383. command options, and Executes the command with the given options.
  384. The string 'Todo' shoud be of the form 'command options', options
  385. separated by commas.
  386. the PATH environment is not searched for 'command'.
  387. The specified environment(in 'ep') is passed on to command
  388. }
  389. var
  390. p : ppchar;
  391. begin
  392. p:=StringToPPChar(ToDo,0);
  393. if (p=nil) or (p^=nil) then
  394. Begin
  395. fpsetErrno(ESysEnoEnt);
  396. Exit(-1);
  397. end;
  398. ExecLe:=fpExecVE(p^,p,EP);
  399. end;
  400. Function Execl(const Todo:string):cint;
  401. {
  402. This procedure takes the string 'Todo', parses it for command and
  403. command options, and Executes the command with the given options.
  404. The string 'Todo' shoud be of the form 'command options', options
  405. separated by commas.
  406. the PATH environment is not searched for 'command'.
  407. The current environment is passed on to command
  408. }
  409. begin
  410. Execl:=ExecLE(ToDo,EnvP);
  411. end;
  412. Function Execlp(Todo:string;Ep:ppchar):cint;
  413. {
  414. This procedure takes the string 'Todo', parses it for command and
  415. command options, and Executes the command with the given options.
  416. The string 'Todo' shoud be of the form 'command options', options
  417. separated by commas.
  418. the PATH environment is searched for 'command'.
  419. The specified environment (in 'ep') is passed on to command
  420. }
  421. var
  422. p : ppchar;
  423. begin
  424. p:=StringToPPchar(todo,0);
  425. if (p=nil) or (p^=nil) then
  426. Begin
  427. fpsetErrno(ESysEnoEnt);
  428. Exit(-1);
  429. end;
  430. Execlp:=ExecVP(StrPas(p^),p,EP);
  431. end;
  432. Function Execlp(Todo: Ansistring;Ep:ppchar):cint;
  433. {
  434. Overloaded ansistring version.
  435. }
  436. var
  437. p : ppchar;
  438. begin
  439. p:=StringToPPchar(todo,0);
  440. if (p=nil) or (p^=nil) then
  441. Begin
  442. fpsetErrno(ESysEnoEnt);
  443. Exit(-1);
  444. end;
  445. execlp:=ExecVP(StrPas(p^),p,EP);
  446. end;
  447. function intFpExecVEMaybeP (Const PathName:AnsiString;Args,MyEnv:ppchar;SearchPath:Boolean):cint;
  448. // does an ExecVE, but still has to handle P
  449. // execv variants call this directly, execl variants indirectly via
  450. // intfpexecl
  451. Var
  452. NewCmd : ansistring;
  453. ThePath : AnsiString;
  454. Error : cint;
  455. NrParam : longint;
  456. Begin
  457. If SearchPath and (pos('/',pathname)=0) Then
  458. Begin
  459. // The above could be better. (check if not escaped/quoted '/' 's) ?
  460. // (Jilles says this is ok)
  461. // Stevens says only search if newcmd contains no '/'
  462. // fsearch is not ansistring clean yet.
  463. ThePath:=fpgetenv('PATH');
  464. if thepath='' then
  465. thepath:='.'; // FreeBSD uses _PATH_DEFPATH = /usr/bin:/bin
  466. // but a quick check showed that _PATH_DEFPATH
  467. // varied from OS to OS
  468. newcmd:=FSearch(pathname,thepath,NoCurrentDirectory);
  469. // FreeBSD libc keeps on trying till a file is successfully run.
  470. // Stevens says "try each path prefix"
  471. // execp puts newcmd here.
  472. args^:=pchar(newcmd);
  473. End;
  474. // repeat
  475. // if searchpath then args^:=pchar(commandtorun)
  476. IntFpExecVEMaybeP:=fpExecVE(Args^,Args,MyEnv);
  477. {
  478. // Code that if exec fails due to permissions, tries to run it with sh
  479. // Should we deallocate p on fail? -> no fpexit is run no matter what
  480. //
  481. }
  482. // if intfpexecvemaybep=-1 then zoekvolgende file.
  483. // until (Goexit) or SearchExit;
  484. {
  485. If IntFpExec=-1 Then
  486. Begin
  487. Error:=fpGetErrno
  488. Case Error of
  489. ESysE2Big : Exit(-1);
  490. ESysELoop,
  491. : Exit(-1);
  492. }
  493. end;
  494. function intFpExecl (Const PathName:AnsiString;const s:array of ansistring;MyEnv:ppchar;SearchPath:Boolean):cint;
  495. { Handles the array of ansistring -> ppchar conversion.
  496. Base for the the "l" variants.
  497. }
  498. var p:ppchar;
  499. begin
  500. If PathName='' Then
  501. Begin
  502. fpsetErrno(ESysEnoEnt);
  503. Exit(-1); // Errno?
  504. End;
  505. p:=ArrayStringToPPchar(s,1);
  506. if p=NIL Then
  507. Begin
  508. GetMem(p,2*sizeof(pchar));
  509. if p=nil then
  510. begin
  511. {$ifdef xunix}
  512. fpseterrno(ESysEnoMem);
  513. {$endif}
  514. fpseterrno(ESysEnoEnt);
  515. exit(-1);
  516. end;
  517. p[1]:=nil;
  518. End;
  519. p^:=pchar(PathName);
  520. IntFPExecL:=intFpExecVEMaybeP(PathName,p,MyEnv,SearchPath);
  521. // If we come here, no attempts were executed successfully.
  522. Freemem(p);
  523. end;
  524. function FpExecLE (Const PathName:AnsiString;const S:Array Of AnsiString;MyEnv:ppchar):cint;
  525. Begin
  526. FpExecLE:=intFPExecl(PathName,s,MyEnv,false);
  527. End;
  528. function FpExecL(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  529. Begin
  530. FpExecL:=intFPExecl(PathName,S,EnvP,false);
  531. End;
  532. function FpExecLP(Const PathName:AnsiString;const S:Array Of AnsiString):cint;
  533. Begin
  534. FpExecLP:=intFPExecl(PathName,S,EnvP,True);
  535. End;
  536. function FpExecV(Const PathName:AnsiString;args:ppchar):cint;
  537. Begin
  538. fpexecV:=intFpExecVEMaybeP (PathName,args,envp,false);
  539. End;
  540. function FpExecVP(Const PathName:AnsiString;args:ppchar):cint;
  541. Begin
  542. fpexecVP:=intFpExecVEMaybeP (PathName,args,envp,true);
  543. End;
  544. function FpExecVPE(Const PathName:AnsiString;args,env:ppchar):cint;
  545. Begin
  546. fpexecVPE:=intFpExecVEMaybeP (PathName,args,env,true);
  547. End;
  548. // exect and execvP (ExecCapitalP) are not implement
  549. // Non POSIX anyway.
  550. // Exect turns on tracing for the process
  551. // execvP has the searchpath as array of ansistring ( const char *search_path)
  552. {$define FPC_USE_FPEXEC}
  553. Function Shell(const Command:String):cint;
  554. {
  555. Executes the shell, and passes it the string Command. (Through /bin/sh -c)
  556. The current environment is passed to the shell.
  557. It waits for the shell to exit, and returns its exit status.
  558. If the Exec call failed exit status 127 is reported.
  559. }
  560. { Changed the structure:
  561. - the previous version returns an undefinied value if fork fails
  562. - it returns the status of Waitpid instead of the Process returnvalue (see the doc to Shell)
  563. - it uses exit(127) not ExitProc (The Result in pp386: going on Compiling in 2 processes!)
  564. - ShellArgs are now released
  565. - The Old CreateShellArg gives back pointers to a local var
  566. }
  567. var
  568. {$ifndef FPC_USE_FPEXEC}
  569. p : ppchar;
  570. {$endif}
  571. pid : cint;
  572. begin
  573. {$ifndef FPC_USE_FPEXEC}
  574. p:=CreateShellArgv(command);
  575. {$endif}
  576. pid:=fpfork;
  577. if pid=0 then // We are in the Child
  578. begin
  579. {This is the child.}
  580. {$ifndef FPC_USE_FPEXEC}
  581. fpExecve(p^,p,envp);
  582. {$else}
  583. fpexecl('/bin/sh',['-c',Command]);
  584. {$endif}
  585. fpExit(127); // was Exit(127)
  586. end
  587. else if (pid<>-1) then // Successfull started
  588. Shell:=WaitProcess(pid)
  589. else // no success
  590. Shell:=-1; // indicate an error
  591. {$ifndef FPC_USE_FPEXEC}
  592. FreeShellArgV(p);
  593. {$endif}
  594. end;
  595. Function Shell(const Command:AnsiString):cint;
  596. {
  597. AnsiString version of Shell
  598. }
  599. var
  600. {$ifndef FPC_USE_FPEXEC}
  601. p : ppchar;
  602. {$endif}
  603. pid : cint;
  604. begin { Changes as above }
  605. {$ifndef FPC_USE_FPEXEC}
  606. p:=CreateShellArgv(command);
  607. {$endif}
  608. pid:=fpfork;
  609. if pid=0 then // We are in the Child
  610. begin
  611. {$ifdef FPC_USE_FPEXEC}
  612. fpexecl('/bin/sh',['-c',Command]);
  613. {$else}
  614. fpExecve(p^,p,envp);
  615. {$endif}
  616. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  617. end
  618. else if (pid<>-1) then // Successfull started
  619. Shell:=WaitProcess(pid)
  620. else // no success
  621. Shell:=-1;
  622. {$ifndef FPC_USE_FPEXEC}
  623. FreeShellArgV(p);
  624. {$ENDIF}
  625. end;
  626. {$ifdef FPC_USE_LIBC}
  627. function xfpsystem(p:pchar):cint; cdecl; external clib name 'system';
  628. Function fpSystem(const Command:AnsiString):cint;
  629. begin
  630. fpsystem:=xfpsystem(pchar(command));
  631. end;
  632. {$else}
  633. Function fpSystem(const Command:AnsiString):cint;
  634. {
  635. AnsiString version of Shell
  636. }
  637. var
  638. pid,savedpid : cint;
  639. pstat : cint;
  640. ign,intact,
  641. quitact : SigactionRec;
  642. newsigblock,
  643. oldsigblock : tsigset;
  644. begin { Changes as above }
  645. if command='' then exit(1);
  646. {$ifdef FreeBSD}
  647. ign.sa_handler:=TSigAction(SIG_IGN);
  648. {$else}
  649. ign.sa_handler:=SignalHandler(SIG_IGN);
  650. {$endif}
  651. fpsigemptyset(ign.sa_mask);
  652. ign.sa_flags:=0;
  653. fpsigaction(SIGINT, @ign, @intact);
  654. fpsigaction(SIGQUIT, @ign, @quitact);
  655. fpsigemptyset(newsigblock);
  656. fpsigaddset(newsigblock,SIGCHLD);
  657. fpsigprocmask(SIG_BLOCK,newsigblock,oldsigblock);
  658. pid:=fpfork;
  659. if pid=0 then // We are in the Child
  660. begin
  661. fpsigaction(SIGINT,@intact,NIL);
  662. fpsigaction(SIGQUIT,@quitact,NIL);
  663. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  664. fpexecl('/bin/sh',['-c',Command]);
  665. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  666. end
  667. else if (pid<>-1) then // Successfull started
  668. begin
  669. savedpid:=pid;
  670. repeat
  671. pid:=fpwaitpid(savedpid,@pstat,0);
  672. until (pid<>-1) and (fpgeterrno()<>ESysEintr);
  673. if pid=-1 Then
  674. fpsystem:=-1
  675. else
  676. fpsystem:=pstat;
  677. end
  678. else // no success
  679. fpsystem:=-1;
  680. fpsigaction(SIGINT,@intact,NIL);
  681. fpsigaction(SIGQUIT,@quitact,NIL);
  682. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  683. end;
  684. {$endif}
  685. Function WIFSTOPPED(Status: Integer): Boolean;
  686. begin
  687. WIFSTOPPED:=((Status and $FF)=$7F);
  688. end;
  689. Function W_EXITCODE(ReturnCode, Signal: Integer): Integer;
  690. begin
  691. W_EXITCODE:=(ReturnCode shl 8) or Signal;
  692. end;
  693. Function W_STOPCODE(Signal: Integer): Integer;
  694. begin
  695. W_STOPCODE:=(Signal shl 8) or $7F;
  696. end;
  697. {******************************************************************************
  698. Date and Time related calls
  699. ******************************************************************************}
  700. Function GetEpochTime: cint;
  701. {
  702. Get the number of seconds since 00:00, January 1 1970, GMT
  703. the time NOT corrected any way
  704. }
  705. begin
  706. GetEpochTime:=fptime;
  707. end;
  708. procedure GetTime(var hour,min,sec,msec,usec:word);
  709. {
  710. Gets the current time, adjusted to local time
  711. }
  712. var
  713. year,day,month:Word;
  714. tz:timeval;
  715. begin
  716. fpgettimeofday(@tz,nil);
  717. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  718. msec:=tz.tv_usec div 1000;
  719. usec:=tz.tv_usec mod 1000;
  720. end;
  721. procedure GetTime(var hour,min,sec,sec100:word);
  722. {
  723. Gets the current time, adjusted to local time
  724. }
  725. var
  726. usec : word;
  727. begin
  728. gettime(hour,min,sec,sec100,usec);
  729. sec100:=sec100 div 10;
  730. end;
  731. Procedure GetTime(Var Hour,Min,Sec:Word);
  732. {
  733. Gets the current time, adjusted to local time
  734. }
  735. var
  736. msec,usec : Word;
  737. Begin
  738. gettime(hour,min,sec,msec,usec);
  739. End;
  740. Procedure GetDate(Var Year,Month,Day:Word);
  741. {
  742. Gets the current date, adjusted to local time
  743. }
  744. var
  745. hour,minute,second : word;
  746. Begin
  747. EpochToLocal(fptime,year,month,day,hour,minute,second);
  748. End;
  749. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  750. {
  751. Gets the current date, adjusted to local time
  752. }
  753. Begin
  754. EpochToLocal(fptime,year,month,day,hour,minute,second);
  755. End;
  756. {$ifndef BSD} // this can be done nicer, but I still have
  757. // to think about what to do with this func.
  758. {$ifdef linux}
  759. {$ifdef FPC_USE_LIBC}
  760. function intstime (t:ptime_t):cint; external name 'stime';
  761. {$endif}
  762. Function stime (t : cint) : boolean;
  763. begin
  764. {$ifdef FPC_USE_LIBC}
  765. stime:=intstime(@t)=0;
  766. {$else}
  767. stime:=do_SysCall(Syscall_nr_stime,cint(@t))=0;
  768. {$endif}
  769. end;
  770. {$endif}
  771. {$endif}
  772. {$ifdef BSD}
  773. Function stime (t : cint) : Boolean;
  774. begin
  775. end;
  776. {$endif}
  777. Function SetTime(Hour,Min,Sec:word) : boolean;
  778. var
  779. Year, Month, Day : Word;
  780. begin
  781. GetDate (Year, Month, Day);
  782. SetTime:=stime ( LocalToEpoch ( Year, Month, Day, Hour, Min, Sec ) );
  783. end;
  784. Function SetDate(Year,Month,Day:Word) : boolean;
  785. var
  786. Hour, Minute, Second, Sec100 : Word;
  787. begin
  788. GetTime ( Hour, Minute, Second, Sec100 );
  789. SetDate:=stime ( LocalToEpoch ( Year, Month, Day, Hour, Minute, Second ) );
  790. end;
  791. Function SetDateTime(Year,Month,Day,hour,minute,second:Word) : Boolean;
  792. begin
  793. SetDateTime:=stime ( LocalToEpoch ( Year, Month, Day, Hour, Minute, Second ) );
  794. end;
  795. { Include timezone handling routines which use /usr/share/timezone info }
  796. {$i timezone.inc}
  797. {******************************************************************************
  798. FileSystem calls
  799. ******************************************************************************}
  800. Function Execl(const Todo:Ansistring):cint;
  801. {
  802. Overloaded AnsiString Version of ExecL.
  803. }
  804. begin
  805. Execl:=ExecLE(ToDo,EnvP);
  806. end;
  807. Function Flock (var T : text;mode : cint) : cint;
  808. begin
  809. Flock:=Flock(TextRec(T).Handle,mode);
  810. end;
  811. Function Flock (var F : File;mode : cint) :cint;
  812. begin
  813. Flock:=Flock(FileRec(F).Handle,mode);
  814. end;
  815. Function SelectText(var T:Text;TimeOut :PTimeval):cint;
  816. Var
  817. F:TfdSet;
  818. begin
  819. if textrec(t).mode=fmclosed then
  820. begin
  821. fpseterrno(ESysEBADF);
  822. exit(-1);
  823. end;
  824. FpFD_ZERO(f);
  825. fpFD_SET(textrec(T).handle,f);
  826. if textrec(T).mode=fminput then
  827. SelectText:=fpselect(textrec(T).handle+1,@f,nil,nil,TimeOut)
  828. else
  829. SelectText:=fpselect(textrec(T).handle+1,nil,@f,nil,TimeOut);
  830. end;
  831. Function SelectText(var T:Text;TimeOut :cint):cint;
  832. var
  833. p : PTimeVal;
  834. tv : TimeVal;
  835. begin
  836. if TimeOut=-1 then
  837. p:=nil
  838. else
  839. begin
  840. tv.tv_Sec:=Timeout div 1000;
  841. tv.tv_Usec:=(Timeout mod 1000)*1000;
  842. p:=@tv;
  843. end;
  844. SelectText:=SelectText(T,p);
  845. end;
  846. {******************************************************************************
  847. Directory
  848. ******************************************************************************}
  849. procedure SeekDir(p:pdir;loc:clong);
  850. begin
  851. if p=nil then
  852. begin
  853. fpseterrno(ESysEBADF);
  854. exit;
  855. end;
  856. {$ifndef bsd}
  857. p^.dd_nextoff:=fplseek(p^.dd_fd,loc,seek_set);
  858. {$endif}
  859. p^.dd_size:=0;
  860. p^.dd_loc:=0;
  861. end;
  862. function TellDir(p:pdir):clong;
  863. begin
  864. if p=nil then
  865. begin
  866. fpseterrno(ESysEBADF);
  867. telldir:=-1;
  868. exit;
  869. end;
  870. telldir:=fplseek(p^.dd_fd,0,seek_cur)
  871. { We could try to use the nextoff field here, but on my 1.2.13
  872. kernel, this gives nothing... This may have to do with
  873. the readdir implementation of libc... I also didn't find any trace of
  874. the field in the kernel code itself, So I suspect it is an artifact of libc.
  875. Michael. }
  876. end;
  877. {******************************************************************************
  878. Pipes/Fifo
  879. ******************************************************************************}
  880. Procedure OpenPipe(var F:Text);
  881. begin
  882. case textrec(f).mode of
  883. fmoutput :
  884. if textrec(f).userdata[1]<>P_OUT then
  885. textrec(f).mode:=fmclosed;
  886. fminput :
  887. if textrec(f).userdata[1]<>P_IN then
  888. textrec(f).mode:=fmclosed;
  889. else
  890. textrec(f).mode:=fmclosed;
  891. end;
  892. end;
  893. Function IOPipe(var F:text):cint;
  894. begin
  895. IOPipe:=0;
  896. case textrec(f).mode of
  897. fmoutput :
  898. begin
  899. { first check if we need something to write, else we may
  900. get a SigPipe when Close() is called (PFV) }
  901. if textrec(f).bufpos>0 then
  902. IOPipe:=fpwrite(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufpos);
  903. end;
  904. fminput : Begin
  905. textrec(f).bufend:=fpread(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufsize);
  906. IOPipe:=textrec(f).bufend;
  907. End;
  908. end;
  909. textrec(f).bufpos:=0;
  910. end;
  911. Function FlushPipe(var F:Text):cint;
  912. begin
  913. FlushPipe:=0;
  914. if (textrec(f).mode=fmoutput) and (textrec(f).bufpos<>0) then
  915. FlushPipe:=IOPipe(f);
  916. textrec(f).bufpos:=0;
  917. end;
  918. Function ClosePipe(var F:text):cint;
  919. begin
  920. textrec(f).mode:=fmclosed;
  921. ClosePipe:=fpclose(textrec(f).handle);
  922. end;
  923. Function AssignPipe(var pipe_in,pipe_out:text):cint;
  924. {
  925. Sets up a pair of file variables, which act as a pipe. The first one can
  926. be read from, the second one can be written to.
  927. }
  928. var
  929. f_in,f_out : cint;
  930. begin
  931. if AssignPipe(f_in,f_out)=-1 then
  932. exit(-1);
  933. { Set up input }
  934. Assign(Pipe_in,'');
  935. Textrec(Pipe_in).Handle:=f_in;
  936. Textrec(Pipe_in).Mode:=fmInput;
  937. Textrec(Pipe_in).userdata[1]:=P_IN;
  938. TextRec(Pipe_in).OpenFunc:=@OpenPipe;
  939. TextRec(Pipe_in).InOutFunc:=@IOPipe;
  940. TextRec(Pipe_in).FlushFunc:=@FlushPipe;
  941. TextRec(Pipe_in).CloseFunc:=@ClosePipe;
  942. { Set up output }
  943. Assign(Pipe_out,'');
  944. Textrec(Pipe_out).Handle:=f_out;
  945. Textrec(Pipe_out).Mode:=fmOutput;
  946. Textrec(Pipe_out).userdata[1]:=P_OUT;
  947. TextRec(Pipe_out).OpenFunc:=@OpenPipe;
  948. TextRec(Pipe_out).InOutFunc:=@IOPipe;
  949. TextRec(Pipe_out).FlushFunc:=@FlushPipe;
  950. TextRec(Pipe_out).CloseFunc:=@ClosePipe;
  951. AssignPipe:=0;
  952. end;
  953. Function AssignPipe(var pipe_in,pipe_out:file):cint;
  954. {
  955. Sets up a pair of file variables, which act as a pipe. The first one can
  956. be read from, the second one can be written to.
  957. If the operation was unsuccesful,
  958. }
  959. var
  960. f_in,f_out : cint;
  961. begin
  962. if AssignPipe(f_in,f_out)=-1 then
  963. exit(-1);
  964. { Set up input }
  965. Assign(Pipe_in,'');
  966. Filerec(Pipe_in).Handle:=f_in;
  967. Filerec(Pipe_in).Mode:=fmInput;
  968. Filerec(Pipe_in).recsize:=1;
  969. Filerec(Pipe_in).userdata[1]:=P_IN;
  970. { Set up output }
  971. Assign(Pipe_out,'');
  972. Filerec(Pipe_out).Handle:=f_out;
  973. Filerec(Pipe_out).Mode:=fmoutput;
  974. Filerec(Pipe_out).recsize:=1;
  975. Filerec(Pipe_out).userdata[1]:=P_OUT;
  976. AssignPipe:=0;
  977. end;
  978. Function PCloseText(Var F:text):cint;
  979. {
  980. May not use @PClose due overloading
  981. }
  982. begin
  983. PCloseText:=PClose(f);
  984. end;
  985. function POpen(var F:text;const Prog:String;rw:char):cint;
  986. {
  987. Starts the program in 'Prog' and makes it's input or out put the
  988. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  989. F, will be read from stdin by the program in 'Prog'. The inverse is true
  990. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  991. read from 'f'.
  992. }
  993. var
  994. pipi,
  995. pipo : text;
  996. pid : pid_t;
  997. pl : ^cint;
  998. pp : ppchar;
  999. ret : cint;
  1000. begin
  1001. rw:=upcase(rw);
  1002. if not (rw in ['R','W']) then
  1003. begin
  1004. FpSetErrno(ESysEnoent);
  1005. exit(-1);
  1006. end;
  1007. if AssignPipe(pipi,pipo)=-1 Then
  1008. Exit(-1);
  1009. pid:=fpfork;
  1010. if pid=-1 then
  1011. begin
  1012. close(pipi);
  1013. close(pipo);
  1014. exit(-1);
  1015. end;
  1016. if pid=0 then
  1017. begin
  1018. { We're in the child }
  1019. if rw='W' then
  1020. begin
  1021. close(pipo);
  1022. ret:=fpdup2(pipi,input);
  1023. close(pipi);
  1024. if ret=-1 then
  1025. halt(127);
  1026. end
  1027. else
  1028. begin
  1029. close(pipi);
  1030. ret:=fpdup2(pipo,output);
  1031. close(pipo);
  1032. if ret=-1 then
  1033. halt(127);
  1034. end;
  1035. pp:=createshellargv(prog);
  1036. fpExecve(pp^,pp,envp);
  1037. halt(127);
  1038. end
  1039. else
  1040. begin
  1041. { We're in the parent }
  1042. if rw='W' then
  1043. begin
  1044. close(pipi);
  1045. f:=pipo;
  1046. textrec(f).bufptr:=@textrec(f).buffer;
  1047. end
  1048. else
  1049. begin
  1050. close(pipo);
  1051. f:=pipi;
  1052. textrec(f).bufptr:=@textrec(f).buffer;
  1053. end;
  1054. {Save the process ID - needed when closing }
  1055. pl:=@(textrec(f).userdata[2]);
  1056. pl^:=pid;
  1057. textrec(f).closefunc:=@PCloseText;
  1058. end;
  1059. ret:=0;
  1060. end;
  1061. Function POpen(var F:file;const Prog:String;rw:char):cint;
  1062. {
  1063. Starts the program in 'Prog' and makes it's input or out put the
  1064. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  1065. F, will be read from stdin by the program in 'Prog'. The inverse is true
  1066. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  1067. read from 'f'.
  1068. }
  1069. var
  1070. pipi,
  1071. pipo : file;
  1072. pid : cint;
  1073. pl : ^cint;
  1074. p,pp : ppchar;
  1075. temp : string[255];
  1076. ret : cint;
  1077. begin
  1078. rw:=upcase(rw);
  1079. if not (rw in ['R','W']) then
  1080. begin
  1081. FpSetErrno(ESysEnoent);
  1082. exit(-1);
  1083. end;
  1084. ret:=AssignPipe(pipi,pipo);
  1085. if ret=-1 then
  1086. exit(-1);
  1087. pid:=fpfork;
  1088. if pid=-1 then
  1089. begin
  1090. close(pipi);
  1091. close(pipo);
  1092. exit(-1);
  1093. end;
  1094. if pid=0 then
  1095. begin
  1096. { We're in the child }
  1097. if rw='W' then
  1098. begin
  1099. close(pipo);
  1100. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  1101. close(pipi);
  1102. if ret=-1 then
  1103. halt(127);
  1104. end
  1105. else
  1106. begin
  1107. close(pipi);
  1108. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  1109. close(pipo);
  1110. if ret=1 then
  1111. halt(127);
  1112. end;
  1113. getmem(pp,sizeof(pchar)*4);
  1114. temp:='/bin/sh'#0'-c'#0+prog+#0;
  1115. p:=pp;
  1116. p^:=@temp[1];
  1117. inc(p);
  1118. p^:=@temp[9];
  1119. inc(p);
  1120. p^:=@temp[12];
  1121. inc(p);
  1122. p^:=Nil;
  1123. fpExecve(ansistring('/bin/sh'),pp,envp);
  1124. halt(127);
  1125. end
  1126. else
  1127. begin
  1128. { We're in the parent }
  1129. if rw='W' then
  1130. begin
  1131. close(pipi);
  1132. f:=pipo;
  1133. end
  1134. else
  1135. begin
  1136. close(pipo);
  1137. f:=pipi;
  1138. end;
  1139. {Save the process ID - needed when closing }
  1140. pl:=@(filerec(f).userdata[2]);
  1141. pl^:=pid;
  1142. end;
  1143. POpen:=0;
  1144. end;
  1145. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:String) : cint;
  1146. {
  1147. Starts the program in 'Prog' and makes its input and output the
  1148. other end of two pipes, which are the stdin and stdout of a program
  1149. specified in 'Prog'.
  1150. streamout can be used to write to the program, streamin can be used to read
  1151. the output of the program. See the following diagram :
  1152. Parent Child
  1153. STreamout --> Input
  1154. Streamin <-- Output
  1155. Return value is the process ID of the process being spawned, or -1 in case of failure.
  1156. }
  1157. var
  1158. pipi,
  1159. pipo : text;
  1160. pid : cint;
  1161. pl : ^cint;
  1162. begin
  1163. AssignStream:=-1;
  1164. if AssignPipe(streamin,pipo)=-1 Then
  1165. exit(-1);
  1166. if AssignPipe(pipi,streamout)=-1 Then // shouldn't this close streamin and pipo?
  1167. exit(-1);
  1168. pid:=fpfork;
  1169. if pid=-1 then
  1170. begin
  1171. close(pipi);
  1172. close(pipo);
  1173. close (streamin);
  1174. close (streamout);
  1175. exit;
  1176. end;
  1177. if pid=0 then
  1178. begin
  1179. { We're in the child }
  1180. { Close what we don't need }
  1181. close(streamout);
  1182. close(streamin);
  1183. if fpdup2(pipi,input)=-1 Then
  1184. halt(127);
  1185. close(pipi);
  1186. If fpdup2(pipo,output)=-1 Then
  1187. halt (127);
  1188. close(pipo);
  1189. Execl(Prog);
  1190. halt(127);
  1191. end
  1192. else
  1193. begin
  1194. { we're in the parent}
  1195. close(pipo);
  1196. close(pipi);
  1197. {Save the process ID - needed when closing }
  1198. pl:=@(textrec(StreamIn).userdata[2]);
  1199. pl^:=pid;
  1200. textrec(StreamIn).closefunc:=@PCloseText;
  1201. {Save the process ID - needed when closing }
  1202. pl:=@(textrec(StreamOut).userdata[2]);
  1203. pl^:=pid;
  1204. textrec(StreamOut).closefunc:=@PCloseText;
  1205. AssignStream:=Pid;
  1206. end;
  1207. end;
  1208. function AssignStream(var StreamIn, StreamOut, StreamErr: Text; const prog: String):cint;
  1209. {
  1210. Starts the program in 'prog' and makes its input, output and error output the
  1211. other end of three pipes, which are the stdin, stdout and stderr of a program
  1212. specified in 'prog'.
  1213. StreamOut can be used to write to the program, StreamIn can be used to read
  1214. the output of the program, StreamErr reads the error output of the program.
  1215. See the following diagram :
  1216. Parent Child
  1217. StreamOut --> StdIn (input)
  1218. StreamIn <-- StdOut (output)
  1219. StreamErr <-- StdErr (error output)
  1220. }
  1221. var
  1222. PipeIn, PipeOut, PipeErr: text;
  1223. pid: cint;
  1224. pl: ^cint;
  1225. begin
  1226. AssignStream := -1;
  1227. // Assign pipes
  1228. if AssignPipe(StreamIn, PipeOut)=-1 Then
  1229. Exit(-1);
  1230. If AssignPipe(StreamErr, PipeErr)=-1 Then
  1231. begin
  1232. Close(StreamIn);
  1233. Close(PipeOut);
  1234. exit(-1);
  1235. end;
  1236. if AssignPipe(PipeIn, StreamOut)=-1 Then
  1237. begin
  1238. Close(StreamIn);
  1239. Close(PipeOut);
  1240. Close(StreamErr);
  1241. Close(PipeErr);
  1242. exit(-1);
  1243. end;
  1244. // Fork
  1245. pid := fpFork;
  1246. if pid=-1 then begin
  1247. Close(StreamIn);
  1248. Close(PipeOut);
  1249. Close(StreamErr);
  1250. Close(PipeErr);
  1251. Close(PipeIn);
  1252. Close(StreamOut);
  1253. exit(-1);
  1254. end;
  1255. if pid = 0 then begin
  1256. // *** We are in the child ***
  1257. // Close what we don not need
  1258. Close(StreamOut);
  1259. Close(StreamIn);
  1260. Close(StreamErr);
  1261. // Connect pipes
  1262. if fpdup2(PipeIn, Input)=-1 Then
  1263. Halt(127);
  1264. Close(PipeIn);
  1265. if fpdup2(PipeOut, Output)=-1 Then
  1266. Halt(127);
  1267. Close(PipeOut);
  1268. if fpdup2(PipeErr, StdErr)=-1 Then
  1269. Halt(127);
  1270. Close(PipeErr);
  1271. // Execute program
  1272. Execl(Prog);
  1273. Halt(127);
  1274. end else begin
  1275. // *** We are in the parent ***
  1276. Close(PipeErr);
  1277. Close(PipeOut);
  1278. Close(PipeIn);
  1279. // Save the process ID - needed when closing
  1280. pl := @(TextRec(StreamIn).userdata[2]);
  1281. pl^ := pid;
  1282. TextRec(StreamIn).closefunc := @PCloseText;
  1283. // Save the process ID - needed when closing
  1284. pl := @(TextRec(StreamOut).userdata[2]);
  1285. pl^ := pid;
  1286. TextRec(StreamOut).closefunc := @PCloseText;
  1287. // Save the process ID - needed when closing
  1288. pl := @(TextRec(StreamErr).userdata[2]);
  1289. pl^ := pid;
  1290. TextRec(StreamErr).closefunc := @PCloseText;
  1291. AssignStream := pid;
  1292. end;
  1293. end;
  1294. {******************************************************************************
  1295. General information calls
  1296. ******************************************************************************}
  1297. {$ifndef BSD}
  1298. Function GetDomainName:String; { linux only!}
  1299. // domainname is a glibc extension.
  1300. {
  1301. Get machines domain name. Returns empty string if not set.
  1302. }
  1303. Var
  1304. Sysn : utsname;
  1305. begin
  1306. If fpUname(sysn)<>0 then
  1307. getdomainname:=''
  1308. else
  1309. getdomainname:=strpas(@Sysn.domain[0]);
  1310. end;
  1311. {$endif}
  1312. Function GetHostName:String;
  1313. {
  1314. Get machines name. Returns empty string if not set.
  1315. }
  1316. Var
  1317. Sysn : utsname;
  1318. begin
  1319. If fpuname(sysn)=-1 then
  1320. gethostname:=''
  1321. else
  1322. gethostname:=strpas(@Sysn.nodename[0]);
  1323. end;
  1324. {******************************************************************************
  1325. Signal handling calls
  1326. ******************************************************************************}
  1327. procedure SigRaise(sig:integer);
  1328. begin
  1329. fpKill(fpGetPid,Sig);
  1330. end;
  1331. {******************************************************************************
  1332. Utility calls
  1333. ******************************************************************************}
  1334. {
  1335. Function Octal(l:cint):cint;
  1336. {
  1337. Convert an octal specified number to decimal;
  1338. }
  1339. var
  1340. octnr,
  1341. oct : cint;
  1342. begin
  1343. octnr:=0;
  1344. oct:=0;
  1345. while (l>0) do
  1346. begin
  1347. oct:=oct or ((l mod 10) shl octnr);
  1348. l:=l div 10;
  1349. inc(octnr,3);
  1350. end;
  1351. Octal:=oct;
  1352. end;
  1353. }
  1354. {$DEFINE FPC_FEXPAND_TILDE} { Tilde is expanded to home }
  1355. {$DEFINE FPC_FEXPAND_GETENVPCHAR} { GetEnv result is a PChar }
  1356. {$I fexpand.inc}
  1357. {$UNDEF FPC_FEXPAND_GETENVPCHAR}
  1358. {$UNDEF FPC_FEXPAND_TILDE}
  1359. Function FSearch(const path:pathstr;dirlist:string):pathstr;
  1360. {
  1361. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1362. returns an empty string if not found. Wildcards are NOT allowed.
  1363. If dirlist is empty, it is set to '.'
  1364. }
  1365. Var
  1366. NewDir : PathStr;
  1367. p1 : cint;
  1368. Info : Stat;
  1369. Begin
  1370. {Replace ':' with ';'}
  1371. for p1:=1to length(dirlist) do
  1372. if dirlist[p1]=':' then
  1373. dirlist[p1]:=';';
  1374. {Check for WildCards}
  1375. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1376. FSearch:='' {No wildcards allowed in these things.}
  1377. Else
  1378. Begin
  1379. Dirlist:='.;'+dirlist;{Make sure current dir is first to be searched.}
  1380. Repeat
  1381. p1:=Pos(';',DirList);
  1382. If p1=0 Then
  1383. p1:=255;
  1384. NewDir:=Copy(DirList,1,P1 - 1);
  1385. if NewDir[Length(NewDir)]<>'/' then
  1386. NewDir:=NewDir+'/';
  1387. NewDir:=NewDir+Path;
  1388. Delete(DirList,1,p1);
  1389. if (FpStat(NewDir,Info)>=0) and
  1390. (not fpS_ISDIR(Info.st_Mode)) then
  1391. Begin
  1392. If Pos('./',NewDir)=1 Then
  1393. Delete(NewDir,1,2);
  1394. {DOS strips off an initial .\}
  1395. End
  1396. Else
  1397. NewDir:='';
  1398. Until (DirList='') or (Length(NewDir) > 0);
  1399. FSearch:=NewDir;
  1400. End;
  1401. End;
  1402. Function FSearch(const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  1403. {
  1404. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1405. returns an empty string if not found. Wildcards are NOT allowed.
  1406. If dirlist is empty, it is set to '.'
  1407. This function tries to make FSearch use ansistrings, and decrease
  1408. stringhandling overhead at the same time.
  1409. }
  1410. Var
  1411. NewDir : PathStr;
  1412. p1 : cint;
  1413. Info : Stat;
  1414. i,j : cint;
  1415. p : pchar;
  1416. Begin
  1417. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1418. Dirlist:='.:'+dirlist; {Make sure current dir is first to be searched.}
  1419. if CurrentDirStrategy=CurrentDirectoryLast Then
  1420. Dirlist:=dirlist+':.'; {Make sure current dir is last to be searched.}
  1421. {Replace ':' and ';' with #0}
  1422. for p1:=1 to length(dirlist) do
  1423. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1424. dirlist[p1]:=#0;
  1425. {Check for WildCards}
  1426. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1427. FSearch:='' {No wildcards allowed in these things.}
  1428. Else
  1429. Begin
  1430. p:=pchar(dirlist);
  1431. i:=length(dirlist);
  1432. j:=1;
  1433. Repeat
  1434. NewDir:=p+'/'+Path;
  1435. if (FpStat(NewDir,Info)>=0) and
  1436. (not fpS_ISDIR(Info.st_Mode)) then
  1437. Begin
  1438. If Pos('./',NewDir)=1 Then
  1439. Delete(NewDir,1,2);
  1440. {DOS strips off an initial .\}
  1441. End
  1442. Else
  1443. NewDir:='';
  1444. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1445. if p^=#0 then inc(p);
  1446. Until (j>=i) or (Length(NewDir) > 0);
  1447. FSearch:=NewDir;
  1448. End;
  1449. End;
  1450. Function FSearch(const path:AnsiString;dirlist:Ansistring):AnsiString;
  1451. Begin
  1452. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1453. End;
  1454. Procedure Globfree(var p : pglob);
  1455. {
  1456. Release memory occupied by pglob structure, and names in it.
  1457. sets p to nil.
  1458. }
  1459. var
  1460. temp : pglob;
  1461. begin
  1462. while assigned(p) do
  1463. begin
  1464. temp:=p^.next;
  1465. if assigned(p^.name) then
  1466. freemem(p^.name);
  1467. dispose(p);
  1468. p:=temp;
  1469. end;
  1470. end;
  1471. Function Glob(Const path:pathstr):pglob;
  1472. {
  1473. Fills a tglob structure with entries matching path,
  1474. and returns a pointer to it. Returns nil on error,
  1475. linuxerror is set accordingly.
  1476. }
  1477. var
  1478. temp,
  1479. temp2 : string[255];
  1480. thedir : pdir;
  1481. buffer : pdirent;
  1482. root,
  1483. current : pglob;
  1484. begin
  1485. { Get directory }
  1486. temp:=dirname(path);
  1487. if temp='' then
  1488. temp:='.';
  1489. temp:=temp+#0;
  1490. thedir:=fpopendir(@temp[1]);
  1491. if thedir=nil then
  1492. exit(nil);
  1493. temp:=basename(path,''); { get the pattern }
  1494. if thedir^.dd_fd<0 then
  1495. exit(nil);
  1496. {get the entries}
  1497. root:=nil;
  1498. current:=nil;
  1499. repeat
  1500. buffer:=fpreaddir(thedir^);
  1501. if buffer=nil then
  1502. break;
  1503. temp2:=strpas(@(buffer^.d_name[0]));
  1504. if fnmatch(temp,temp2) then
  1505. begin
  1506. if root=nil then
  1507. begin
  1508. new(root);
  1509. current:=root;
  1510. end
  1511. else
  1512. begin
  1513. new(current^.next);
  1514. current:=current^.next;
  1515. end;
  1516. if current=nil then
  1517. begin
  1518. fpseterrno(ESysENOMEM);
  1519. globfree(root);
  1520. break;
  1521. end;
  1522. current^.next:=nil;
  1523. getmem(current^.name,length(temp2)+1);
  1524. if current^.name=nil then
  1525. begin
  1526. fpseterrno(ESysENOMEM);
  1527. globfree(root);
  1528. break;
  1529. end;
  1530. move(buffer^.d_name[0],current^.name^,length(temp2)+1);
  1531. end;
  1532. until false;
  1533. fpclosedir(thedir^);
  1534. glob:=root;
  1535. end;
  1536. {--------------------------------
  1537. Stat.Mode Macro's
  1538. --------------------------------}
  1539. Initialization
  1540. InitLocalTime;
  1541. finalization
  1542. DoneLocalTime;
  1543. End.
  1544. {
  1545. $Log$
  1546. Revision 1.65 2004-02-14 21:12:14 marco
  1547. * provisorische fix voor Michael's problemen
  1548. Revision 1.64 2004/02/14 18:22:15 marco
  1549. * fpsystem, and some FPC_USE_LIBC fixes. (FreeBSD needs systypes.inc, also when FPC_USE_LIBC, it only contains types like statfs
  1550. Revision 1.63 2004/02/13 10:50:22 marco
  1551. * Hopefully last large changes to fpexec and friends.
  1552. - naming conventions changes from Michael.
  1553. - shell functions get alternative under ifdef.
  1554. - arraystring function moves to unixutil
  1555. - unixutil now regards quotes in stringtoppchar.
  1556. - sysutils/unix get executeprocess(ansi,array of ansi), and
  1557. both executeprocess functions are fixed
  1558. - Sysutils/win32 get executeprocess(ansi,array of ansi)
  1559. Revision 1.62 2004/02/12 16:20:58 marco
  1560. * currentpath stuff fixed for fsearch
  1561. Revision 1.61 2004/02/12 15:31:06 marco
  1562. * First version of fpexec change. Still under ifdef or silently overloaded
  1563. Revision 1.60 2004/01/23 08:11:18 jonas
  1564. * only include systypes.inc if FPC_USE_LIBC is not defined
  1565. Revision 1.59 2004/01/22 13:46:14 marco
  1566. bsd
  1567. Revision 1.58 2004/01/04 21:05:01 jonas
  1568. * declare C-library routines as external in libc so we generate proper
  1569. import entries for Darwin
  1570. Revision 1.57 2004/01/04 20:53:02 jonas
  1571. * don't use systypes if FPC_USE_LIBC is defined
  1572. Revision 1.56 2004/01/04 16:24:05 jonas
  1573. * fixed WaitProcess in case of SysEintr
  1574. Revision 1.55 2003/12/31 20:24:25 marco
  1575. * export statfs(pchar)
  1576. Revision 1.54 2003/12/30 15:43:20 marco
  1577. * linux now compiles with FPC_USE_LIBC
  1578. Revision 1.53 2003/12/30 12:24:01 marco
  1579. * FPC_USE_LIBC
  1580. Revision 1.52 2003/12/08 17:16:30 peter
  1581. * fsearch should only find files
  1582. Revision 1.51 2003/11/19 17:11:40 marco
  1583. * termio unit
  1584. Revision 1.50 2003/11/19 10:54:32 marco
  1585. * some simple restructures
  1586. Revision 1.49 2003/11/17 11:28:08 marco
  1587. * Clone moved to linux, + few small unit unix changes
  1588. Revision 1.48 2003/11/17 10:05:51 marco
  1589. * threads for FreeBSD. Not working tho
  1590. Revision 1.47 2003/11/14 17:30:14 marco
  1591. * weeehoo linuxerror is no more :-)
  1592. Revision 1.46 2003/11/14 16:44:48 marco
  1593. * stream functions converted to work without linuxerror
  1594. Revision 1.45 2003/11/13 18:44:06 marco
  1595. * small fi
  1596. Revision 1.44 2003/11/12 22:19:45 marco
  1597. * more linuxeror fixes
  1598. Revision 1.43 2003/11/03 09:42:28 marco
  1599. * Peter's Cardinal<->Longint fixes patch
  1600. Revision 1.42 2003/10/30 16:42:58 marco
  1601. * fixes for old syscall() convention removing
  1602. Revision 1.41 2003/10/12 19:40:43 marco
  1603. * ioctl fixes. IDE now starts, but
  1604. Revision 1.40 2003/09/29 14:36:06 peter
  1605. * fixed for stricter compiler
  1606. Revision 1.39 2003/09/27 12:51:33 peter
  1607. * fpISxxx macros renamed to C compliant fpS_ISxxx
  1608. Revision 1.38 2003/09/20 12:38:29 marco
  1609. * FCL now compiles for FreeBSD with new 1.1. Now Linux.
  1610. Revision 1.37 2003/09/17 19:07:44 marco
  1611. * more fixes for Unix<->unixutil
  1612. Revision 1.36 2003/09/17 17:30:46 marco
  1613. * Introduction of unixutil
  1614. Revision 1.35 2003/09/16 21:46:27 marco
  1615. * small fixes, checking things on linux
  1616. Revision 1.34 2003/09/16 20:52:24 marco
  1617. * small cleanups. Mostly killing of already commented code in unix etc
  1618. Revision 1.33 2003/09/16 16:13:56 marco
  1619. * fdset functions renamed to fp<posix name>
  1620. Revision 1.32 2003/09/15 20:08:49 marco
  1621. * small fixes. FreeBSD now cycles
  1622. Revision 1.31 2003/09/14 20:15:01 marco
  1623. * Unix reform stage two. Remove all calls from Unix that exist in Baseunix.
  1624. Revision 1.30 2003/07/08 21:23:24 peter
  1625. * sparc fixes
  1626. Revision 1.29 2003/05/30 19:58:40 marco
  1627. * Getting NetBSD/i386 to compile.
  1628. Revision 1.28 2003/05/29 19:16:16 marco
  1629. * fixed a small *BSD gotcha
  1630. Revision 1.27 2003/05/24 20:39:54 jonas
  1631. * fixed ExitCode translation in WaitProcess for Linux and Darwin (and
  1632. probably other BSD's as well)
  1633. Revision 1.26 2003/03/11 08:27:59 michael
  1634. * stringtoppchar should use tabs instead of backspace as delimiter
  1635. Revision 1.25 2002/12/18 16:50:39 marco
  1636. * Unix RTL generic parts. Linux working, *BSD will follow shortly
  1637. Revision 1.24 2002/09/07 16:01:28 peter
  1638. * old logs removed and tabs fixed
  1639. Revision 1.23 2002/08/06 13:30:46 sg
  1640. * replaced some Longints with Cardinals, to mach the C headers
  1641. * updated the termios record
  1642. Revision 1.22 2002/03/05 20:04:25 michael
  1643. + Patch from Sebastian for FCNTL call
  1644. Revision 1.21 2002/01/02 12:22:54 marco
  1645. * Removed ifdef arround getepoch.
  1646. }