sysutils.pp 44 KB

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