sysutils.pp 45 KB

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