2
0

unix.pp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Michael Van Canneyt,
  4. BSD parts (c) 2000 by Marco van de Voort
  5. members of the Free Pascal development team.
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY;without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. Unit Unix;
  13. Interface
  14. Uses
  15. BaseUnix,UnixType;
  16. // If you deprecated new symbols, please annotate the version.
  17. // this makes it easier to decide if they can already be removed.
  18. {$if (defined(BSD) or defined(SUNOS)) and defined(FPC_USE_LIBC)}
  19. {$define USE_VFORK}
  20. {$endif}
  21. {$i aliasptp.inc}
  22. {$i unxconst.inc} { Get Types and Constants only exported in this unit }
  23. {** File handling **}
  24. Const
  25. P_IN = 1; // pipes (?)
  26. P_OUT = 2;
  27. LOCK_SH = 1; // flock constants ?
  28. LOCK_EX = 2;
  29. LOCK_UN = 8;
  30. LOCK_NB = 4;
  31. // The portable MAP_* and PROT_ constants are exported from unit Unix for compability.
  32. PROT_READ = baseunix.PROT_READ; { page can be read }
  33. PROT_WRITE = baseunix.PROT_WRITE; { page can be written }
  34. PROT_EXEC = baseunix.PROT_EXEC; { page can be executed }
  35. PROT_NONE = baseunix.PROT_NONE; { page can not be accessed }
  36. MAP_FAILED = baseunix.MAP_FAILED; { mmap() failed }
  37. MAP_SHARED = baseunix.MAP_SHARED; { Share changes }
  38. MAP_PRIVATE = baseunix.MAP_PRIVATE; { Changes are private }
  39. MAP_TYPE = baseunix.MAP_TYPE; { Mask for type of mapping }
  40. MAP_FIXED = baseunix.MAP_FIXED; { Interpret addr exactly }
  41. {** Time/Date Handling **}
  42. type
  43. TTZInfo = record
  44. daylight : boolean;
  45. seconds : Longint; // difference from UTC
  46. validsince : int64; // UTC timestamp
  47. validuntil : int64; // UTC timestamp
  48. end;
  49. TTZInfoEx = record
  50. name : array[boolean] of RawByteString; { False = StandardName, True = DaylightName }
  51. leap_correct : longint;
  52. leap_hit : longint;
  53. end;
  54. Function GetTzseconds : Longint;
  55. property Tzseconds : Longint read GetTzseconds;
  56. function Gettzdaylight : boolean;
  57. property tzdaylight : boolean read Gettzdaylight;
  58. function Gettzname(const b : boolean) : string;
  59. property tzname[b : boolean] : string read Gettzname;
  60. function GetTZInfo : TTZInfo;
  61. property TZInfo : TTZInfo read GetTZInfo;
  62. function GetTZInfoEx : TTZInfoEx;
  63. property TZInfoEx : TTZInfoEx read GetTZInfoEx;
  64. procedure SetTZInfo(const ATZInfo: TTZInfo; const ATZInfoEx: TTZInfoEx);
  65. {************ Procedure/Functions ************}
  66. {$ifdef android}
  67. {$define DONT_READ_TIMEZONE}
  68. {$endif android}
  69. {$IFNDEF DONT_READ_TIMEZONE} // allows to disable linking in and trying for platforms
  70. // it doesn't (yet) work for.
  71. { timezone support }
  72. function GetLocalTimezone(timer:int64;timerIsUTC:Boolean;var ATZInfo:TTZInfo;var ATZInfoEx:TTZInfoEx):Boolean;
  73. function GetLocalTimezone(timer:int64;timerIsUTC:Boolean;var ATZInfo:TTZInfo):Boolean;
  74. procedure RefreshTZInfo;
  75. function ReadTimezoneFile(fn:string) : Boolean;
  76. function GetTimezoneFile:string;
  77. Procedure ReReadLocalTime;
  78. {$ENDIF}
  79. Function UniversalToEpoch(year,month,day,hour,minute,second:Word):int64; // use DateUtils.DateTimeToUnix for cross-platform applications
  80. Function LocalToEpoch(year,month,day,hour,minute,second:Word):int64; // use DateUtils.DateTimeToUnix for cross-platform applications
  81. Procedure EpochToLocal(epoch:int64;var year,month,day,hour,minute,second:Word); // use DateUtils.UnixToDateTime for cross-platform applications
  82. Procedure EpochToUniversal(epoch:int64;var year,month,day,hour,minute,second:Word); // use DateUtils.UnixToDateTime for cross-platform applications
  83. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word); // use DateUtils.DateTimetoJulianDate for cross-platform applications
  84. Function GregorianToJulian(Year,Month,Day:Longint):LongInt; // use DateUtils.JulianDateToDateTime for cross-platform applications
  85. {** Process Handling **}
  86. function FpExecLE (Const PathName:RawByteString;const S:Array Of RawByteString;MyEnv:ppchar):cint;
  87. function FpExecL (Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  88. function FpExecLP (Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  89. function FpExecLPE(Const PathName:RawByteString;const S:Array Of RawByteString;env:ppchar):cint;
  90. function FpExecV (Const PathName:RawByteString;args:ppchar):cint;
  91. function FpExecVP (Const PathName:RawByteString;args:ppchar):cint;
  92. function FpExecVPE(Const PathName:RawByteString;args,env:ppchar):cint;
  93. Function fpSystem(const Command:RawByteString):cint;
  94. Function WaitProcess (Pid:cint):cint;
  95. Function WIFSTOPPED (Status: Integer): Boolean;
  96. Function W_EXITCODE (ReturnCode, Signal: Integer): Integer;
  97. Function W_STOPCODE (Signal: Integer): Integer;
  98. {** File Handling **}
  99. Function fpFlock (var T : text;mode : cint) : cint;
  100. Function fpFlock (var F : File;mode : cint) : cint;
  101. {** Directory Handling **}
  102. procedure SeekDir(p:pdir;loc:clong);
  103. function TellDir(p:pdir):TOff;
  104. {** Pipe/Fifo/Stream **}
  105. Function AssignPipe (var pipe_in,pipe_out:cint):cint;
  106. Function AssignPipe (var pipe_in,pipe_out:text):cint;
  107. Function AssignPipe (var pipe_in,pipe_out:file):cint;
  108. Function POpen (var F:text;const Prog:RawByteString;rw:char):cint;
  109. Function POpen (var F:file;const Prog:RawByteString;rw:char):cint;
  110. Function POpen (var F:text;const Prog:UnicodeString;rw:char):cint;
  111. Function POpen (var F:file;const Prog:UnicodeString;rw:char):cint;
  112. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  113. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  114. Function GetDomainName:String; deprecated; // because linux only.
  115. Function GetHostName:String;
  116. {** Utility functions **}
  117. Type
  118. TFSearchOption = (NoCurrentDirectory,
  119. CurrentDirectoryFirst,
  120. CurrentDirectoryLast);
  121. Function FSearch (const path:RawByteString;dirlist:RawByteString;CurrentDirStrategy:TFSearchOption):RawByteString;
  122. Function FSearch (const path:RawByteString;dirlist:RawByteString):RawByteString;
  123. Function FSearch (const path:UnicodeString;dirlist:UnicodeString;CurrentDirStrategy:TFSearchOption):UnicodeString;
  124. Function FSearch (const path:UnicodeString;dirlist:UnicodeString):UnicodeString;
  125. {$ifdef FPC_USE_LIBC}
  126. const clib = 'c';
  127. {$i unxdeclh.inc}
  128. {$else}
  129. {$i unxsysch.inc} // calls used in system and not reexported from baseunix
  130. {$endif}
  131. {******************************************************************************
  132. Implementation
  133. ******************************************************************************}
  134. {$i unxovlh.inc}
  135. Implementation
  136. {$ifndef FPC_USE_LIBC}
  137. Uses
  138. Syscall;
  139. {$endif}
  140. {$i unxovl.inc}
  141. {$ifndef FPC_USE_LIBC}
  142. {$i syscallh.inc}
  143. {$i unxsysc.inc}
  144. {$endif}
  145. {$i unxfunc.inc} { Platform specific implementations }
  146. Function getenv(name:string):Pchar; external name 'FPC_SYSC_FPGETENV';
  147. {******************************************************************************
  148. timezone support
  149. ******************************************************************************}
  150. var
  151. CurrentTZinfo : array [0..1] of TTZInfo;
  152. CurrentTzinfoEx : array [0..1] of TTZInfoEx;
  153. CurrentTZindex : LongInt = 0; // current index for CurrentTZinfo/CurrentTZinfoEx - can be only 0 or 1
  154. {$ifdef FPC_HAS_FEATURE_THREADING}
  155. UseTZThreading: Boolean = false;
  156. TZInfoCS: TRTLCriticalSection;
  157. {$endif}
  158. procedure LockTZInfo;
  159. begin
  160. {$if declared(UseTZThreading)}
  161. if UseTZThreading then
  162. EnterCriticalSection(TZInfoCS);
  163. {$endif}
  164. end;
  165. procedure UnlockTZInfo;
  166. begin
  167. {$if declared(UseTZThreading)}
  168. if UseTZThreading then
  169. LeaveCriticalSection(TZInfoCS);
  170. {$endif}
  171. end;
  172. Function GetTzseconds : Longint;
  173. begin
  174. GetTzseconds:=Tzinfo.seconds;
  175. end;
  176. function Gettzdaylight : boolean;
  177. begin
  178. Gettzdaylight:=Tzinfo.daylight;
  179. end;
  180. function Gettzname(const b : boolean) : string;
  181. begin
  182. Gettzname:=TzinfoEx.name[b];
  183. end;
  184. function GetTZInfo : TTZInfo;
  185. {$IFNDEF DONT_READ_TIMEZONE}
  186. var
  187. curtime: time_t;
  188. {$ENDIF}
  189. begin
  190. GetTZInfo:=CurrentTZinfo[InterlockedExchangeAdd(CurrentTZindex, 0)];
  191. {$IFNDEF DONT_READ_TIMEZONE}
  192. curtime:=fptime;
  193. if not((GetTZInfo.validsince+GetTZInfo.seconds<=curtime) and (curtime<GetTZInfo.validuntil+GetTZInfo.seconds)) then
  194. begin
  195. RefreshTZInfo;
  196. GetTZInfo:=CurrentTZinfo[InterlockedExchangeAdd(CurrentTZindex, 0)];
  197. end;
  198. {$ENDIF}
  199. end;
  200. function GetTZInfoEx : TTZInfoEx;
  201. begin
  202. GetTZInfoEx:=CurrentTzinfoEx[InterlockedExchangeAdd(CurrentTZindex, 0)];
  203. end;
  204. procedure SetTZInfo(const ATZInfo: TTZInfo; const ATZInfoEx: TTZInfoEx);
  205. var
  206. OldTZindex,NewTZindex: longint;
  207. begin
  208. LockTZInfo;
  209. OldTZindex:=InterlockedExchangeAdd(CurrentTZindex,0);
  210. if OldTZindex=0 then
  211. NewTZindex:=1
  212. else
  213. NewTZindex:=0;
  214. CurrentTzinfo[NewTZindex]:=ATZInfo;
  215. CurrentTzinfoEx[NewTZindex]:=ATZInfoEx;
  216. InterlockedExchangeAdd(CurrentTZindex,NewTZindex-OldTZindex);
  217. UnlockTZInfo;
  218. end;
  219. Const
  220. {Date Translation}
  221. C1970=2440588;
  222. D0 = 1461;
  223. D1 = 146097;
  224. D2 =1721119;
  225. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word);
  226. Var
  227. YYear,XYear,Temp,TempMonth : LongInt;
  228. Begin
  229. Temp:=((JulianDN-D2) shl 2)-1;
  230. JulianDN:=Temp Div D1;
  231. XYear:=(Temp Mod D1) or 3;
  232. YYear:=(XYear Div D0);
  233. Temp:=((((XYear mod D0)+4) shr 2)*5)-3;
  234. Day:=((Temp Mod 153)+5) Div 5;
  235. TempMonth:=Temp Div 153;
  236. If TempMonth>=10 Then
  237. Begin
  238. inc(YYear);
  239. dec(TempMonth,12);
  240. End;
  241. inc(TempMonth,3);
  242. Month := TempMonth;
  243. Year:=YYear+(JulianDN*100);
  244. end;
  245. Procedure EpochToLocal(epoch:Int64;var year,month,day,hour,minute,second:Word);
  246. {
  247. Transforms Epoch time into local time (hour, minute,seconds)
  248. }
  249. Var
  250. lTZInfo: TTZInfo;
  251. Begin
  252. {$if declared(GetLocalTimezone)}
  253. if GetLocalTimezone(epoch,true,lTZInfo) then
  254. inc(Epoch,lTZInfo.seconds)
  255. else { fallback }
  256. {$endif}
  257. inc(Epoch,TZInfo.seconds);
  258. EpochToUniversal(epoch,year,month,day,hour,minute,second);
  259. End;
  260. Procedure EpochToUniversal(epoch:Int64;var year,month,day,hour,minute,second:Word);
  261. {
  262. Transforms Epoch time into universal time (hour, minute,seconds)
  263. }
  264. Var
  265. DateNum: LongInt;
  266. Begin
  267. Datenum:=(Epoch Div 86400) + c1970;
  268. JulianToGregorian(DateNum,Year,Month,day);
  269. Epoch:=Abs(Epoch Mod 86400);
  270. Hour:=Epoch Div 3600;
  271. Epoch:=Epoch Mod 3600;
  272. Minute:=Epoch Div 60;
  273. Second:=Epoch Mod 60;
  274. End;
  275. Function LocalToEpoch(year,month,day,hour,minute,second:Word):Int64;
  276. {
  277. Transforms local time (year,month,day,hour,minutes,second) to Epoch time
  278. (seconds since 00:00, january 1 1970, corrected for local time zone)
  279. }
  280. Var
  281. lTZInfo: TTZInfo;
  282. LocalEpoch: Int64;
  283. Begin
  284. LocalEpoch:=UniversalToEpoch(year,month,day,hour,minute,second);
  285. {$if declared(GetLocalTimezone)}
  286. if GetLocalTimezone(LocalEpoch,false,lTZInfo) then
  287. LocalToEpoch:=LocalEpoch-lTZInfo.seconds
  288. else { fallback }
  289. {$endif}
  290. LocalToEpoch:=LocalEpoch-TZInfo.seconds;
  291. End;
  292. Function UniversalToEpoch(year,month,day,hour,minute,second:Word):Int64;
  293. {
  294. Transforms universal time (year,month,day,hour,minutes,second) to Epoch time
  295. (seconds since 00:00, january 1 1970, corrected for local time zone)
  296. }
  297. Begin
  298. UniversalToEpoch:=(Int64(GregorianToJulian(Year,Month,Day)-c1970)*86400)+
  299. (LongInt(Hour)*3600)+(Longint(Minute)*60)+Second;
  300. End;
  301. Function GregorianToJulian(Year,Month,Day:Longint):LongInt;
  302. Var
  303. Century,XYear: LongInt;
  304. Begin
  305. If Month<=2 Then
  306. Begin
  307. Dec(Year);
  308. Inc(Month,12);
  309. End;
  310. Dec(Month,3);
  311. Century:=(longint(Year Div 100)*D1) shr 2;
  312. XYear:=(longint(Year Mod 100)*D0) shr 2;
  313. GregorianToJulian:=((((Month*153)+2) div 5)+Day)+D2+XYear+Century;
  314. End;
  315. {******************************************************************************
  316. Process related calls
  317. ******************************************************************************}
  318. { Most calls of WaitPID do not handle the result correctly, this funktion treats errors more correctly }
  319. 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}
  320. var
  321. r,s : cint;
  322. begin
  323. s:=$7F00;
  324. repeat
  325. r:=fpWaitPid(Pid,@s,0);
  326. if (r=-1) and (fpgeterrno=ESysEIntr) Then
  327. r:=0;
  328. until (r<>0);
  329. if (r=-1) or (r=0) then // 0 is not a valid return and should never occur (it means status invalid when using WNOHANG)
  330. WaitProcess:=-1 // return -1 to indicate an error. fpwaitpid updated it.
  331. else
  332. begin
  333. if wifexited(s) then
  334. WaitProcess:=wexitstatus(s)
  335. else if (s>0) then // Until now there is not use of the highest bit , but check this for the future
  336. WaitProcess:=-s // normal case
  337. else
  338. WaitProcess:=s; // s<0 should not occur, but wie return also a negativ value
  339. end;
  340. end;
  341. function intFpExecVEMaybeP (Const PathName:RawByteString;Args,MyEnv:ppchar;SearchPath:Boolean):cint;
  342. // does an ExecVE, but still has to handle P
  343. // execv variants call this directly, execl variants indirectly via
  344. // intfpexecl
  345. Var
  346. NewCmd : RawByteString;
  347. ThePath : RawByteString;
  348. Begin
  349. If SearchPath and (pos('/',pathname)=0) Then
  350. Begin
  351. // The above could be better. (check if not escaped/quoted '/'s) ?
  352. // (Jilles says this is ok)
  353. // Stevens says only search if newcmd contains no '/'
  354. // fsearch is not ansistring clean yet.
  355. ThePath:=fpgetenv('PATH');
  356. SetCodePage(ThePath,DefaultSystemCodePage,false);
  357. SetCodePage(ThePath,DefaultFileSystemCodePage,true);
  358. if thepath='' then
  359. thepath:='.'; // FreeBSD uses _PATH_DEFPATH = /usr/bin:/bin
  360. // but a quick check showed that _PATH_DEFPATH
  361. // varied from OS to OS
  362. newcmd:=ToSingleByteFileSystemEncodedFileName(FSearch(pathname,thepath,NoCurrentDirectory));
  363. // FreeBSD libc keeps on trying till a file is successfully run.
  364. // Stevens says "try each path prefix"
  365. // execp puts newcmd here.
  366. args^:=pchar(newcmd);
  367. End else
  368. newcmd:=ToSingleByteFileSystemEncodedFileName(pathname);
  369. // repeat
  370. // if searchpath then args^:=pchar(commandtorun)
  371. IntFpExecVEMaybeP:=fpExecVE(newcmd,Args,MyEnv);
  372. {
  373. // Code that if exec fails due to permissions, tries to run it with sh
  374. // Should we deallocate p on fail? -> no fpexit is run no matter what
  375. //
  376. }
  377. // if intfpexecvemaybep=-1 then seach next file.
  378. // until (Goexit) or SearchExit;
  379. {
  380. If IntFpExec=-1 Then
  381. Begin
  382. Error:=fpGetErrno
  383. Case Error of
  384. ESysE2Big : Exit(-1);
  385. ESysELoop,
  386. : Exit(-1);
  387. }
  388. end;
  389. function intFpExecl (Const PathName:RawByteString;const s:array of RawByteString;MyEnv:ppchar;SearchPath:Boolean):cint;
  390. { Handles the array of ansistring -> ppchar conversion.
  391. Base for the the "l" variants.
  392. }
  393. var p:ppchar;
  394. i:integer;
  395. s2:array of Rawbytestring;
  396. begin
  397. If PathName='' Then
  398. Begin
  399. fpsetErrno(ESysEnoEnt);
  400. Exit(-1); // Errno?
  401. End;
  402. setlength(s2,high(s)+1);
  403. for i:=low(s) to high(s) do
  404. s2[i]:=ToSingleByteFileSystemEncodedFileName(s[i]);
  405. p:=ArrayStringToPPchar(s2,1);
  406. if p=NIL Then
  407. Begin
  408. GetMem(p,2*sizeof(pchar));
  409. if p=nil then
  410. begin
  411. {$ifdef xunix}
  412. fpseterrno(ESysEnoMem);
  413. {$endif}
  414. fpseterrno(ESysEnoEnt);
  415. exit(-1);
  416. end;
  417. p[1]:=nil;
  418. End;
  419. p^:=pchar(PathName);
  420. IntFPExecL:=intFpExecVEMaybeP(PathName,p,MyEnv,SearchPath);
  421. // If we come here, no attempts were executed successfully.
  422. Freemem(p);
  423. end;
  424. function FpExecLE (Const PathName:RawByteString;const S:Array Of RawByteString;MyEnv:ppchar):cint;
  425. Begin
  426. FpExecLE:=intFPExecl(PathName,s,MyEnv,false);
  427. End;
  428. function FpExecL(Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  429. Begin
  430. FpExecL:=intFPExecl(PathName,S,EnvP,false);
  431. End;
  432. function FpExecLP(Const PathName:RawByteString;const S:Array Of RawByteString):cint;
  433. Begin
  434. FpExecLP:=intFPExecl(PathName,S,EnvP,True);
  435. End;
  436. function FpExecLPE(Const PathName:RawByteString;const S:Array Of RawByteString;env:ppchar):cint;
  437. Begin
  438. FpExecLPE:=intFPExecl(PathName,S,Env,True);
  439. End;
  440. function FpExecV(Const PathName:RawByteString;args:ppchar):cint;
  441. Begin
  442. fpexecV:=intFpExecVEMaybeP (PathName,args,envp,false);
  443. End;
  444. function FpExecVP(Const PathName:RawByteString;args:ppchar):cint;
  445. Begin
  446. fpexecVP:=intFpExecVEMaybeP (PathName,args,envp,true);
  447. End;
  448. function FpExecVPE(Const PathName:RawByteString;args,env:ppchar):cint;
  449. Begin
  450. fpexecVPE:=intFpExecVEMaybeP (PathName,args,env,true);
  451. End;
  452. // exect and execvP (ExecCapitalP) are not implement
  453. // Non POSIX anyway.
  454. // Exect turns on tracing for the process
  455. // execvP has the searchpath as array of ansistring ( const char *search_path)
  456. {$define FPC_USE_FPEXEC}
  457. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  458. {$define SHELL_USE_FPEXEC}
  459. {$endif}
  460. {$ifdef FPC_USE_LIBC}
  461. function xfpsystem(p:pchar):cint; cdecl; external clib name 'system';
  462. Function fpSystem(const Command:RawByteString):cint;
  463. var
  464. cmd: RawByteString;
  465. begin
  466. cmd:=ToSingleByteFileSystemEncodedFileName(Command);
  467. fpsystem:=xfpsystem(pchar(cmd));
  468. end;
  469. {$else}
  470. Function fpSystem(const Command:RawByteString):cint;
  471. var
  472. pid,savedpid : cint;
  473. pstat : cint;
  474. ign,intact,
  475. quitact : SigactionRec;
  476. newsigblock,
  477. oldsigblock : tsigset;
  478. {$ifndef SHELL_USE_FPEXEC}
  479. p : ppchar;
  480. {$endif}
  481. cmd : RawByteString;
  482. begin { Changes as above }
  483. { fpexec* take care of converting the command to the right code page }
  484. if command='' then exit(1);
  485. {$ifndef SHELL_USE_FPEXEC}
  486. p:=CreateShellArgv(command);
  487. {$endif}
  488. ign.sa_handler:=SigActionHandler(SIG_IGN);
  489. fpsigemptyset(ign.sa_mask);
  490. ign.sa_flags:=0;
  491. fpsigaction(SIGINT, @ign, @intact);
  492. fpsigaction(SIGQUIT, @ign, @quitact);
  493. fpsigemptyset(newsigblock);
  494. fpsigaddset(newsigblock,SIGCHLD);
  495. fpsigprocmask(SIG_BLOCK,newsigblock,oldsigblock);
  496. {$ifdef USE_VFORK}
  497. pid:=fpvfork;
  498. {$else USE_VFORK}
  499. pid:=fpfork;
  500. {$endif USE_VFORK}
  501. if pid=0 then // We are in the Child
  502. begin
  503. fpsigaction(SIGINT,@intact,NIL);
  504. fpsigaction(SIGQUIT,@quitact,NIL);
  505. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  506. {$ifndef SHELL_USE_FPEXEC}
  507. fpExecve(p^,p,envp);
  508. {$else}
  509. fpexecl('/bin/sh',['-c',Command]);
  510. {$endif}
  511. fpExit(127); // was exit(127)!! We must exit the Process, not the function
  512. end
  513. else if (pid<>-1) then // Successfull started
  514. begin
  515. savedpid:=pid;
  516. repeat
  517. pid:=fpwaitpid(savedpid,@pstat,0);
  518. until (pid<>-1) and (fpgeterrno()<>ESysEintr);
  519. if pid=-1 Then
  520. fpsystem:=-1
  521. else
  522. fpsystem:=pstat;
  523. end
  524. else // no success
  525. fpsystem:=-1;
  526. fpsigaction(SIGINT,@intact,NIL);
  527. fpsigaction(SIGQUIT,@quitact,NIL);
  528. fpsigprocmask(SIG_SETMASK,@oldsigblock,NIL);
  529. {$ifndef SHELL_USE_FPEXEC}
  530. FreeShellArgV(p);
  531. {$endif}
  532. end;
  533. {$endif}
  534. Function WIFSTOPPED(Status: Integer): Boolean;
  535. begin
  536. WIFSTOPPED:=((Status and $FF)=$7F);
  537. end;
  538. Function W_EXITCODE(ReturnCode, Signal: Integer): Integer;
  539. begin
  540. W_EXITCODE:=(ReturnCode shl 8) or Signal;
  541. end;
  542. Function W_STOPCODE(Signal: Integer): Integer;
  543. begin
  544. W_STOPCODE:=(Signal shl 8) or $7F;
  545. end;
  546. {$IFNDEF DONT_READ_TIMEZONE}
  547. { Include timezone handling routines which use /usr/share/timezone info }
  548. {$i timezone.inc}
  549. {$endif}
  550. {******************************************************************************
  551. FileSystem calls
  552. ******************************************************************************}
  553. Function fpFlock (var T : text;mode : cint) : cint;
  554. begin
  555. {$ifndef beos}
  556. fpFlock:=fpFlock(TextRec(T).Handle,mode);
  557. {$endif}
  558. end;
  559. Function fpFlock (var F : File;mode : cint) :cint;
  560. begin
  561. {$ifndef beos}
  562. fpFlock:=fpFlock(FileRec(F).Handle,mode);
  563. {$endif}
  564. end;
  565. Function SelectText(var T:Text;TimeOut :PTimeval):cint;
  566. Var
  567. F:TfdSet;
  568. begin
  569. if textrec(t).mode=fmclosed then
  570. begin
  571. fpseterrno(ESysEBADF);
  572. exit(-1);
  573. end;
  574. FpFD_ZERO(f);
  575. fpFD_SET(textrec(T).handle,f);
  576. if textrec(T).mode=fminput then
  577. SelectText:=fpselect(textrec(T).handle+1,@f,nil,nil,TimeOut)
  578. else
  579. SelectText:=fpselect(textrec(T).handle+1,nil,@f,nil,TimeOut);
  580. end;
  581. Function SelectText(var T:Text;TimeOut :cint):cint;
  582. var
  583. p : PTimeVal;
  584. tv : TimeVal;
  585. begin
  586. if TimeOut=-1 then
  587. p:=nil
  588. else
  589. begin
  590. tv.tv_Sec:=Timeout div 1000;
  591. tv.tv_Usec:=(Timeout mod 1000)*1000;
  592. p:=@tv;
  593. end;
  594. SelectText:=SelectText(T,p);
  595. end;
  596. {******************************************************************************
  597. Directory
  598. ******************************************************************************}
  599. procedure SeekDir(p:pdir;loc:clong);
  600. begin
  601. if p=nil then
  602. begin
  603. fpseterrno(ESysEBADF);
  604. exit;
  605. end;
  606. {$if not(defined(bsd)) and not(defined(solaris)) and not(defined(beos)) and not(defined(aix)) }
  607. p^.dd_nextoff:=fplseek(p^.dd_fd,loc,seek_set);
  608. {$endif}
  609. {$if not(defined(beos))}
  610. p^.dd_size:=0;
  611. p^.dd_loc:=0;
  612. {$endif}
  613. end;
  614. function TellDir(p:pdir):TOff;
  615. begin
  616. if p=nil then
  617. begin
  618. fpseterrno(ESysEBADF);
  619. telldir:=-1;
  620. exit;
  621. end;
  622. {$ifndef beos}
  623. telldir:=fplseek(p^.dd_fd,0,seek_cur)
  624. {$endif}
  625. { We could try to use the nextoff field here, but on my 1.2.13
  626. kernel, this gives nothing... This may have to do with
  627. the readdir implementation of libc... I also didn't find any trace of
  628. the field in the kernel code itself, So I suspect it is an artifact of libc.
  629. Michael. }
  630. end;
  631. {******************************************************************************
  632. Pipes/Fifo
  633. ******************************************************************************}
  634. Procedure OpenPipe(var F:Text);
  635. begin
  636. case textrec(f).mode of
  637. fmoutput :
  638. if textrec(f).userdata[1]<>P_OUT then
  639. textrec(f).mode:=fmclosed;
  640. fminput :
  641. if textrec(f).userdata[1]<>P_IN then
  642. textrec(f).mode:=fmclosed;
  643. else
  644. textrec(f).mode:=fmclosed;
  645. end;
  646. end;
  647. Function IOPipe(var F:text):cint;
  648. begin
  649. IOPipe:=0;
  650. case textrec(f).mode of
  651. fmoutput :
  652. begin
  653. { first check if we need something to write, else we may
  654. get a SigPipe when Close() is called (PFV) }
  655. if textrec(f).bufpos>0 then
  656. IOPipe:=fpwrite(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufpos);
  657. end;
  658. fminput : Begin
  659. textrec(f).bufend:=fpread(textrec(f).handle,pchar(textrec(f).bufptr),textrec(f).bufsize);
  660. IOPipe:=textrec(f).bufend;
  661. End;
  662. end;
  663. textrec(f).bufpos:=0;
  664. end;
  665. Function FlushPipe(var F:Text):cint;
  666. begin
  667. FlushPipe:=0;
  668. if (textrec(f).mode=fmoutput) and (textrec(f).bufpos<>0) then
  669. FlushPipe:=IOPipe(f);
  670. textrec(f).bufpos:=0;
  671. end;
  672. Function ClosePipe(var F:text):cint;
  673. begin
  674. textrec(f).mode:=fmclosed;
  675. ClosePipe:=fpclose(textrec(f).handle);
  676. end;
  677. Function AssignPipe(var pipe_in,pipe_out:text):cint;
  678. {
  679. Sets up a pair of file variables, which act as a pipe. The first one can
  680. be read from, the second one can be written to.
  681. }
  682. var
  683. f_in,f_out : cint;
  684. begin
  685. if AssignPipe(f_in,f_out)=-1 then
  686. exit(-1);
  687. { Set up input }
  688. Assign(Pipe_in,'');
  689. Textrec(Pipe_in).Handle:=f_in;
  690. Textrec(Pipe_in).Mode:=fmInput;
  691. Textrec(Pipe_in).userdata[1]:=P_IN;
  692. TextRec(Pipe_in).OpenFunc:=@OpenPipe;
  693. TextRec(Pipe_in).InOutFunc:=@IOPipe;
  694. TextRec(Pipe_in).FlushFunc:=@FlushPipe;
  695. TextRec(Pipe_in).CloseFunc:=@ClosePipe;
  696. { Set up output }
  697. Assign(Pipe_out,'');
  698. Textrec(Pipe_out).Handle:=f_out;
  699. Textrec(Pipe_out).Mode:=fmOutput;
  700. Textrec(Pipe_out).userdata[1]:=P_OUT;
  701. TextRec(Pipe_out).OpenFunc:=@OpenPipe;
  702. TextRec(Pipe_out).InOutFunc:=@IOPipe;
  703. TextRec(Pipe_out).FlushFunc:=@FlushPipe;
  704. TextRec(Pipe_out).CloseFunc:=@ClosePipe;
  705. AssignPipe:=0;
  706. end;
  707. Function AssignPipe(var pipe_in,pipe_out:file):cint;
  708. {
  709. Sets up a pair of file variables, which act as a pipe. The first one can
  710. be read from, the second one can be written to.
  711. If the operation was unsuccesful,
  712. }
  713. var
  714. f_in,f_out : cint;
  715. begin
  716. if AssignPipe(f_in,f_out)=-1 then
  717. exit(-1);
  718. { Set up input }
  719. Assign(Pipe_in,'');
  720. Filerec(Pipe_in).Handle:=f_in;
  721. Filerec(Pipe_in).Mode:=fmInput;
  722. Filerec(Pipe_in).recsize:=1;
  723. Filerec(Pipe_in).userdata[1]:=P_IN;
  724. { Set up output }
  725. Assign(Pipe_out,'');
  726. Filerec(Pipe_out).Handle:=f_out;
  727. Filerec(Pipe_out).Mode:=fmoutput;
  728. Filerec(Pipe_out).recsize:=1;
  729. Filerec(Pipe_out).userdata[1]:=P_OUT;
  730. AssignPipe:=0;
  731. end;
  732. Function PCloseText(Var F:text):cint;
  733. {
  734. May not use @PClose due overloading
  735. }
  736. begin
  737. PCloseText:=PClose(f);
  738. end;
  739. Function POpen_internal(var F:text;const Prog:RawByteString;rw:char):cint;
  740. {
  741. Starts the program in 'Prog' and makes it's input or out put the
  742. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  743. F, will be read from stdin by the program in 'Prog'. The inverse is true
  744. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  745. read from 'f'.
  746. }
  747. var
  748. pipi,
  749. pipo : text;
  750. pid : cint;
  751. pl : ^cint;
  752. {$if not defined(FPC_USE_FPEXEC) or defined(USE_VFORK)}
  753. pp : array[0..3] of pchar;
  754. temp : string[255];
  755. {$endif not FPC_USE_FPEXEC or USE_VFORK}
  756. ret : cint;
  757. begin
  758. rw:=upcase(rw);
  759. if not (rw in ['R','W']) then
  760. begin
  761. FpSetErrno(ESysEnoent);
  762. exit(-1);
  763. end;
  764. ret:=AssignPipe(pipi,pipo);
  765. if ret=-1 then
  766. exit(-1);
  767. {$ifdef USE_VFORK}
  768. pid:=fpvfork;
  769. {$else USE_VFORK}
  770. pid:=fpfork;
  771. {$endif USE_VFORK}
  772. if pid=-1 then
  773. begin
  774. close(pipi);
  775. close(pipo);
  776. exit(-1);
  777. end;
  778. if pid=0 then
  779. begin
  780. { We're in the child }
  781. if rw='W' then
  782. begin
  783. if (textrec(pipi).handle <> stdinputhandle) then
  784. begin
  785. ret:=fpdup2(pipi,input);
  786. {$ifdef USE_VFORK}
  787. fpclose(textrec(pipi).handle);
  788. {$else USE_VFORK}
  789. close(pipi);
  790. {$endif USE_VFORK}
  791. end;
  792. {$ifdef USE_VFORK}
  793. fpclose(textrec(pipo).handle);
  794. {$else USE_VFORK}
  795. close(pipo);
  796. {$endif USE_VFORK}
  797. if ret=-1 then
  798. fpexit(127);
  799. end
  800. else
  801. begin
  802. {$ifdef USE_VFORK}
  803. fpclose(textrec(pipi).handle);
  804. {$else USE_VFORK}
  805. close(pipi);
  806. {$endif USE_VFORK}
  807. if (textrec(pipo).handle <> stdoutputhandle) then
  808. begin
  809. ret:=fpdup2(pipo,output);
  810. {$ifdef USE_VFORK}
  811. fpclose(textrec(pipo).handle);
  812. {$else USE_VFORK}
  813. close(pipo);
  814. {$endif USE_VFORK}
  815. end;
  816. if ret=-1 then
  817. fpexit(127);
  818. end;
  819. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  820. fpexecl(pchar('/bin/sh'),['-c',Prog]);
  821. {$else}
  822. temp:='/bin/sh'#0'-c'#0;
  823. pp[0]:=@temp[1];
  824. pp[1]:=@temp[9];
  825. pp[2]:=@prog[1];
  826. pp[3]:=Nil;
  827. fpExecve('/bin/sh',@pp,envp);
  828. {$endif}
  829. fpexit(127);
  830. end
  831. else
  832. begin
  833. { We're in the parent }
  834. if rw='W' then
  835. begin
  836. close(pipi);
  837. f:=pipo;
  838. end
  839. else
  840. begin
  841. close(pipo);
  842. f:=pipi;
  843. end;
  844. textrec(f).bufptr:=@textrec(f).buffer;
  845. {Save the process ID - needed when closing }
  846. pl:=pcint(@textrec(f).userdata[2]);
  847. { avoid alignment error on sparc }
  848. move(pid,pl^,sizeof(pid));
  849. textrec(f).closefunc:=@PCloseText;
  850. end;
  851. POpen_internal:=0;
  852. end;
  853. Function POpen_internal(var F:file;const Prog:RawByteString;rw:char):cint;
  854. {
  855. Starts the program in 'Prog' and makes it's input or out put the
  856. other end of a pipe. If rw is 'w' or 'W', then whatever is written to
  857. F, will be read from stdin by the program in 'Prog'. The inverse is true
  858. for 'r' or 'R' : whatever the program in 'Prog' writes to stdout, can be
  859. read from 'f'.
  860. }
  861. var
  862. pipi,
  863. pipo : file;
  864. pid : cint;
  865. pl : ^cint;
  866. {$if not defined(FPC_USE_FPEXEC) or defined(USE_VFORK)}
  867. pp : array[0..3] of pchar;
  868. temp : string[255];
  869. {$endif not FPC_USE_FPEXEC or USE_VFORK}
  870. ret : cint;
  871. begin
  872. rw:=upcase(rw);
  873. if not (rw in ['R','W']) then
  874. begin
  875. FpSetErrno(ESysEnoent);
  876. exit(-1);
  877. end;
  878. ret:=AssignPipe(pipi,pipo);
  879. if ret=-1 then
  880. exit(-1);
  881. {$ifdef USE_VFORK}
  882. pid:=fpvfork;
  883. {$else USE_VFORK}
  884. pid:=fpfork;
  885. {$endif USE_VFORK}
  886. if pid=-1 then
  887. begin
  888. close(pipi);
  889. close(pipo);
  890. exit(-1);
  891. end;
  892. if pid=0 then
  893. begin
  894. { We're in the child }
  895. if rw='W' then
  896. begin
  897. if (filerec(pipi).handle <> stdinputhandle) then
  898. begin
  899. ret:=fpdup2(filerec(pipi).handle,stdinputhandle);
  900. {$ifdef USE_VFORK}
  901. fpclose(filerec(pipi).handle);
  902. {$else USE_VFORK}
  903. close(pipi);
  904. {$endif USE_VFORK}
  905. end;
  906. {$ifdef USE_VFORK}
  907. fpclose(filerec(pipo).handle);
  908. {$else USE_VFORK}
  909. close(pipo);
  910. {$endif USE_VFORK}
  911. if ret=-1 then
  912. fpexit(127);
  913. end
  914. else
  915. begin
  916. {$ifdef USE_VFORK}
  917. fpclose(filerec(pipi).handle);
  918. {$else USE_VFORK}
  919. close(pipi);
  920. {$endif USE_VFORK}
  921. if (filerec(pipo).handle <> stdoutputhandle) then
  922. begin
  923. ret:=fpdup2(filerec(pipo).handle,stdoutputhandle);
  924. {$ifdef USE_VFORK}
  925. fpclose(filerec(pipo).handle);
  926. {$else USE_VFORK}
  927. close(pipo);
  928. {$endif USE_VFORK}
  929. end;
  930. if ret=-1 then
  931. fpexit(127);
  932. end;
  933. {$if defined(FPC_USE_FPEXEC) and not defined(USE_VFORK)}
  934. fpexecl(pchar('/bin/sh'),['-c',Prog]);
  935. {$else}
  936. temp:='/bin/sh'#0'-c'#0;
  937. pp[0]:=@temp[1];
  938. pp[1]:=@temp[9];
  939. pp[2]:=@prog[1];
  940. pp[3]:=Nil;
  941. fpExecve('/bin/sh',@pp,envp);
  942. {$endif}
  943. fpexit(127);
  944. end
  945. else
  946. begin
  947. { We're in the parent }
  948. if rw='W' then
  949. begin
  950. close(pipi);
  951. f:=pipo;
  952. end
  953. else
  954. begin
  955. close(pipo);
  956. f:=pipi;
  957. end;
  958. {Save the process ID - needed when closing }
  959. pl:=pcint(@filerec(f).userdata[2]);
  960. { avoid alignment error on sparc }
  961. move(pid,pl^,sizeof(pid));
  962. end;
  963. POpen_internal:=0;
  964. end;
  965. Function POpen(var F:text;const Prog:RawByteString;rw:char):cint;
  966. begin
  967. { can't do the ToSingleByteFileSystemEncodedFileName() conversion inside
  968. POpen_internal, because this may destroy the temp rawbytestring result
  969. of that function in the parent before the child is finished with it }
  970. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  971. end;
  972. Function POpen(var F:file;const Prog:RawByteString;rw:char):cint;
  973. begin
  974. { can't do the ToSingleByteFileSystemEncodedFileName() conversion inside
  975. POpen_internal, because this may destroy the temp rawbytestring result
  976. of that function in the parent before the child is finished with it }
  977. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  978. end;
  979. function POpen(var F: text; const Prog: UnicodeString; rw: char): cint;
  980. begin
  981. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  982. end;
  983. function POpen(var F: file; const Prog: UnicodeString; rw: char): cint;
  984. begin
  985. POpen:=POpen_internal(F,ToSingleByteFileSystemEncodedFileName(Prog),rw);
  986. end;
  987. Function AssignStream(Var StreamIn,Streamout:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  988. {
  989. Starts the program in 'Prog' and makes its input and output the
  990. other end of two pipes, which are the stdin and stdout of a program
  991. specified in 'Prog'.
  992. streamout can be used to write to the program, streamin can be used to read
  993. the output of the program. See the following diagram :
  994. Parent Child
  995. STreamout --> Input
  996. Streamin <-- Output
  997. Return value is the process ID of the process being spawned, or -1 in case of failure.
  998. }
  999. var
  1000. pipi,
  1001. pipo : text;
  1002. pid : cint;
  1003. pl : ^cint;
  1004. begin
  1005. AssignStream:=-1;
  1006. if fpAccess(prog,X_OK)<>0 then
  1007. exit(-1);
  1008. if AssignPipe(streamin,pipo)=-1 Then
  1009. exit(-1);
  1010. if AssignPipe(pipi,streamout)=-1 Then
  1011. begin
  1012. close(streamin);
  1013. close(pipo);
  1014. exit(-1);
  1015. end;
  1016. pid:=fpfork;
  1017. if pid=-1 then
  1018. begin
  1019. close(pipi);
  1020. close(pipo);
  1021. close (streamin);
  1022. close (streamout);
  1023. exit;
  1024. end;
  1025. if pid=0 then
  1026. begin
  1027. { We're in the child }
  1028. { Close what we don't need }
  1029. close(streamout);
  1030. close(streamin);
  1031. if fpdup2(pipi,input)=-1 Then
  1032. halt(127);
  1033. close(pipi);
  1034. If fpdup2(pipo,output)=-1 Then
  1035. halt (127);
  1036. close(pipo);
  1037. fpExecl(Prog,args);
  1038. halt(127);
  1039. end
  1040. else
  1041. begin
  1042. { we're in the parent}
  1043. close(pipo);
  1044. close(pipi);
  1045. {Save the process ID - needed when closing }
  1046. pl:=pcint(@textrec(StreamIn).userdata[2]);
  1047. { avoid alignment error on sparc }
  1048. move(pid,pl^,sizeof(pid));
  1049. textrec(StreamIn).closefunc:=@PCloseText;
  1050. {Save the process ID - needed when closing }
  1051. pl:=pcint(@textrec(StreamOut).userdata[2]);
  1052. { avoid alignment error on sparc }
  1053. move(pid,pl^,sizeof(pid));
  1054. textrec(StreamOut).closefunc:=@PCloseText;
  1055. AssignStream:=Pid;
  1056. end;
  1057. end;
  1058. Function AssignStream(Var StreamIn,Streamout,streamerr:text;Const Prog:ansiString;const args : array of ansistring) : cint;
  1059. {
  1060. Starts the program in 'prog' and makes its input, output and error output the
  1061. other end of three pipes, which are the stdin, stdout and stderr of a program
  1062. specified in 'prog'.
  1063. StreamOut can be used to write to the program, StreamIn can be used to read
  1064. the output of the program, StreamErr reads the error output of the program.
  1065. See the following diagram :
  1066. Parent Child
  1067. StreamOut --> StdIn (input)
  1068. StreamIn <-- StdOut (output)
  1069. StreamErr <-- StdErr (error output)
  1070. }
  1071. var
  1072. PipeIn, PipeOut, PipeErr: text;
  1073. pid: cint;
  1074. pl: ^cint;
  1075. begin
  1076. AssignStream := -1;
  1077. if fpAccess(prog,X_OK)<>0 then
  1078. exit(-1);
  1079. // Assign pipes
  1080. if AssignPipe(StreamIn, PipeOut)=-1 Then
  1081. Exit(-1);
  1082. If AssignPipe(StreamErr, PipeErr)=-1 Then
  1083. begin
  1084. Close(StreamIn);
  1085. Close(PipeOut);
  1086. exit(-1);
  1087. end;
  1088. if AssignPipe(PipeIn, StreamOut)=-1 Then
  1089. begin
  1090. Close(StreamIn);
  1091. Close(PipeOut);
  1092. Close(StreamErr);
  1093. Close(PipeErr);
  1094. exit(-1);
  1095. end;
  1096. // Fork
  1097. pid := fpFork;
  1098. if pid=-1 then begin
  1099. Close(StreamIn);
  1100. Close(PipeOut);
  1101. Close(StreamErr);
  1102. Close(PipeErr);
  1103. Close(PipeIn);
  1104. Close(StreamOut);
  1105. exit(-1);
  1106. end;
  1107. if pid = 0 then begin
  1108. // *** We are in the child ***
  1109. // Close what we don not need
  1110. Close(StreamOut);
  1111. Close(StreamIn);
  1112. Close(StreamErr);
  1113. // Connect pipes
  1114. if fpdup2(PipeIn, Input)=-1 Then
  1115. Halt(127);
  1116. Close(PipeIn);
  1117. if fpdup2(PipeOut, Output)=-1 Then
  1118. Halt(127);
  1119. Close(PipeOut);
  1120. if fpdup2(PipeErr, StdErr)=-1 Then
  1121. Halt(127);
  1122. Close(PipeErr);
  1123. // Execute program
  1124. fpExecl(Prog,args);
  1125. Halt(127);
  1126. end else begin
  1127. // *** We are in the parent ***
  1128. Close(PipeErr);
  1129. Close(PipeOut);
  1130. Close(PipeIn);
  1131. // Save the process ID - needed when closing
  1132. pl := pcint(@TextRec(StreamIn).userdata[2]);
  1133. { avoid alignment error on sparc }
  1134. move(pid,pl^,sizeof(pid));
  1135. TextRec(StreamIn).closefunc := @PCloseText;
  1136. // Save the process ID - needed when closing
  1137. pl := pcint(@TextRec(StreamOut).userdata[2]);
  1138. { avoid alignment error on sparc }
  1139. move(pid,pl^,sizeof(pid));
  1140. TextRec(StreamOut).closefunc := @PCloseText;
  1141. // Save the process ID - needed when closing
  1142. pl := pcint(@TextRec(StreamErr).userdata[2]);
  1143. { avoid alignment error on sparc }
  1144. move(pid,pl^,sizeof(pid));
  1145. TextRec(StreamErr).closefunc := @PCloseText;
  1146. AssignStream := pid;
  1147. end;
  1148. end;
  1149. {******************************************************************************
  1150. General information calls
  1151. ******************************************************************************}
  1152. {$if defined(Linux)}
  1153. Function GetDomainName:String; { linux only!}
  1154. // domainname is a glibc extension.
  1155. {
  1156. Get machines domain name. Returns empty string if not set.
  1157. }
  1158. Var
  1159. Sysn : utsname;
  1160. begin
  1161. If fpUname(sysn)<>0 then
  1162. getdomainname:=''
  1163. else
  1164. getdomainname:=strpas(@Sysn.domain[0]);
  1165. end;
  1166. {$endif}
  1167. {$ifdef sunos}
  1168. { sunos doesn't support GetDomainName, see also
  1169. http://www.sun.com/software/solaris/programs/abi/appcert_faq.xml#q18
  1170. }
  1171. Function GetDomainName:String;
  1172. begin
  1173. GetDomainName:='';
  1174. end;
  1175. {$endif sunos}
  1176. {$ifdef android}
  1177. { android doesn't seem to implement GetDomainName
  1178. }
  1179. Function GetDomainName:String;
  1180. begin
  1181. GetDomainName:='';
  1182. end;
  1183. {$endif}
  1184. {$if defined(BSD) or defined(aix)}
  1185. function intGetDomainName(Name:PChar; NameLen:Cint):cint;
  1186. {$ifndef FPC_USE_LIBC}
  1187. external name 'FPC_SYSC_GETDOMAINNAME';
  1188. {$else FPC_USE_LIBC}
  1189. cdecl; external clib name 'getdomainname';
  1190. {$endif FPC_USE_LIBC}
  1191. Function GetDomainName:String; { linux only!}
  1192. // domainname is a glibc extension.
  1193. {
  1194. Get machines domain name. Returns empty string if not set.
  1195. }
  1196. begin
  1197. if intGetDomainName(@getdomainname[1],255)=-1 then
  1198. getdomainname:=''
  1199. else
  1200. getdomainname[0]:=chr(strlen(@getdomainname[1]));
  1201. end;
  1202. {$endif}
  1203. Function GetHostName:String;
  1204. {
  1205. Get machines name. Returns empty string if not set.
  1206. }
  1207. Var
  1208. Sysn : utsname;
  1209. begin
  1210. If fpuname(sysn)=-1 then
  1211. gethostname:=''
  1212. else
  1213. gethostname:=strpas(@Sysn.nodename[0]);
  1214. end;
  1215. {******************************************************************************
  1216. Utility calls
  1217. ******************************************************************************}
  1218. Function FSearch(const path:RawByteString;dirlist:RawByteString;CurrentDirStrategy:TFSearchOption):RawByteString;
  1219. {
  1220. Searches for a file 'path' in the list of direcories in 'dirlist'.
  1221. returns an empty string if not found. Wildcards are NOT allowed.
  1222. If dirlist is empty, it is set to '.'
  1223. This function tries to make FSearch use ansistrings, and decrease
  1224. stringhandling overhead at the same time.
  1225. }
  1226. Var
  1227. mypath,
  1228. mydir,NewDir : RawByteString;
  1229. p1 : cint;
  1230. Info : Stat;
  1231. i,j : cint;
  1232. p : pchar;
  1233. Begin
  1234. SetCodePage(dirlist,DefaultFileSystemCodePage);
  1235. if CurrentDirStrategy=CurrentDirectoryFirst Then
  1236. Dirlist:=ToSingleByteFileSystemEncodedFileName('.:')+dirlist {Make sure current dir is first to be searched.}
  1237. else if CurrentDirStrategy=CurrentDirectoryLast Then
  1238. Dirlist:=dirlist+ToSingleByteFileSystemEncodedFileName('.:'); {Make sure current dir is last to be searched.}
  1239. {Replace ':' and ';' with #0}
  1240. for p1:=1 to length(dirlist) do
  1241. if (dirlist[p1]=':') or (dirlist[p1]=';') then
  1242. dirlist[p1]:=#0;
  1243. {Check for WildCards}
  1244. If (Pos('?',Path) <> 0) or (Pos('*',Path) <> 0) Then
  1245. FSearch:='' {No wildcards allowed in these things.}
  1246. Else
  1247. Begin
  1248. mypath:=ToSingleByteFileSystemEncodedFileName(path);
  1249. p:=pchar(dirlist);
  1250. i:=length(dirlist);
  1251. j:=1;
  1252. Repeat
  1253. mydir:=RawByteString(p);
  1254. if (length(mydir)>0) and (mydir[length(mydir)]<>'/') then
  1255. begin
  1256. { concatenate character without influencing code page }
  1257. setlength(mydir,length(mydir)+1);
  1258. mydir[length(mydir)]:='/';
  1259. end;
  1260. NewDir:=mydir+mypath;
  1261. if (FpStat(NewDir,Info)>=0) and
  1262. (not fpS_ISDIR(Info.st_Mode)) then
  1263. Begin
  1264. If Pos('./',NewDir)=1 Then
  1265. Delete(NewDir,1,2);
  1266. {DOS strips off an initial .\}
  1267. End
  1268. Else
  1269. NewDir:='';
  1270. while (j<=i) and (p^<>#0) do begin inc(j); inc(p); end;
  1271. if p^=#0 then inc(p);
  1272. Until (j>=i) or (Length(NewDir) > 0);
  1273. FSearch:=NewDir;
  1274. SetCodePage(FSearch,DefaultRTLFileSystemCodePage);
  1275. End;
  1276. End;
  1277. Function FSearch(const path:RawByteString;dirlist:RawByteString):RawByteString;
  1278. Begin
  1279. FSearch:=FSearch(path,dirlist,CurrentDirectoryFirst);
  1280. End;
  1281. function FSearch(const path: UnicodeString; dirlist: UnicodeString; CurrentDirStrategy: TFSearchOption): UnicodeString;
  1282. begin
  1283. FSearch:=FSearch(ToSingleByteFileSystemEncodedFileName(path),ToSingleByteFileSystemEncodedFileName(dirlist),CurrentDirStrategy);
  1284. end;
  1285. function FSearch(const path: UnicodeString; dirlist: UnicodeString): UnicodeString;
  1286. begin
  1287. FSearch:=FSearch(ToSingleByteFileSystemEncodedFileName(path),ToSingleByteFileSystemEncodedFileName(dirlist),CurrentDirectoryFirst);
  1288. end;
  1289. {$ifdef android}
  1290. {$I unixandroid.inc}
  1291. {$endif android}
  1292. {$if declared(UseTZThreading)}
  1293. procedure InitTZThreading;
  1294. begin
  1295. UseTZThreading:=True;
  1296. InitCriticalSection(TZInfoCS);
  1297. end;
  1298. {$endif}
  1299. Initialization
  1300. {$if declared(UseTZThreading)}
  1301. RegisterLazyInitThreadingProc(@InitTZThreading);
  1302. {$endif}
  1303. {$IFNDEF DONT_READ_TIMEZONE}
  1304. InitLocalTime;
  1305. {$endif}
  1306. {$ifdef android}
  1307. InitLocalTime;
  1308. {$endif android}
  1309. finalization
  1310. {$IFNDEF DONT_READ_TIMEZONE}
  1311. DoneLocalTime;
  1312. {$endif}
  1313. {$if declared(UseTZThreading)}
  1314. if UseTZThreading then
  1315. DoneCriticalSection(TZInfoCS);
  1316. {$endif}
  1317. End.