sysutils.pp 52 KB

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