2
0

unix.pp 33 KB

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