unix.pp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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; // vfork in FreeBSD.
  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. {$ifdef FPC_USE_FPEXEC}
  1036. fpexecl('/bin/sh',['-c',Prog]);
  1037. {$else}
  1038. pp:=createshellargv(prog);
  1039. fpExecve(pp^,pp,envp);
  1040. {$endif}
  1041. halt(127);
  1042. end
  1043. else
  1044. begin
  1045. { We're in the parent }
  1046. if rw='W' then
  1047. begin
  1048. close(pipi);
  1049. f:=pipo;
  1050. textrec(f).bufptr:=@textrec(f).buffer;
  1051. end
  1052. else
  1053. begin
  1054. close(pipo);
  1055. f:=pipi;
  1056. textrec(f).bufptr:=@textrec(f).buffer;
  1057. end;
  1058. {Save the process ID - needed when closing }
  1059. pl:=@(textrec(f).userdata[2]);
  1060. pl^:=pid;
  1061. textrec(f).closefunc:=@PCloseText;
  1062. end;
  1063. ret:=0;
  1064. end;
  1065. Function POpen(var F:file;const Prog:String;rw:char):cint;
  1066. {
  1067. Starts the program in 'Prog' and makes it's input or out put the
  1068. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  1069. F, will be read from stdin by the program in 'Prog'. The inverse is true
  1070. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  1071. read from 'f'.
  1072. }
  1073. var
  1074. pipi,
  1075. pipo : file;
  1076. pid : cint;
  1077. pl : ^cint;
  1078. p,pp : ppchar;
  1079. temp : string[255];
  1080. ret : cint;
  1081. begin
  1082. rw:=upcase(rw);
  1083. if not (rw in ['R','W']) then
  1084. begin
  1085. FpSetErrno(ESysEnoent);
  1086. exit(-1);
  1087. end;
  1088. ret:=AssignPipe(pipi,pipo);
  1089. if ret=-1 then
  1090. exit(-1);
  1091. pid:=fpfork;
  1092. if pid=-1 then
  1093. begin
  1094. close(pipi);
  1095. close(pipo);
  1096. exit(-1);
  1097. end;
  1098. if pid=0 then
  1099. begin
  1100. { We're in the child }
  1101. if rw='W' then
  1102. begin
  1103. close(pipo);
  1104. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  1105. close(pipi);
  1106. if ret=-1 then
  1107. halt(127);
  1108. end
  1109. else
  1110. begin
  1111. close(pipi);
  1112. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  1113. close(pipo);
  1114. if ret=1 then
  1115. halt(127);
  1116. end;
  1117. {$ifdef FPC_USE_FPEXEC}
  1118. fpexecl('/bin/sh',['-c',Prog]);
  1119. {$else}
  1120. getmem(pp,sizeof(pchar)*4);
  1121. temp:='/bin/sh'#0'-c'#0+prog+#0;
  1122. p:=pp;
  1123. p^:=@temp[1];
  1124. inc(p);
  1125. p^:=@temp[9];
  1126. inc(p);
  1127. p^:=@temp[12];
  1128. inc(p);
  1129. p^:=Nil;
  1130. fpExecve(ansistring('/bin/sh'),pp,envp);
  1131. {$endif}
  1132. halt(127);
  1133. end
  1134. else
  1135. begin
  1136. { We're in the parent }
  1137. if rw='W' then
  1138. begin
  1139. close(pipi);
  1140. f:=pipo;
  1141. end
  1142. else
  1143. begin
  1144. close(pipo);
  1145. f:=pipi;
  1146. end;
  1147. {Save the process ID - needed when closing }
  1148. pl:=@(filerec(f).userdata[2]);
  1149. pl^:=pid;
  1150. end;
  1151. POpen:=0;
  1152. end;
  1153. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:String) : cint;
  1154. {
  1155. Starts the program in 'Prog' and makes its input and output the
  1156. other end of two pipes, which are the stdin and stdout of a program
  1157. specified in 'Prog'.
  1158. streamout can be used to write to the program, streamin can be used to read
  1159. the output of the program. See the following diagram :
  1160. Parent Child
  1161. STreamout --> Input
  1162. Streamin <-- Output
  1163. Return value is the process ID of the process being spawned, or -1 in case of failure.
  1164. }
  1165. var
  1166. pipi,
  1167. pipo : text;
  1168. pid : cint;
  1169. pl : ^cint;
  1170. begin
  1171. AssignStream:=-1;
  1172. if AssignPipe(streamin,pipo)=-1 Then
  1173. exit(-1);
  1174. if AssignPipe(pipi,streamout)=-1 Then // shouldn't this close streamin and pipo?
  1175. exit(-1);
  1176. pid:=fpfork;
  1177. if pid=-1 then
  1178. begin
  1179. close(pipi);
  1180. close(pipo);
  1181. close (streamin);
  1182. close (streamout);
  1183. exit;
  1184. end;
  1185. if pid=0 then
  1186. begin
  1187. { We're in the child }
  1188. { Close what we don't need }
  1189. close(streamout);
  1190. close(streamin);
  1191. if fpdup2(pipi,input)=-1 Then
  1192. halt(127);
  1193. close(pipi);
  1194. If fpdup2(pipo,output)=-1 Then
  1195. halt (127);
  1196. close(pipo);
  1197. Execl(Prog);
  1198. halt(127);
  1199. end
  1200. else
  1201. begin
  1202. { we're in the parent}
  1203. close(pipo);
  1204. close(pipi);
  1205. {Save the process ID - needed when closing }
  1206. pl:=@(textrec(StreamIn).userdata[2]);
  1207. pl^:=pid;
  1208. textrec(StreamIn).closefunc:=@PCloseText;
  1209. {Save the process ID - needed when closing }
  1210. pl:=@(textrec(StreamOut).userdata[2]);
  1211. pl^:=pid;
  1212. textrec(StreamOut).closefunc:=@PCloseText;
  1213. AssignStream:=Pid;
  1214. end;
  1215. end;
  1216. function AssignStream(var StreamIn, StreamOut, StreamErr: Text; const prog: String):cint;
  1217. {
  1218. Starts the program in 'prog' and makes its input, output and error output the
  1219. other end of three pipes, which are the stdin, stdout and stderr of a program
  1220. specified in 'prog'.
  1221. StreamOut can be used to write to the program, StreamIn can be used to read
  1222. the output of the program, StreamErr reads the error output of the program.
  1223. See the following diagram :
  1224. Parent Child
  1225. StreamOut --> StdIn (input)
  1226. StreamIn <-- StdOut (output)
  1227. StreamErr <-- StdErr (error output)
  1228. }
  1229. var
  1230. PipeIn, PipeOut, PipeErr: text;
  1231. pid: cint;
  1232. pl: ^cint;
  1233. begin
  1234. AssignStream := -1;
  1235. // Assign pipes
  1236. if AssignPipe(StreamIn, PipeOut)=-1 Then
  1237. Exit(-1);
  1238. If AssignPipe(StreamErr, PipeErr)=-1 Then
  1239. begin
  1240. Close(StreamIn);
  1241. Close(PipeOut);
  1242. exit(-1);
  1243. end;
  1244. if AssignPipe(PipeIn, StreamOut)=-1 Then
  1245. begin
  1246. Close(StreamIn);
  1247. Close(PipeOut);
  1248. Close(StreamErr);
  1249. Close(PipeErr);
  1250. exit(-1);
  1251. end;
  1252. // Fork
  1253. pid := fpFork;
  1254. if pid=-1 then begin
  1255. Close(StreamIn);
  1256. Close(PipeOut);
  1257. Close(StreamErr);
  1258. Close(PipeErr);
  1259. Close(PipeIn);
  1260. Close(StreamOut);
  1261. exit(-1);
  1262. end;
  1263. if pid = 0 then begin
  1264. // *** We are in the child ***
  1265. // Close what we don not need
  1266. Close(StreamOut);
  1267. Close(StreamIn);
  1268. Close(StreamErr);
  1269. // Connect pipes
  1270. if fpdup2(PipeIn, Input)=-1 Then
  1271. Halt(127);
  1272. Close(PipeIn);
  1273. if fpdup2(PipeOut, Output)=-1 Then
  1274. Halt(127);
  1275. Close(PipeOut);
  1276. if fpdup2(PipeErr, StdErr)=-1 Then
  1277. Halt(127);
  1278. Close(PipeErr);
  1279. // Execute program
  1280. Execl(Prog);
  1281. Halt(127);
  1282. end else begin
  1283. // *** We are in the parent ***
  1284. Close(PipeErr);
  1285. Close(PipeOut);
  1286. Close(PipeIn);
  1287. // Save the process ID - needed when closing
  1288. pl := @(TextRec(StreamIn).userdata[2]);
  1289. pl^ := pid;
  1290. TextRec(StreamIn).closefunc := @PCloseText;
  1291. // Save the process ID - needed when closing
  1292. pl := @(TextRec(StreamOut).userdata[2]);
  1293. pl^ := pid;
  1294. TextRec(StreamOut).closefunc := @PCloseText;
  1295. // Save the process ID - needed when closing
  1296. pl := @(TextRec(StreamErr).userdata[2]);
  1297. pl^ := pid;
  1298. TextRec(StreamErr).closefunc := @PCloseText;
  1299. AssignStream := pid;
  1300. end;
  1301. end;
  1302. {******************************************************************************
  1303. General information calls
  1304. ******************************************************************************}
  1305. {$ifndef BSD}
  1306. Function GetDomainName:String; { linux only!}
  1307. // domainname is a glibc extension.
  1308. {
  1309. Get machines domain name. Returns empty string if not set.
  1310. }
  1311. Var
  1312. Sysn : utsname;
  1313. begin
  1314. If fpUname(sysn)<>0 then
  1315. getdomainname:=''
  1316. else
  1317. getdomainname:=strpas(@Sysn.domain[0]);
  1318. end;
  1319. {$endif}
  1320. Function GetHostName:String;
  1321. {
  1322. Get machines name. Returns empty string if not set.
  1323. }
  1324. Var
  1325. Sysn : utsname;
  1326. begin
  1327. If fpuname(sysn)=-1 then
  1328. gethostname:=''
  1329. else
  1330. gethostname:=strpas(@Sysn.nodename[0]);
  1331. end;
  1332. {******************************************************************************
  1333. Signal handling calls
  1334. ******************************************************************************}
  1335. procedure SigRaise(sig:integer);
  1336. begin
  1337. fpKill(fpGetPid,Sig);
  1338. end;
  1339. {******************************************************************************
  1340. Utility calls
  1341. ******************************************************************************}
  1342. {
  1343. Function Octal(l:cint):cint;
  1344. {
  1345. Convert an octal specified number to decimal;
  1346. }
  1347. var
  1348. octnr,
  1349. oct : cint;
  1350. begin
  1351. octnr:=0;
  1352. oct:=0;
  1353. while (l>0) do
  1354. begin
  1355. oct:=oct or ((l mod 10) shl octnr);
  1356. l:=l div 10;
  1357. inc(octnr,3);
  1358. end;
  1359. Octal:=oct;
  1360. end;
  1361. }
  1362. {$DEFINE FPC_FEXPAND_TILDE} { Tilde is expanded to home }
  1363. {$DEFINE FPC_FEXPAND_GETENVPCHAR} { GetEnv result is a PChar }
  1364. {$I fexpand.inc}
  1365. {$UNDEF FPC_FEXPAND_GETENVPCHAR}
  1366. {$UNDEF FPC_FEXPAND_TILDE}
  1367. Function FSearch(const path:pathstr;dirlist:string):pathstr;
  1368. {
  1369. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1370. returns an empty string if not found. Wildcards are NOT allowed.
  1371. If dirlist is empty, it is set to '.'
  1372. }
  1373. Var
  1374. NewDir : PathStr;
  1375. p1 : cint;
  1376. Info : Stat;
  1377. Begin
  1378. {Replace ':' with ';'}
  1379. for p1:=1to length(dirlist) do
  1380. if dirlist[p1]=':' then
  1381. dirlist[p1]:=';';
  1382. {Check for WildCards}
  1383. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1384. FSearch:='' {No wildcards allowed in these things.}
  1385. Else
  1386. Begin
  1387. Dirlist:='.;'+dirlist;{Make sure current dir is first to be searched.}
  1388. Repeat
  1389. p1:=Pos(';',DirList);
  1390. If p1=0 Then
  1391. p1:=255;
  1392. NewDir:=Copy(DirList,1,P1 - 1);
  1393. if NewDir[Length(NewDir)]<>'/' then
  1394. NewDir:=NewDir+'/';
  1395. NewDir:=NewDir+Path;
  1396. Delete(DirList,1,p1);
  1397. if (FpStat(NewDir,Info)>=0) and
  1398. (not fpS_ISDIR(Info.st_Mode)) then
  1399. Begin
  1400. If Pos('./',NewDir)=1 Then
  1401. Delete(NewDir,1,2);
  1402. {DOS strips off an initial .\}
  1403. End
  1404. Else
  1405. NewDir:='';
  1406. Until (DirList='') or (Length(NewDir) > 0);
  1407. FSearch:=NewDir;
  1408. End;
  1409. End;
  1410. Function FSearch(const path:AnsiString;dirlist:Ansistring;CurrentDirStrategy:TFSearchOption):AnsiString;
  1411. {
  1412. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1413. returns an empty string if not found. Wildcards are NOT allowed.
  1414. If dirlist is empty, it is set to '.'
  1415. This function tries to make FSearch use ansistrings, and decrease
  1416. stringhandling overhead at the same time.
  1417. }
  1418. Var
  1419. NewDir : PathStr;
  1420. p1 : cint;
  1421. Info : Stat;
  1422. i,j : cint;
  1423. p : pchar;
  1424. Begin
  1425. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1426. Dirlist:='.:'+dirlist; {Make sure current dir is first to be searched.}
  1427. if CurrentDirStrategy=CurrentDirectoryLast Then
  1428. Dirlist:=dirlist+':.'; {Make sure current dir is last to be searched.}
  1429. {Replace ':' and ';' with #0}
  1430. for p1:=1 to length(dirlist) do
  1431. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1432. dirlist[p1]:=#0;
  1433. {Check for WildCards}
  1434. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1435. FSearch:='' {No wildcards allowed in these things.}
  1436. Else
  1437. Begin
  1438. p:=pchar(dirlist);
  1439. i:=length(dirlist);
  1440. j:=1;
  1441. Repeat
  1442. NewDir:=p+'/'+Path;
  1443. if (FpStat(NewDir,Info)>=0) and
  1444. (not fpS_ISDIR(Info.st_Mode)) then
  1445. Begin
  1446. If Pos('./',NewDir)=1 Then
  1447. Delete(NewDir,1,2);
  1448. {DOS strips off an initial .\}
  1449. End
  1450. Else
  1451. NewDir:='';
  1452. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1453. if p^=#0 then inc(p);
  1454. Until (j>=i) or (Length(NewDir) > 0);
  1455. FSearch:=NewDir;
  1456. End;
  1457. End;
  1458. Function FSearch(const path:AnsiString;dirlist:Ansistring):AnsiString;
  1459. Begin
  1460. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1461. End;
  1462. Procedure Globfree(var p : pglob);
  1463. {
  1464. Release memory occupied by pglob structure, and names in it.
  1465. sets p to nil.
  1466. }
  1467. var
  1468. temp : pglob;
  1469. begin
  1470. while assigned(p) do
  1471. begin
  1472. temp:=p^.next;
  1473. if assigned(p^.name) then
  1474. freemem(p^.name);
  1475. dispose(p);
  1476. p:=temp;
  1477. end;
  1478. end;
  1479. Function Glob(Const path:pathstr):pglob;
  1480. {
  1481. Fills a tglob structure with entries matching path,
  1482. and returns a pointer to it. Returns nil on error,
  1483. linuxerror is set accordingly.
  1484. }
  1485. var
  1486. temp,
  1487. temp2 : string[255];
  1488. thedir : pdir;
  1489. buffer : pdirent;
  1490. root,
  1491. current : pglob;
  1492. begin
  1493. { Get directory }
  1494. temp:=dirname(path);
  1495. if temp='' then
  1496. temp:='.';
  1497. temp:=temp+#0;
  1498. thedir:=fpopendir(@temp[1]);
  1499. if thedir=nil then
  1500. exit(nil);
  1501. temp:=basename(path,''); { get the pattern }
  1502. if thedir^.dd_fd<0 then
  1503. exit(nil);
  1504. {get the entries}
  1505. root:=nil;
  1506. current:=nil;
  1507. repeat
  1508. buffer:=fpreaddir(thedir^);
  1509. if buffer=nil then
  1510. break;
  1511. temp2:=strpas(@(buffer^.d_name[0]));
  1512. if fnmatch(temp,temp2) then
  1513. begin
  1514. if root=nil then
  1515. begin
  1516. new(root);
  1517. current:=root;
  1518. end
  1519. else
  1520. begin
  1521. new(current^.next);
  1522. current:=current^.next;
  1523. end;
  1524. if current=nil then
  1525. begin
  1526. fpseterrno(ESysENOMEM);
  1527. globfree(root);
  1528. break;
  1529. end;
  1530. current^.next:=nil;
  1531. getmem(current^.name,length(temp2)+1);
  1532. if current^.name=nil then
  1533. begin
  1534. fpseterrno(ESysENOMEM);
  1535. globfree(root);
  1536. break;
  1537. end;
  1538. move(buffer^.d_name[0],current^.name^,length(temp2)+1);
  1539. end;
  1540. until false;
  1541. fpclosedir(thedir^);
  1542. glob:=root;
  1543. end;
  1544. {--------------------------------
  1545. Stat.Mode Macro's
  1546. --------------------------------}
  1547. Initialization
  1548. InitLocalTime;
  1549. finalization
  1550. DoneLocalTime;
  1551. End.
  1552. {
  1553. $Log$
  1554. Revision 1.66 2004-02-16 13:21:18 marco
  1555. * fpexec for popen
  1556. Revision 1.65 2004/02/14 21:12:14 marco
  1557. * provisorische fix voor Michael's problemen
  1558. Revision 1.64 2004/02/14 18:22:15 marco
  1559. * fpsystem, and some FPC_USE_LIBC fixes. (FreeBSD needs systypes.inc, also when FPC_USE_LIBC, it only contains types like statfs
  1560. Revision 1.63 2004/02/13 10:50:22 marco
  1561. * Hopefully last large changes to fpexec and friends.
  1562. - naming conventions changes from Michael.
  1563. - shell functions get alternative under ifdef.
  1564. - arraystring function moves to unixutil
  1565. - unixutil now regards quotes in stringtoppchar.
  1566. - sysutils/unix get executeprocess(ansi,array of ansi), and
  1567. both executeprocess functions are fixed
  1568. - Sysutils/win32 get executeprocess(ansi,array of ansi)
  1569. Revision 1.62 2004/02/12 16:20:58 marco
  1570. * currentpath stuff fixed for fsearch
  1571. Revision 1.61 2004/02/12 15:31:06 marco
  1572. * First version of fpexec change. Still under ifdef or silently overloaded
  1573. Revision 1.60 2004/01/23 08:11:18 jonas
  1574. * only include systypes.inc if FPC_USE_LIBC is not defined
  1575. Revision 1.59 2004/01/22 13:46:14 marco
  1576. bsd
  1577. Revision 1.58 2004/01/04 21:05:01 jonas
  1578. * declare C-library routines as external in libc so we generate proper
  1579. import entries for Darwin
  1580. Revision 1.57 2004/01/04 20:53:02 jonas
  1581. * don't use systypes if FPC_USE_LIBC is defined
  1582. Revision 1.56 2004/01/04 16:24:05 jonas
  1583. * fixed WaitProcess in case of SysEintr
  1584. Revision 1.55 2003/12/31 20:24:25 marco
  1585. * export statfs(pchar)
  1586. Revision 1.54 2003/12/30 15:43:20 marco
  1587. * linux now compiles with FPC_USE_LIBC
  1588. Revision 1.53 2003/12/30 12:24:01 marco
  1589. * FPC_USE_LIBC
  1590. Revision 1.52 2003/12/08 17:16:30 peter
  1591. * fsearch should only find files
  1592. Revision 1.51 2003/11/19 17:11:40 marco
  1593. * termio unit
  1594. Revision 1.50 2003/11/19 10:54:32 marco
  1595. * some simple restructures
  1596. Revision 1.49 2003/11/17 11:28:08 marco
  1597. * Clone moved to linux, + few small unit unix changes
  1598. Revision 1.48 2003/11/17 10:05:51 marco
  1599. * threads for FreeBSD. Not working tho
  1600. Revision 1.47 2003/11/14 17:30:14 marco
  1601. * weeehoo linuxerror is no more :-)
  1602. Revision 1.46 2003/11/14 16:44:48 marco
  1603. * stream functions converted to work without linuxerror
  1604. Revision 1.45 2003/11/13 18:44:06 marco
  1605. * small fi
  1606. Revision 1.44 2003/11/12 22:19:45 marco
  1607. * more linuxeror fixes
  1608. Revision 1.43 2003/11/03 09:42:28 marco
  1609. * Peter's Cardinal<->Longint fixes patch
  1610. Revision 1.42 2003/10/30 16:42:58 marco
  1611. * fixes for old syscall() convention removing
  1612. Revision 1.41 2003/10/12 19:40:43 marco
  1613. * ioctl fixes. IDE now starts, but
  1614. Revision 1.40 2003/09/29 14:36:06 peter
  1615. * fixed for stricter compiler
  1616. Revision 1.39 2003/09/27 12:51:33 peter
  1617. * fpISxxx macros renamed to C compliant fpS_ISxxx
  1618. Revision 1.38 2003/09/20 12:38:29 marco
  1619. * FCL now compiles for FreeBSD with new 1.1. Now Linux.
  1620. Revision 1.37 2003/09/17 19:07:44 marco
  1621. * more fixes for Unix<->unixutil
  1622. Revision 1.36 2003/09/17 17:30:46 marco
  1623. * Introduction of unixutil
  1624. Revision 1.35 2003/09/16 21:46:27 marco
  1625. * small fixes, checking things on linux
  1626. Revision 1.34 2003/09/16 20:52:24 marco
  1627. * small cleanups. Mostly killing of already commented code in unix etc
  1628. Revision 1.33 2003/09/16 16:13:56 marco
  1629. * fdset functions renamed to fp<posix name>
  1630. Revision 1.32 2003/09/15 20:08:49 marco
  1631. * small fixes. FreeBSD now cycles
  1632. Revision 1.31 2003/09/14 20:15:01 marco
  1633. * Unix reform stage two. Remove all calls from Unix that exist in Baseunix.
  1634. Revision 1.30 2003/07/08 21:23:24 peter
  1635. * sparc fixes
  1636. Revision 1.29 2003/05/30 19:58:40 marco
  1637. * Getting NetBSD/i386 to compile.
  1638. Revision 1.28 2003/05/29 19:16:16 marco
  1639. * fixed a small *BSD gotcha
  1640. Revision 1.27 2003/05/24 20:39:54 jonas
  1641. * fixed ExitCode translation in WaitProcess for Linux and Darwin (and
  1642. probably other BSD's as well)
  1643. Revision 1.26 2003/03/11 08:27:59 michael
  1644. * stringtoppchar should use tabs instead of backspace as delimiter
  1645. Revision 1.25 2002/12/18 16:50:39 marco
  1646. * Unix RTL generic parts. Linux working, *BSD will follow shortly
  1647. Revision 1.24 2002/09/07 16:01:28 peter
  1648. * old logs removed and tabs fixed
  1649. Revision 1.23 2002/08/06 13:30:46 sg
  1650. * replaced some Longints with Cardinals, to mach the C headers
  1651. * updated the termios record
  1652. Revision 1.22 2002/03/05 20:04:25 michael
  1653. + Patch from Sebastian for FCNTL call
  1654. Revision 1.21 2002/01/02 12:22:54 marco
  1655. * Removed ifdef arround getepoch.
  1656. }