2
0

sysutils.pp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by Florian Klaempfl
  4. member of the Free Pascal development team
  5. Sysutils unit for linux
  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 sysutils;
  13. interface
  14. {$MODE objfpc}
  15. {$MODESWITCH OUT}
  16. { force ansistrings }
  17. {$H+}
  18. {$if (defined(BSD) or defined(SUNOS)) and defined(FPC_USE_LIBC)}
  19. {$define USE_VFORK}
  20. {$endif}
  21. {$DEFINE OS_FILESETDATEBYNAME}
  22. {$DEFINE HAS_SLEEP}
  23. {$DEFINE HAS_OSERROR}
  24. {$DEFINE HAS_OSCONFIG}
  25. {$DEFINE HAS_TEMPDIR}
  26. {$DEFINE HASUNIX}
  27. {$DEFINE HASCREATEGUID}
  28. {$DEFINE HAS_OSUSERDIR}
  29. {$DEFINE HAS_LOCALTIMEZONEOFFSET}
  30. {$DEFINE HAS_GETTICKCOUNT64}
  31. { used OS file system APIs use ansistring }
  32. {$define SYSUTILS_HAS_ANSISTR_FILEUTIL_IMPL}
  33. { OS has an ansistring/single byte environment variable API }
  34. {$define SYSUTILS_HAS_ANSISTR_ENVVAR_IMPL}
  35. uses
  36. {$IFDEF LINUX}linux,{$ENDIF}
  37. {$IFDEF FreeBSD}freebsd,{$ENDIF}
  38. Unix,errors,sysconst,Unixtype;
  39. {$IF defined(LINUX) or defined(FreeBSD)}
  40. {$DEFINE HAVECLOCKGETTIME}
  41. {$ENDIF}
  42. { Include platform independent interface part }
  43. {$i sysutilh.inc}
  44. Function AddDisk(const path:string) : Byte;
  45. { the following is Kylix compatibility stuff, it should be moved to a
  46. special compatibilty unit (FK) }
  47. const
  48. RTL_SIGINT = 0;
  49. RTL_SIGFPE = 1;
  50. RTL_SIGSEGV = 2;
  51. RTL_SIGILL = 3;
  52. RTL_SIGBUS = 4;
  53. RTL_SIGQUIT = 5;
  54. RTL_SIGLAST = RTL_SIGQUIT;
  55. RTL_SIGDEFAULT = -1;
  56. type
  57. TSignalState = (ssNotHooked, ssHooked, ssOverridden);
  58. function InquireSignal(RtlSigNum: Integer): TSignalState;
  59. procedure AbandonSignalHandler(RtlSigNum: Integer);
  60. procedure HookSignal(RtlSigNum: Integer);
  61. procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean = True);
  62. implementation
  63. Uses
  64. {$ifdef FPC_USE_LIBC}initc{$ELSE}Syscall{$ENDIF}, Baseunix, unixutil;
  65. type
  66. tsiginfo = record
  67. oldsiginfo: sigactionrec;
  68. hooked: boolean;
  69. end;
  70. const
  71. rtlsig2ossig: array[RTL_SIGINT..RTL_SIGLAST] of byte =
  72. (SIGINT,SIGFPE,SIGSEGV,SIGILL,SIGBUS,SIGQUIT);
  73. { to avoid linking in all this stuff in every program,
  74. as it's unlikely to be used by anything but libraries
  75. }
  76. signalinfoinited: boolean = false;
  77. var
  78. siginfo: array[RTL_SIGINT..RTL_SIGLAST] of tsiginfo;
  79. oldsigfpe: SigActionRec; external name '_FPC_OLDSIGFPE';
  80. oldsigsegv: SigActionRec; external name '_FPC_OLDSIGSEGV';
  81. oldsigbus: SigActionRec; external name '_FPC_OLDSIGBUS';
  82. oldsigill: SigActionRec; external name '_FPC_OLDSIGILL';
  83. procedure defaultsighandler; external name '_FPC_DEFAULTSIGHANDLER';
  84. procedure installdefaultsignalhandler(signum: Integer; out oldact: SigActionRec); external name '_FPC_INSTALLDEFAULTSIGHANDLER';
  85. function InternalInquireSignal(RtlSigNum: Integer; out act: SigActionRec; frominit: boolean): TSignalState;
  86. begin
  87. result:=ssNotHooked;
  88. if (RtlSigNum<>RTL_SIGDEFAULT) and
  89. (RtlSigNum<RTL_SIGLAST) then
  90. begin
  91. if (frominit or
  92. siginfo[RtlSigNum].hooked) and
  93. (fpsigaction(rtlsig2ossig[RtlSigNum],nil,@act)=0) then
  94. begin
  95. if not frominit then
  96. begin
  97. { check whether the installed signal handler is still ours }
  98. {$if not defined(aix) and (not defined(linux) or not defined(cpupowerpc64))}
  99. if (pointer(act.sa_handler)=pointer(@defaultsighandler)) then
  100. {$else}
  101. { on aix and linux/ppc64, procedure addresses are actually
  102. descriptors -> check whether the code addresses inside the
  103. descriptors match, rather than the descriptors themselves }
  104. if (ppointer(act.sa_handler)^=ppointer(@defaultsighandler)^) then
  105. {$endif}
  106. result:=ssHooked
  107. else
  108. result:=ssOverridden;
  109. end
  110. else if IsLibrary then
  111. begin
  112. { library -> signals have not been hooked by system init code }
  113. exit
  114. end
  115. else
  116. begin
  117. { program -> signals have been hooked by system init code }
  118. if (byte(RtlSigNum) in [RTL_SIGFPE,RTL_SIGSEGV,RTL_SIGILL,RTL_SIGBUS]) then
  119. begin
  120. {$if not defined(aix) and (not defined(linux) or not defined(cpupowerpc64))}
  121. if (pointer(act.sa_handler)=pointer(@defaultsighandler)) then
  122. {$else}
  123. if (ppointer(act.sa_handler)^=ppointer(@defaultsighandler)^) then
  124. {$endif}
  125. result:=ssHooked
  126. else
  127. result:=ssOverridden;
  128. { return the original handlers as saved by the system unit
  129. (the current call to sigaction simply returned our
  130. system unit's installed handlers)
  131. }
  132. case RtlSigNum of
  133. RTL_SIGFPE:
  134. act:=oldsigfpe;
  135. RTL_SIGSEGV:
  136. act:=oldsigsegv;
  137. RTL_SIGILL:
  138. act:=oldsigill;
  139. RTL_SIGBUS:
  140. act:=oldsigbus;
  141. end;
  142. end
  143. else
  144. begin
  145. { these are not hooked in the startup code }
  146. result:=ssNotHooked;
  147. end
  148. end
  149. end
  150. end;
  151. end;
  152. procedure initsignalinfo;
  153. var
  154. i: Integer;
  155. begin
  156. for i:=RTL_SIGINT to RTL_SIGLAST do
  157. siginfo[i].hooked:=(InternalInquireSignal(i,siginfo[i].oldsiginfo,true)=ssHooked);
  158. signalinfoinited:=true;
  159. end;
  160. function InquireSignal(RtlSigNum: Integer): TSignalState;
  161. var
  162. act: SigActionRec;
  163. begin
  164. if not signalinfoinited then
  165. initsignalinfo;
  166. result:=InternalInquireSignal(RtlSigNum,act,false);
  167. end;
  168. procedure AbandonSignalHandler(RtlSigNum: Integer);
  169. begin
  170. if not signalinfoinited then
  171. initsignalinfo;
  172. if (RtlSigNum<>RTL_SIGDEFAULT) and
  173. (RtlSigNum<RTL_SIGLAST) then
  174. siginfo[RtlSigNum].hooked:=false;
  175. end;
  176. procedure HookSignal(RtlSigNum: Integer);
  177. var
  178. lowsig, highsig, i: Integer;
  179. begin
  180. if not signalinfoinited then
  181. initsignalinfo;
  182. if (RtlSigNum<>RTL_SIGDEFAULT) then
  183. begin
  184. lowsig:=RtlSigNum;
  185. highsig:=RtlSigNum;
  186. end
  187. else
  188. begin
  189. { we don't hook SIGINT and SIGQUIT by default }
  190. lowsig:=RTL_SIGFPE;
  191. highsig:=RTL_SIGBUS;
  192. end;
  193. { install the default rtl signal handler for the selected signal(s) }
  194. for i:=lowsig to highsig do
  195. begin
  196. installdefaultsignalhandler(rtlsig2ossig[i],siginfo[i].oldsiginfo);
  197. siginfo[i].hooked:=true;
  198. end;
  199. end;
  200. procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean = True);
  201. var
  202. act: SigActionRec;
  203. lowsig, highsig, i: Integer;
  204. state: TSignalState;
  205. begin
  206. if not signalinfoinited then
  207. initsignalinfo;
  208. if (RtlSigNum<>RTL_SIGDEFAULT) then
  209. begin
  210. lowsig:=RtlSigNum;
  211. highsig:=RtlSigNum;
  212. end
  213. else
  214. begin
  215. { we don't hook SIGINT and SIGQUIT by default }
  216. lowsig:=RTL_SIGFPE;
  217. highsig:=RTL_SIGBUS;
  218. end;
  219. for i:=lowsig to highsig do
  220. begin
  221. if not OnlyIfHooked or
  222. (InquireSignal(i)=ssHooked) then
  223. begin
  224. { restore the handler that was present when we hooked the signal,
  225. if we hooked it at one time or another. If the user doesn't
  226. want this, they have to call AbandonSignalHandler() first
  227. }
  228. if siginfo[i].hooked then
  229. act:=siginfo[i].oldsiginfo
  230. else
  231. begin
  232. fillchar(act,sizeof(act),0);
  233. pointer(act.sa_handler):=pointer(SIG_DFL);
  234. end;
  235. if (fpsigaction(rtlsig2ossig[RtlSigNum],@act,nil)=0) then
  236. siginfo[i].hooked:=false;
  237. end;
  238. end;
  239. end;
  240. {$Define OS_FILEISREADONLY} // Specific implementation for Unix.
  241. {$DEFINE FPC_FEXPAND_TILDE} { Tilde is expanded to home }
  242. {$DEFINE FPC_FEXPAND_GETENVPCHAR} { GetEnv result is a PChar }
  243. { Include platform independent implementation part }
  244. {$i sysutils.inc}
  245. { Include SysCreateGUID function }
  246. {$i suuid.inc}
  247. Const
  248. {Date Translation}
  249. C1970=2440588;
  250. D0 = 1461;
  251. D1 = 146097;
  252. D2 =1721119;
  253. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word);
  254. Var
  255. YYear,XYear,Temp,TempMonth : LongInt;
  256. Begin
  257. Temp:=((JulianDN-D2) shl 2)-1;
  258. JulianDN:=Temp Div D1;
  259. XYear:=(Temp Mod D1) or 3;
  260. YYear:=(XYear Div D0);
  261. Temp:=((((XYear mod D0)+4) shr 2)*5)-3;
  262. Day:=((Temp Mod 153)+5) Div 5;
  263. TempMonth:=Temp Div 153;
  264. If TempMonth>=10 Then
  265. Begin
  266. inc(YYear);
  267. dec(TempMonth,12);
  268. End;
  269. inc(TempMonth,3);
  270. Month := TempMonth;
  271. Year:=YYear+(JulianDN*100);
  272. end;
  273. Procedure EpochToLocal(epoch:longint;var year,month,day,hour,minute,second:Word);
  274. {
  275. Transforms Epoch time into local time (hour, minute,seconds)
  276. }
  277. Var
  278. DateNum: LongInt;
  279. Begin
  280. inc(Epoch,TZSeconds);
  281. Datenum:=(Epoch Div 86400) + c1970;
  282. JulianToGregorian(DateNum,Year,Month,day);
  283. Epoch:=Abs(Epoch Mod 86400);
  284. Hour:=Epoch Div 3600;
  285. Epoch:=Epoch Mod 3600;
  286. Minute:=Epoch Div 60;
  287. Second:=Epoch Mod 60;
  288. End;
  289. function GetTickCount64: QWord;
  290. var
  291. tp: TTimeVal;
  292. {$IFDEF HAVECLOCKGETTIME}
  293. ts: TTimeSpec;
  294. {$ENDIF}
  295. begin
  296. {$IFDEF HAVECLOCKGETTIME}
  297. if clock_gettime(CLOCK_MONOTONIC, @ts)=0 then
  298. begin
  299. Result := (Int64(ts.tv_sec) * 1000) + (ts.tv_nsec div 1000000);
  300. exit;
  301. end;
  302. {$ENDIF}
  303. fpgettimeofday(@tp, nil);
  304. Result := (Int64(tp.tv_sec) * 1000) + (tp.tv_usec div 1000);
  305. end;
  306. {****************************************************************************
  307. File Functions
  308. ****************************************************************************}
  309. Function DoFileLocking(Handle: Longint; Mode: Integer) : Longint;
  310. var
  311. lockop: cint;
  312. lockres: cint;
  313. closeres: cint;
  314. lockerr: cint;
  315. begin
  316. DoFileLocking:=Handle;
  317. {$ifdef beos}
  318. {$else}
  319. if (Handle>=0) then
  320. begin
  321. {$if defined(solaris) or defined(aix)}
  322. { Solaris' & AIX' flock is based on top of fcntl, which does not allow
  323. exclusive locks for files only opened for reading nor shared locks
  324. for files opened only for writing.
  325. If no locking is specified, we normally need an exclusive lock.
  326. So create an exclusive lock for fmOpenWrite and fmOpenReadWrite,
  327. but only a shared lock for fmOpenRead (since an exclusive lock
  328. is not possible in that case)
  329. }
  330. if ((mode and (fmShareCompat or fmShareExclusive or fmShareDenyWrite or fmShareDenyRead or fmShareDenyNone)) = 0) then
  331. begin
  332. if ((mode and (fmOpenRead or fmOpenWrite or fmOpenReadWrite)) = fmOpenRead) then
  333. mode := mode or fmShareDenyWrite
  334. else
  335. mode := mode or fmShareExclusive;
  336. end;
  337. {$endif solaris}
  338. case (mode and (fmShareCompat or fmShareExclusive or fmShareDenyWrite or fmShareDenyRead or fmShareDenyNone)) of
  339. fmShareCompat,
  340. fmShareExclusive:
  341. lockop:=LOCK_EX or LOCK_NB;
  342. fmShareDenyWrite:
  343. lockop:=LOCK_SH or LOCK_NB;
  344. fmShareDenyNone:
  345. exit;
  346. else
  347. begin
  348. { fmShareDenyRead does not exit under *nix, only shared access
  349. (similar to fmShareDenyWrite) and exclusive access (same as
  350. fmShareExclusive)
  351. }
  352. repeat
  353. closeres:=FpClose(Handle);
  354. until (closeres<>-1) or (fpgeterrno<>ESysEINTR);
  355. DoFileLocking:=-1;
  356. exit;
  357. end;
  358. end;
  359. repeat
  360. lockres:=fpflock(Handle,lockop);
  361. until (lockres=0) or
  362. (fpgeterrno<>ESysEIntr);
  363. lockerr:=fpgeterrno;
  364. { Only return an error if locks are working and the file was already
  365. locked. Not if locks are simply unsupported (e.g., on Angstrom Linux
  366. you always get ESysNOLCK in the default configuration) }
  367. if (lockres<>0) and
  368. ((lockerr=ESysEAGAIN) or
  369. (lockerr=EsysEDEADLK)) then
  370. begin
  371. repeat
  372. closeres:=FpClose(Handle);
  373. until (closeres<>-1) or (fpgeterrno<>ESysEINTR);
  374. DoFileLocking:=-1;
  375. exit;
  376. end;
  377. end;
  378. {$endif not beos}
  379. end;
  380. Function FileOpen (Const FileName : RawbyteString; Mode : Integer) : Longint;
  381. Var
  382. SystemFileName: RawByteString;
  383. LinuxFlags : longint;
  384. begin
  385. LinuxFlags:=0;
  386. case (Mode and (fmOpenRead or fmOpenWrite or fmOpenReadWrite)) of
  387. fmOpenRead : LinuxFlags:=LinuxFlags or O_RdOnly;
  388. fmOpenWrite : LinuxFlags:=LinuxFlags or O_WrOnly;
  389. fmOpenReadWrite : LinuxFlags:=LinuxFlags or O_RdWr;
  390. end;
  391. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  392. repeat
  393. FileOpen:=fpOpen (pointer(SystemFileName),LinuxFlags);
  394. until (FileOpen<>-1) or (fpgeterrno<>ESysEINTR);
  395. FileOpen:=DoFileLocking(FileOpen, Mode);
  396. end;
  397. Function FileCreate (Const FileName : RawByteString) : Longint;
  398. Var
  399. SystemFileName: RawByteString;
  400. begin
  401. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  402. repeat
  403. FileCreate:=fpOpen(pointer(SystemFileName),O_RdWr or O_Creat or O_Trunc);
  404. until (FileCreate<>-1) or (fpgeterrno<>ESysEINTR);
  405. end;
  406. Function FileCreate (Const FileName : RawByteString;Rights : Longint) : Longint;
  407. Var
  408. SystemFileName: RawByteString;
  409. begin
  410. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  411. repeat
  412. FileCreate:=fpOpen(pointer(SystemFileName),O_RdWr or O_Creat or O_Trunc,Rights);
  413. until (FileCreate<>-1) or (fpgeterrno<>ESysEINTR);
  414. end;
  415. Function FileCreate (Const FileName : RawByteString; ShareMode : Longint; Rights:LongInt ) : Longint;
  416. begin
  417. Result:=FileCreate( FileName, Rights );
  418. Result:=DoFileLocking(Result,ShareMode);
  419. end;
  420. Function FileRead (Handle : Longint; out Buffer; Count : longint) : Longint;
  421. begin
  422. repeat
  423. FileRead:=fpRead (Handle,Buffer,Count);
  424. until (FileRead<>-1) or (fpgeterrno<>ESysEINTR);
  425. end;
  426. Function FileWrite (Handle : Longint; const Buffer; Count : Longint) : Longint;
  427. begin
  428. repeat
  429. FileWrite:=fpWrite (Handle,Buffer,Count);
  430. until (FileWrite<>-1) or (fpgeterrno<>ESysEINTR);
  431. end;
  432. Function FileSeek (Handle,FOffset,Origin : Longint) : Longint;
  433. begin
  434. result:=longint(FileSeek(Handle,int64(FOffset),Origin));
  435. end;
  436. Function FileSeek (Handle : Longint; FOffset : Int64; Origin : Longint) : Int64;
  437. begin
  438. FileSeek:=fplSeek (Handle,FOffset,Origin);
  439. end;
  440. Procedure FileClose (Handle : Longint);
  441. var
  442. res: cint;
  443. begin
  444. repeat
  445. res:=fpclose(Handle);
  446. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  447. end;
  448. Function FileTruncate (Handle: THandle; Size: Int64) : boolean;
  449. var
  450. res: cint;
  451. begin
  452. if (SizeOf (TOff) < 8) (* fpFTruncate only supporting signed 32-bit size *)
  453. and (Size > high (longint)) then
  454. FileTruncate := false
  455. else
  456. begin
  457. repeat
  458. res:=fpftruncate(Handle,Size);
  459. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  460. FileTruncate:=res>=0;
  461. end;
  462. end;
  463. Function FileAge (Const FileName : RawByteString): Longint;
  464. Var
  465. Info : Stat;
  466. SystemFileName: RawByteString;
  467. begin
  468. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  469. If (fpstat(pchar(SystemFileName),Info)<0) or fpS_ISDIR(info.st_mode) then
  470. exit(-1)
  471. else
  472. Result:=info.st_mtime;
  473. end;
  474. Function FileExists (Const FileName : RawByteString) : Boolean;
  475. var
  476. SystemFileName: RawByteString;
  477. begin
  478. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  479. // Don't use stat. It fails on files >2 GB.
  480. // Access obeys the same access rules, so the result should be the same.
  481. FileExists:=fpAccess(pointer(SystemFileName),F_OK)=0;
  482. end;
  483. Function DirectoryExists (Const Directory : RawByteString) : Boolean;
  484. Var
  485. Info : Stat;
  486. SystemFileName: RawByteString;
  487. begin
  488. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Directory);
  489. DirectoryExists:=(fpstat(pointer(SystemFileName),Info)>=0) and fpS_ISDIR(Info.st_mode);
  490. end;
  491. Function LinuxToWinAttr (const FN : RawByteString; Const Info : Stat) : Longint;
  492. Var
  493. LinkInfo : Stat;
  494. nm : RawByteString;
  495. begin
  496. Result:=faArchive;
  497. If fpS_ISDIR(Info.st_mode) then
  498. Result:=Result or faDirectory;
  499. nm:=ExtractFileName(FN);
  500. If (Length(nm)>=2) and
  501. (nm[1]='.') and
  502. (nm[2]<>'.') then
  503. Result:=Result or faHidden;
  504. If (Info.st_Mode and S_IWUSR)=0 Then
  505. Result:=Result or faReadOnly;
  506. If fpS_ISSOCK(Info.st_mode) or fpS_ISBLK(Info.st_mode) or fpS_ISCHR(Info.st_mode) or fpS_ISFIFO(Info.st_mode) Then
  507. Result:=Result or faSysFile;
  508. If fpS_ISLNK(Info.st_mode) Then
  509. begin
  510. Result:=Result or faSymLink;
  511. // Windows reports if the link points to a directory.
  512. if (fpstat(pchar(FN),LinkInfo)>=0) and fpS_ISDIR(LinkInfo.st_mode) then
  513. Result := Result or faDirectory;
  514. end;
  515. end;
  516. { assumes that pattern and name have the same code page }
  517. Function FNMatch(const Pattern,Name:string):Boolean;
  518. Var
  519. LenPat,LenName : longint;
  520. function NameUtf8CodePointLen(index: longint): longint;
  521. var
  522. MaxLookAhead: longint;
  523. begin
  524. MaxLookAhead:=LenName-Index+1;
  525. { abs so that in case of an invalid sequence, we count this as one
  526. codepoint }
  527. NameUtf8CodePointLen:=abs(Utf8CodePointLen(pansichar(@Name[index]),MaxLookAhead,true));
  528. { if the sequence was incomplete, use the incomplete sequence as
  529. codepoint }
  530. if NameUtf8CodePointLen=0 then
  531. NameUtf8CodePointLen:=MaxLookAhead;
  532. end;
  533. procedure GoToLastByteOfUtf8CodePoint(var j: longint);
  534. begin
  535. inc(j,NameUtf8CodePointLen(j)-1);
  536. end;
  537. { input:
  538. i: current position in pattern (start of utf-8 code point)
  539. j: current position in name (start of utf-8 code point)
  540. update_i_j: should i and j be changed by the routine or not
  541. output:
  542. i: if update_i_j, then position of last matching part of code point in
  543. pattern, or first non-matching code point in pattern. Otherwise the
  544. same value as on input.
  545. j: if update_i_j, then position of last matching part of code point in
  546. name, or first non-matching code point in name. Otherwise the
  547. same value as on input.
  548. result: true if match, false if no match
  549. }
  550. function CompareUtf8CodePoint(var i,j: longint; update_i_j: boolean): Boolean;
  551. var
  552. bytes,
  553. new_i,
  554. new_j: longint;
  555. begin
  556. bytes:=NameUtf8CodePointLen(j);
  557. new_i:=i;
  558. new_j:=j;
  559. { ensure that a part of an UTF-8 codepoint isn't interpreted
  560. as '*' or '?' }
  561. repeat
  562. dec(bytes);
  563. Result:=
  564. (new_j<=LenName) and
  565. (new_i<=LenPat) and
  566. (Pattern[new_i]=Name[new_j]);
  567. inc(new_i);
  568. inc(new_j);
  569. until not(Result) or
  570. (bytes=0);
  571. if update_i_j then
  572. begin
  573. i:=new_i;
  574. j:=new_j;
  575. end;
  576. end;
  577. Function DoFNMatch(i,j:longint):Boolean;
  578. Var
  579. UTF8, Found : boolean;
  580. Begin
  581. Found:=true;
  582. { ensure that we don't skip partial characters in UTF-8-encoded strings }
  583. UTF8:=StringCodePage(Name)=CP_UTF8;
  584. While Found and (i<=LenPat) Do
  585. Begin
  586. Case Pattern[i] of
  587. '?' :
  588. begin
  589. Found:=(j<=LenName);
  590. if UTF8 then
  591. GoToLastByteOfUtf8CodePoint(j);
  592. end;
  593. '*' : Begin
  594. {find the next character in pattern, different of ? and *}
  595. while Found do
  596. begin
  597. inc(i);
  598. if i>LenPat then
  599. Break;
  600. case Pattern[i] of
  601. '*' : ;
  602. '?' : begin
  603. if j>LenName then
  604. begin
  605. DoFNMatch:=false;
  606. Exit;
  607. end;
  608. if UTF8 then
  609. GoToLastByteOfUtf8CodePoint(j);
  610. inc(j);
  611. end;
  612. else
  613. Found:=false;
  614. end;
  615. end;
  616. Assert((i>LenPat) or ( (Pattern[i]<>'*') and (Pattern[i]<>'?') ));
  617. { Now, find in name the character which i points to, if the * or
  618. ? wasn't the last character in the pattern, else, use up all
  619. the chars in name }
  620. Found:=false;
  621. if (i<=LenPat) then
  622. begin
  623. repeat
  624. {find a letter (not only first !) which maches pattern[i]}
  625. if UTF8 then
  626. begin
  627. while (j<=LenName) and
  628. ((name[j]<>pattern[i]) or
  629. not CompareUtf8CodePoint(i,j,false)) do
  630. begin
  631. GoToLastByteOfUtf8CodePoint(j);
  632. inc(j);
  633. end;
  634. end
  635. else
  636. begin
  637. while (j<=LenName) and (name[j]<>pattern[i]) do
  638. inc (j);
  639. end;
  640. if (j<LenName) then
  641. begin
  642. { while positions i/j have already been checked, in
  643. case of UTF-8 we have to ensure that we don't split
  644. a code point. Otherwise we can skip over comparing
  645. the same characters twice }
  646. if DoFnMatch(i+ord(not UTF8),j+ord(not UTF8)) then
  647. begin
  648. i:=LenPat;
  649. j:=LenName;{we can stop}
  650. Found:=true;
  651. Break;
  652. end
  653. { We didn't find one, need to look further }
  654. else
  655. begin
  656. if UTF8 then
  657. GoToLastByteOfUtf8CodePoint(j);
  658. inc(j);
  659. end;
  660. end
  661. else if j=LenName then
  662. begin
  663. Found:=true;
  664. Break;
  665. end;
  666. { This 'until' condition must be j>LenName, not j>=LenName.
  667. That's because when we 'need to look further' and
  668. j = LenName then loop must not terminate. }
  669. until (j>LenName);
  670. end
  671. else
  672. begin
  673. j:=LenName;{we can stop}
  674. Found:=true;
  675. end;
  676. end;
  677. #128..#255:
  678. begin
  679. Found:=(j<=LenName) and (pattern[i]=name[j]);
  680. if Found and UTF8 then
  681. begin
  682. { ensure that a part of an UTF-8 codepoint isn't matched with
  683. '*' or '?' }
  684. Found:=CompareUtf8CodePoint(i,j,true);
  685. { at this point, either Found is false (and we'll stop), or
  686. both pattern[i] and name[j] are the end of the current code
  687. point and equal }
  688. end
  689. end
  690. else {not a wildcard character in pattern}
  691. Found:=(j<=LenName) and (pattern[i]=name[j]);
  692. end;
  693. inc(i);
  694. inc(j);
  695. end;
  696. DoFnMatch:=Found and (j>LenName);
  697. end;
  698. Begin {start FNMatch}
  699. LenPat:=Length(Pattern);
  700. LenName:=Length(Name);
  701. FNMatch:=DoFNMatch(1,1);
  702. End;
  703. Type
  704. TUnixFindData = Record
  705. NamePos : LongInt; {to track which search this is}
  706. DirPtr : Pointer; {directory pointer for reading directory}
  707. SearchSpec : RawbyteString;
  708. SearchType : Byte; {0=normal, 1=open will close, 2=only 1 file}
  709. SearchAttr : Byte; {attribute we are searching for}
  710. End;
  711. PUnixFindData = ^TUnixFindData;
  712. Procedure InternalFindClose(var Handle: Pointer);
  713. var
  714. D: PUnixFindData absolute Handle;
  715. begin
  716. If D=Nil then
  717. Exit;
  718. if D^.SearchType=0 then
  719. begin
  720. if D^.dirptr<>nil then
  721. fpclosedir(pdir(D^.dirptr)^);
  722. end;
  723. Dispose(D);
  724. D:=nil;
  725. end;
  726. Function FindGetFileInfo(const s: RawByteString; var f: TAbstractSearchRec; var Name: RawByteString):boolean;
  727. Var
  728. st : baseunix.stat;
  729. WinAttr : longint;
  730. begin
  731. if Assigned(f.FindHandle) and ( (PUnixFindData(F.FindHandle)^.searchattr and faSymlink) > 0) then
  732. FindGetFileInfo:=(fplstat(pointer(s),st)=0)
  733. else
  734. FindGetFileInfo:=(fpstat(pointer(s),st)=0);
  735. if not FindGetFileInfo then
  736. exit;
  737. WinAttr:=LinuxToWinAttr(s,st);
  738. FindGetFileInfo:=(WinAttr and Not(PUnixFindData(f.FindHandle)^.searchattr))=0;
  739. if FindGetFileInfo then
  740. begin
  741. Name:=ExtractFileName(s);
  742. f.Attr:=WinAttr;
  743. f.Size:=st.st_Size;
  744. f.Mode:=st.st_mode;
  745. f.Time:=st.st_mtime;
  746. FindGetFileInfo:=true;
  747. end;
  748. end;
  749. // Returns the FOUND filename. Error code <> 0 if no file found
  750. Function InternalFindNext (var Rslt : TAbstractSearchRec; var Name : RawByteString) : Longint;
  751. Var
  752. DirName : RawByteString;
  753. FName,
  754. SName : RawBytestring;
  755. Found,
  756. Finished : boolean;
  757. p : pdirent;
  758. UnixFindData : PUnixFindData;
  759. Begin
  760. Result:=-1;
  761. UnixFindData:=PUnixFindData(Rslt.FindHandle);
  762. { SearchSpec='' means that there were no wild cards, so only one file to
  763. find.
  764. }
  765. If (UnixFindData=Nil) or (UnixFindData^.SearchSpec='') then
  766. exit;
  767. if (UnixFindData^.SearchType=0) and
  768. (UnixFindData^.Dirptr=nil) then
  769. begin
  770. If UnixFindData^.NamePos = 0 Then
  771. DirName:='./'
  772. Else
  773. DirName:=Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos);
  774. UnixFindData^.DirPtr := fpopendir(Pchar(DirName));
  775. end;
  776. SName:=Copy(UnixFindData^.SearchSpec,UnixFindData^.NamePos+1,Length(UnixFindData^.SearchSpec));
  777. Found:=False;
  778. Finished:=(UnixFindData^.dirptr=nil);
  779. While Not Finished Do
  780. Begin
  781. p:=fpreaddir(pdir(UnixFindData^.dirptr)^);
  782. if p=nil then
  783. FName:=''
  784. else
  785. FName:=p^.d_name;
  786. If FName='' Then
  787. Finished:=True
  788. Else
  789. Begin
  790. SetCodePage(FName,DefaultFileSystemCodePage,false);
  791. If FNMatch(SName,FName) Then
  792. Begin
  793. Found:=FindGetFileInfo(Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos)+FName,Rslt,Name);
  794. if Found then
  795. begin
  796. Result:=0;
  797. exit;
  798. end;
  799. End;
  800. End;
  801. End;
  802. End;
  803. Function InternalFindFirst (Const Path : RawByteString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name: RawByteString) : Longint;
  804. {
  805. opens dir and calls FindNext if needed.
  806. }
  807. var
  808. UnixFindData : PUnixFindData;
  809. Begin
  810. Result:=-1;
  811. { this is safe even though Rslt actually contains a refcounted field, because
  812. it is declared as "out" and hence has already been initialised }
  813. fillchar(Rslt,sizeof(Rslt),0);
  814. if Path='' then
  815. exit;
  816. { Allocate UnixFindData (we always need it, for the search attributes) }
  817. New(UnixFindData);
  818. FillChar(UnixFindData^,sizeof(UnixFindData^),0);
  819. Rslt.FindHandle:=UnixFindData;
  820. {We always also search for readonly and archive, regardless of Attr:}
  821. UnixFindData^.SearchAttr := Attr or faarchive or fareadonly;
  822. {Wildcards?}
  823. if (Pos('?',Path)=0) and (Pos('*',Path)=0) then
  824. begin
  825. if FindGetFileInfo(ToSingleByteFileSystemEncodedFileName(Path),Rslt,Name) then
  826. Result:=0;
  827. end
  828. else
  829. begin
  830. {Create Info}
  831. UnixFindData^.SearchSpec := ToSingleByteFileSystemEncodedFileName(Path);
  832. UnixFindData^.NamePos := Length(UnixFindData^.SearchSpec);
  833. while (UnixFindData^.NamePos>0) and (UnixFindData^.SearchSpec[UnixFindData^.NamePos]<>'/') do
  834. dec(UnixFindData^.NamePos);
  835. Result:=InternalFindNext(Rslt,Name);
  836. end;
  837. If (Result<>0) then
  838. InternalFindClose(Rslt.FindHandle);
  839. End;
  840. Function FileGetDate (Handle : Longint) : Longint;
  841. Var Info : Stat;
  842. begin
  843. If (fpFStat(Handle,Info))<0 then
  844. Result:=-1
  845. else
  846. Result:=Info.st_Mtime;
  847. end;
  848. Function FileSetDate (Handle,Age : Longint) : Longint;
  849. begin
  850. // Impossible under Linux from FileHandle !!
  851. FileSetDate:=-1;
  852. end;
  853. Function FileGetAttr (Const FileName : RawByteString) : Longint;
  854. Var
  855. SystemFileName: RawByteString;
  856. Info : Stat;
  857. res : Integer;
  858. begin
  859. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  860. res:=FpLStat(pointer(SystemFileName),Info);
  861. if res<0 then
  862. res:=FpStat(pointer(SystemFileName),Info);
  863. if res<0 then
  864. Result:=-1
  865. Else
  866. Result:=LinuxToWinAttr(SystemFileName,Info);
  867. end;
  868. Function FileSetAttr (Const Filename : RawByteString; Attr: longint) : Longint;
  869. begin
  870. Result:=-1;
  871. end;
  872. Function DeleteFile (Const FileName : RawByteString) : Boolean;
  873. var
  874. SystemFileName: RawByteString;
  875. begin
  876. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  877. Result:=fpUnLink (pchar(SystemFileName))>=0;
  878. end;
  879. Function RenameFile (Const OldName, NewName : RawByteString) : Boolean;
  880. var
  881. SystemOldName, SystemNewName: RawByteString;
  882. begin
  883. SystemOldName:=ToSingleByteFileSystemEncodedFileName(OldName);
  884. SystemNewName:=ToSingleByteFileSystemEncodedFileName(NewName);
  885. RenameFile:=BaseUnix.FpRename(pointer(SystemOldName),pointer(SystemNewName))>=0;
  886. end;
  887. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  888. var
  889. SystemFileName: RawByteString;
  890. begin
  891. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  892. Result:=fpAccess(PChar(SystemFileName),W_OK)<>0;
  893. end;
  894. Function FileSetDate (Const FileName : RawByteString; Age : Longint) : Longint;
  895. var
  896. SystemFileName: RawByteString;
  897. t: TUTimBuf;
  898. begin
  899. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  900. Result:=0;
  901. t.actime:= Age;
  902. t.modtime:=Age;
  903. if fputime(PChar(SystemFileName), @t) = -1 then
  904. Result:=fpgeterrno;
  905. end;
  906. {****************************************************************************
  907. Disk Functions
  908. ****************************************************************************}
  909. {
  910. The Diskfree and Disksize functions need a file on the specified drive, since this
  911. is required for the fpstatfs system call.
  912. These filenames are set in drivestr[0..26], and have been preset to :
  913. 0 - '.' (default drive - hence current dir is ok.)
  914. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  915. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  916. 3 - '/' (C: equivalent of dos is the root partition)
  917. 4..26 (can be set by you're own applications)
  918. ! Use AddDisk() to Add new drives !
  919. They both return -1 when a failure occurs.
  920. }
  921. Const
  922. FixDriveStr : array[0..3] of pchar=(
  923. '.',
  924. '/fd0/.',
  925. '/fd1/.',
  926. '/.'
  927. );
  928. var
  929. Drives : byte = 4;
  930. DriveStr : array[4..26] of pchar;
  931. Function AddDisk(const path:string) : Byte;
  932. begin
  933. if not (DriveStr[Drives]=nil) then
  934. FreeMem(DriveStr[Drives]);
  935. GetMem(DriveStr[Drives],length(Path)+1);
  936. StrPCopy(DriveStr[Drives],path);
  937. Result:=Drives;
  938. inc(Drives);
  939. if Drives>26 then
  940. Drives:=4;
  941. end;
  942. Function DiskFree(Drive: Byte): int64;
  943. var
  944. fs : tstatfs;
  945. Begin
  946. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (fpstatfs(StrPas(fixdrivestr[drive]),@fs)<>-1)) or
  947. ((Drive <= High(drivestr)) and (not (drivestr[Drive]=nil)) and (fpstatfs(StrPas(drivestr[drive]),@fs)<>-1)) then
  948. Diskfree:=int64(fs.bavail)*int64(fs.bsize)
  949. else
  950. Diskfree:=-1;
  951. End;
  952. Function DiskSize(Drive: Byte): int64;
  953. var
  954. fs : tstatfs;
  955. Begin
  956. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (fpstatfs(StrPas(fixdrivestr[drive]),@fs)<>-1)) or
  957. ((drive <= High(drivestr)) and (not (drivestr[Drive]=nil)) and (fpstatfs(StrPas(drivestr[drive]),@fs)<>-1)) then
  958. DiskSize:=int64(fs.blocks)*int64(fs.bsize)
  959. else
  960. DiskSize:=-1;
  961. End;
  962. Procedure FreeDriveStr;
  963. var
  964. i: longint;
  965. begin
  966. for i:=low(drivestr) to high(drivestr) do
  967. if assigned(drivestr[i]) then
  968. begin
  969. freemem(drivestr[i]);
  970. drivestr[i]:=nil;
  971. end;
  972. end;
  973. {****************************************************************************
  974. Misc Functions
  975. ****************************************************************************}
  976. {****************************************************************************
  977. Locale Functions
  978. ****************************************************************************}
  979. Function GetEpochTime: cint;
  980. {
  981. Get the number of seconds since 00:00, January 1 1970, GMT
  982. the time NOT corrected any way
  983. }
  984. begin
  985. GetEpochTime:=fptime;
  986. end;
  987. // Now, adjusted to local time.
  988. Procedure DoGetLocalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  989. var
  990. tz:timeval;
  991. begin
  992. fpgettimeofday(@tz,nil);
  993. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  994. msec:=tz.tv_usec div 1000;
  995. usec:=tz.tv_usec mod 1000;
  996. end;
  997. procedure GetTime(var hour,min,sec,msec,usec:word);
  998. Var
  999. year,day,month:Word;
  1000. begin
  1001. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1002. end;
  1003. procedure GetTime(var hour,min,sec,sec100:word);
  1004. {
  1005. Gets the current time, adjusted to local time
  1006. }
  1007. var
  1008. year,day,month,usec : word;
  1009. begin
  1010. DoGetLocalDateTime(year,month,day,hour,min,sec,sec100,usec);
  1011. sec100:=sec100 div 10;
  1012. end;
  1013. Procedure GetTime(Var Hour,Min,Sec:Word);
  1014. {
  1015. Gets the current time, adjusted to local time
  1016. }
  1017. var
  1018. year,day,month,msec,usec : Word;
  1019. Begin
  1020. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1021. End;
  1022. Procedure GetDate(Var Year,Month,Day:Word);
  1023. {
  1024. Gets the current date, adjusted to local time
  1025. }
  1026. var
  1027. hour,minute,second,msec,usec : word;
  1028. Begin
  1029. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1030. End;
  1031. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  1032. {
  1033. Gets the current date, adjusted to local time
  1034. }
  1035. Var
  1036. usec,msec : word;
  1037. Begin
  1038. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1039. End;
  1040. {$ifndef FPUNONE}
  1041. Procedure GetLocalTime(var SystemTime: TSystemTime);
  1042. var
  1043. usecs : Word;
  1044. begin
  1045. DoGetLocalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1046. end ;
  1047. {$endif}
  1048. Procedure InitAnsi;
  1049. Var
  1050. i : longint;
  1051. begin
  1052. { Fill table entries 0 to 127 }
  1053. for i := 0 to 96 do
  1054. UpperCaseTable[i] := chr(i);
  1055. for i := 97 to 122 do
  1056. UpperCaseTable[i] := chr(i - 32);
  1057. for i := 123 to 191 do
  1058. UpperCaseTable[i] := chr(i);
  1059. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  1060. for i := 0 to 64 do
  1061. LowerCaseTable[i] := chr(i);
  1062. for i := 65 to 90 do
  1063. LowerCaseTable[i] := chr(i + 32);
  1064. for i := 91 to 191 do
  1065. LowerCaseTable[i] := chr(i);
  1066. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  1067. end;
  1068. Procedure InitInternational;
  1069. begin
  1070. InitInternationalGeneric;
  1071. InitAnsi;
  1072. end;
  1073. function SysErrorMessage(ErrorCode: Integer): String;
  1074. begin
  1075. Result:=StrError(ErrorCode);
  1076. end;
  1077. {****************************************************************************
  1078. OS utility functions
  1079. ****************************************************************************}
  1080. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1081. begin
  1082. { no need to adjust the code page of EnvVar to DefaultSystemCodePage, as only
  1083. ASCII identifiers are supported }
  1084. Result:=BaseUnix.FPGetenv(PChar(pointer(EnvVar)));
  1085. end;
  1086. Function GetEnvironmentVariableCount : Integer;
  1087. begin
  1088. Result:=FPCCountEnvVar(EnvP);
  1089. end;
  1090. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1091. begin
  1092. Result:=FPCGetEnvStrFromP(Envp,Index);
  1093. end;
  1094. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString;Flags:TExecuteFlags=[]):integer;
  1095. var
  1096. pid : longint;
  1097. e : EOSError;
  1098. CommandLine: AnsiString;
  1099. cmdline2 : ppchar;
  1100. Begin
  1101. { always surround the name of the application by quotes
  1102. so that long filenames will always be accepted. But don't
  1103. do it if there are already double quotes!
  1104. }
  1105. // Only place we still parse
  1106. cmdline2:=nil;
  1107. if Comline<>'' Then
  1108. begin
  1109. CommandLine:=ComLine;
  1110. { Make an unique copy because stringtoppchar modifies the
  1111. string }
  1112. UniqueString(CommandLine);
  1113. cmdline2:=StringtoPPChar(CommandLine,1);
  1114. cmdline2^:=pchar(pointer(Path));
  1115. end
  1116. else
  1117. begin
  1118. getmem(cmdline2,2*sizeof(pchar));
  1119. cmdline2^:=pchar(Path);
  1120. cmdline2[1]:=nil;
  1121. end;
  1122. {$ifdef USE_VFORK}
  1123. pid:=fpvFork;
  1124. {$else USE_VFORK}
  1125. pid:=fpFork;
  1126. {$endif USE_VFORK}
  1127. if pid=0 then
  1128. begin
  1129. {The child does the actual exec, and then exits}
  1130. fpexecv(pchar(pointer(Path)),Cmdline2);
  1131. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1132. fpExit(127);
  1133. end
  1134. else
  1135. if pid=-1 then {Fork failed}
  1136. begin
  1137. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1138. e.ErrorCode:=-1;
  1139. raise e;
  1140. end;
  1141. { We're in the parent, let's wait. }
  1142. result:=WaitProcess(pid); // WaitPid and result-convert
  1143. if Comline<>'' Then
  1144. freemem(cmdline2);
  1145. if (result<0) or (result=127) then
  1146. begin
  1147. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1148. E.ErrorCode:=result;
  1149. Raise E;
  1150. end;
  1151. End;
  1152. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array Of AnsiString;Flags:TExecuteFlags=[]):integer;
  1153. var
  1154. pid : longint;
  1155. e : EOSError;
  1156. Begin
  1157. pid:=fpFork;
  1158. if pid=0 then
  1159. begin
  1160. {The child does the actual exec, and then exits}
  1161. fpexecl(Path,Comline);
  1162. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1163. fpExit(127);
  1164. end
  1165. else
  1166. if pid=-1 then {Fork failed}
  1167. begin
  1168. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1169. e.ErrorCode:=-1;
  1170. raise e;
  1171. end;
  1172. { We're in the parent, let's wait. }
  1173. result:=WaitProcess(pid); // WaitPid and result-convert
  1174. if (result<0) or (result=127) then
  1175. begin
  1176. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1177. E.ErrorCode:=result;
  1178. raise E;
  1179. end;
  1180. End;
  1181. procedure Sleep(milliseconds: Cardinal);
  1182. Var
  1183. timeout,timeoutresult : TTimespec;
  1184. res: cint;
  1185. begin
  1186. timeout.tv_sec:=milliseconds div 1000;
  1187. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  1188. repeat
  1189. res:=fpnanosleep(@timeout,@timeoutresult);
  1190. timeout:=timeoutresult;
  1191. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  1192. end;
  1193. Function GetLastOSError : Integer;
  1194. begin
  1195. Result:=fpgetErrNo;
  1196. end;
  1197. { ---------------------------------------------------------------------
  1198. Application config files
  1199. ---------------------------------------------------------------------}
  1200. Function GetHomeDir : String;
  1201. begin
  1202. Result:=GetEnvironmentVariable('HOME');
  1203. If (Result<>'') then
  1204. Result:=IncludeTrailingPathDelimiter(Result);
  1205. end;
  1206. { Follows base-dir spec,
  1207. see [http://freedesktop.org/Standards/basedir-spec].
  1208. Always ends with PathDelim. }
  1209. Function XdgConfigHome : String;
  1210. begin
  1211. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  1212. if (Result='') then
  1213. Result:=GetHomeDir + '.config/'
  1214. else
  1215. Result:=IncludeTrailingPathDelimiter(Result);
  1216. end;
  1217. Function GetAppConfigDir(Global : Boolean) : String;
  1218. begin
  1219. If Global then
  1220. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1221. else
  1222. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1223. if VendorName<>'' then
  1224. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1225. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1226. end;
  1227. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1228. begin
  1229. If Global then
  1230. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1231. else
  1232. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1233. if SubDir then
  1234. begin
  1235. if VendorName<>'' then
  1236. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1237. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1238. end;
  1239. Result:=Result+ApplicationName+ConfigExtension;
  1240. end;
  1241. {****************************************************************************
  1242. GetTempDir
  1243. ****************************************************************************}
  1244. Function GetTempDir(Global : Boolean) : String;
  1245. begin
  1246. If Assigned(OnGetTempDir) then
  1247. Result:=OnGetTempDir(Global)
  1248. else
  1249. begin
  1250. Result:=GetEnvironmentVariable('TEMP');
  1251. If (Result='') Then
  1252. Result:=GetEnvironmentVariable('TMP');
  1253. If (Result='') Then
  1254. Result:=GetEnvironmentVariable('TMPDIR');
  1255. if (Result='') then
  1256. Result:='/tmp/' // fallback.
  1257. end;
  1258. if (Result<>'') then
  1259. Result:=IncludeTrailingPathDelimiter(Result);
  1260. end;
  1261. {****************************************************************************
  1262. GetUserDir
  1263. ****************************************************************************}
  1264. Var
  1265. TheUserDir : String;
  1266. Function GetUserDir : String;
  1267. begin
  1268. If (TheUserDir='') then
  1269. begin
  1270. TheUserDir:=GetEnvironmentVariable('HOME');
  1271. if (TheUserDir<>'') then
  1272. TheUserDir:=IncludeTrailingPathDelimiter(TheUserDir)
  1273. else
  1274. TheUserDir:=GetTempDir(False);
  1275. end;
  1276. Result:=TheUserDir;
  1277. end;
  1278. Procedure SysBeep;
  1279. begin
  1280. Write(#7);
  1281. Flush(Output);
  1282. end;
  1283. function GetLocalTimeOffset: Integer;
  1284. begin
  1285. Result := -Tzseconds div 60;
  1286. end;
  1287. {****************************************************************************
  1288. Initialization code
  1289. ****************************************************************************}
  1290. Initialization
  1291. InitExceptions; { Initialize exceptions. OS independent }
  1292. InitInternational; { Initialize internationalization settings }
  1293. SysConfigDir:='/etc'; { Initialize system config dir }
  1294. OnBeep:=@SysBeep;
  1295. Finalization
  1296. FreeDriveStr;
  1297. DoneExceptions;
  1298. end.