unix.pp 41 KB

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