unix.pp 33 KB

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