sysutils.pp 53 KB

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