unix.pp 32 KB

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