sysutils.pp 42 KB

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