unix.pp 32 KB

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