sysutils.pp 52 KB

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