sysutils.pp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938
  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. FileOpen:=DoFileLocking(FileOpen, Mode);
  412. end;
  413. function FileFlush(Handle: THandle): Boolean;
  414. begin
  415. Result:= fpfsync(handle)=0;
  416. end;
  417. Function FileCreate (Const FileName : RawByteString) : Longint;
  418. Var
  419. SystemFileName: RawByteString;
  420. begin
  421. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  422. repeat
  423. FileCreate:=fpOpen(pointer(SystemFileName),O_RdWr or O_Creat or O_Trunc);
  424. until (FileCreate<>-1) or (fpgeterrno<>ESysEINTR);
  425. end;
  426. Function FileCreate (Const FileName : RawByteString;Rights : Longint) : Longint;
  427. Var
  428. SystemFileName: RawByteString;
  429. begin
  430. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  431. repeat
  432. FileCreate:=fpOpen(pointer(SystemFileName),O_RdWr or O_Creat or O_Trunc,Rights);
  433. until (FileCreate<>-1) or (fpgeterrno<>ESysEINTR);
  434. end;
  435. Function FileCreate (Const FileName : RawByteString; ShareMode : Longint; Rights:LongInt ) : Longint;
  436. Var
  437. fd: Longint;
  438. begin
  439. { if the file already exists and we can't open it using the requested
  440. ShareMode (e.g. exclusive sharing), exit immediately so that we don't
  441. first empty the file and then check whether we can lock this new file
  442. (which we can by definition) }
  443. fd:=FileOpenNoLocking(FileName,ShareMode);
  444. { the file exists, check whether our locking request is compatible }
  445. if fd>=0 then
  446. begin
  447. Result:=DoFileLocking(fd,ShareMode);
  448. FileClose(fd);
  449. { Can't lock -> abort }
  450. if Result<0 then
  451. exit;
  452. end;
  453. { now create the file }
  454. Result:=FileCreate(FileName,Rights);
  455. Result:=DoFileLocking(Result,ShareMode);
  456. end;
  457. Function FileRead (Handle : Longint; out Buffer; Count : longint) : Longint;
  458. begin
  459. repeat
  460. FileRead:=fpRead (Handle,Buffer,Count);
  461. until (FileRead<>-1) or (fpgeterrno<>ESysEINTR);
  462. end;
  463. Function FileWrite (Handle : Longint; const Buffer; Count : Longint) : Longint;
  464. begin
  465. repeat
  466. FileWrite:=fpWrite (Handle,Buffer,Count);
  467. until (FileWrite<>-1) or (fpgeterrno<>ESysEINTR);
  468. end;
  469. Function FileSeek (Handle,FOffset,Origin : Longint) : Longint;
  470. Var
  471. I : Int64;
  472. begin
  473. I:=FileSeek(Handle,int64(FOffset),Origin);
  474. if I>High(Longint) then
  475. Raise EInOutError.CreateFmt(SErrPosToBigForLongint,[I]);
  476. result:=I;
  477. end;
  478. Function FileSeek (Handle : Longint; FOffset : Int64; Origin : Longint) : Int64;
  479. begin
  480. FileSeek:=fplSeek (Handle,FOffset,Origin);
  481. end;
  482. Procedure FileClose (Handle : Longint);
  483. var
  484. res: cint;
  485. begin
  486. repeat
  487. res:=fpclose(Handle);
  488. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  489. end;
  490. Function FileTruncate (Handle: THandle; Size: Int64) : boolean;
  491. var
  492. res: cint;
  493. begin
  494. if (SizeOf (TOff) < 8) (* fpFTruncate only supporting signed 32-bit size *)
  495. and (Size > high (longint)) then
  496. FileTruncate := false
  497. else
  498. begin
  499. repeat
  500. res:=fpftruncate(Handle,Size);
  501. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  502. FileTruncate:=res>=0;
  503. end;
  504. end;
  505. Function FileAge (Const FileName : RawByteString): Int64;
  506. Var
  507. Info : Stat;
  508. SystemFileName: RawByteString;
  509. {$ifdef USE_STATX}
  510. Infox : TStatx;
  511. {$endif USE_STATX}
  512. begin
  513. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  514. {$ifdef USE_STATX}
  515. { first try statx }
  516. if {$ifdef FPC_USE_LIBC} (@statx<>nil) and {$endif}
  517. (statx(AT_FDCWD,PAnsiChar(SystemFileName),0,STATX_MTIME or STATX_MODE,Infox)>=0) and not(fpS_ISDIR(Infox.stx_mode)) then
  518. begin
  519. Result:=Infox.stx_mtime.tv_sec;
  520. exit;
  521. end;
  522. {$endif USE_STATX}
  523. If (fpstat(PAnsiChar(SystemFileName),Info)<0) or fpS_ISDIR(info.st_mode) then
  524. exit(-1)
  525. else
  526. Result:=info.st_mtime;
  527. end;
  528. function FileGetDateTimeInfo(const FileName: string; out DateTime: TDateTimeInfoRec; FollowLink: Boolean = True): Boolean;
  529. var
  530. FN : AnsiString;
  531. st: tstat;
  532. {$IFDEF USE_STATX}
  533. stx : tstatx;
  534. flags : Integer;
  535. const
  536. STATXMASK = STATX_MTIME or STATX_ATIME or STATX_CTIME;
  537. {$ENDIF}
  538. begin
  539. FN:=FileName;
  540. {$ifdef USE_STATX}
  541. flags:=0;
  542. if Not FollowLink then
  543. Flags:=AT_SYMLINK_NOFOLLOW;
  544. if {$ifdef FPC_USE_LIBC} (@statx<>nil) and {$endif}
  545. (statx(AT_FDCWD,PAnsiChar(FN),FLags,STATXMASK, stx)>=0) then
  546. begin
  547. DateTime.Data:=stx;
  548. Exit(True);
  549. end;
  550. {$else}
  551. if (FollowLink and (fpstat(FN,st) = 0)) or
  552. (not FollowLink and (fplstat(fn, st) = 0)) then
  553. begin
  554. DateTime.Data:=st;
  555. Result := True;
  556. end;
  557. {$endif}
  558. end;
  559. Function LinuxToWinAttr (const FN : RawByteString; Const Info : Stat) : Longint;
  560. Var
  561. LinkInfo : Stat;
  562. nm : RawByteString;
  563. begin
  564. Result:=faArchive;
  565. If fpS_ISDIR(Info.st_mode) then
  566. Result:=Result or faDirectory;
  567. nm:=ExtractFileName(FN);
  568. If (Length(nm)>=2) and
  569. (nm[1]='.') and
  570. (nm[2]<>'.') then
  571. Result:=Result or faHidden;
  572. If (Info.st_Mode and S_IWUSR)=0 Then
  573. Result:=Result or faReadOnly;
  574. 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
  575. Result:=Result or faSysFile;
  576. If fpS_ISLNK(Info.st_mode) Then
  577. begin
  578. Result:=Result or faSymLink;
  579. // Windows reports if the link points to a directory.
  580. if (fpstat(PAnsiChar(FN),LinkInfo)>=0) and fpS_ISDIR(LinkInfo.st_mode) then
  581. Result := Result or faDirectory;
  582. end;
  583. end;
  584. {$ifdef USE_STATX}
  585. Function LinuxToWinAttr (const FN : RawByteString; Const Info : TStatx) : Longint;
  586. Var
  587. LinkInfo : Stat;
  588. nm : RawByteString;
  589. begin
  590. Result:=faArchive;
  591. If fpS_ISDIR(Info.stx_mode) then
  592. Result:=Result or faDirectory;
  593. nm:=ExtractFileName(FN);
  594. If (Length(nm)>=2) and
  595. (nm[1]='.') and
  596. (nm[2]<>'.') then
  597. Result:=Result or faHidden;
  598. If (Info.stx_Mode and S_IWUSR)=0 Then
  599. Result:=Result or faReadOnly;
  600. 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
  601. Result:=Result or faSysFile;
  602. If fpS_ISLNK(Info.stx_mode) Then
  603. begin
  604. Result:=Result or faSymLink;
  605. // Windows reports if the link points to a directory.
  606. { as we are only interested in the st_mode field here, we do not need to use statx }
  607. if (fpstat(PAnsiChar(FN),LinkInfo)>=0) and fpS_ISDIR(LinkInfo.st_mode) then
  608. Result := Result or faDirectory;
  609. end;
  610. end;
  611. {$endif USE_STATX}
  612. function FileGetSymLinkTarget(const FileName: RawByteString; out SymLinkRec: TRawbyteSymLinkRec): Boolean;
  613. var
  614. Info : Stat;
  615. SystemFileName: RawByteString;
  616. begin
  617. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  618. if (fplstat(SystemFileName,Info)>=0) and fpS_ISLNK(Info.st_mode) then begin
  619. FillByte(SymLinkRec, SizeOf(SymLinkRec), 0);
  620. SymLinkRec.TargetName:=fpreadlink(SystemFileName);
  621. if fpstat(pointer(SystemFileName), Info) < 0 then
  622. raise EDirectoryNotFoundException.Create(SysErrorMessage(GetLastOSError));
  623. SymLinkRec.Attr := LinuxToWinAttr(SystemFileName, Info);
  624. SymLinkRec.Size := Info.st_size;
  625. SymLinkRec.Mode := Info.st_mode;
  626. Result:=True;
  627. end else
  628. Result:=False;
  629. end;
  630. Function FileExists (Const FileName : RawByteString; FollowLink : Boolean) : Boolean;
  631. var
  632. Info : Stat;
  633. SystemFileName: RawByteString;
  634. isdir: Boolean;
  635. begin
  636. // Do not call fpAccess with an empty name. (Valgrind will complain)
  637. if Filename='' then
  638. Exit(False);
  639. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  640. // Don't use stat. It fails on files >2 GB.
  641. // Access obeys the same access rules, so the result should be the same.
  642. FileExists:=fpAccess(pointer(SystemFileName),F_OK)=0;
  643. { we need to ensure however that we aren't dealing with a directory }
  644. isdir:=False;
  645. if FileExists then begin
  646. if (fpstat(pointer(SystemFileName),Info)>=0) and fpS_ISDIR(Info.st_mode) then begin
  647. FileExists:=False;
  648. isdir:=True;
  649. end;
  650. end;
  651. { if we shall not follow the link we only need to check for a symlink if the
  652. target file itself should not exist }
  653. if not FileExists and not isdir and not FollowLink then
  654. FileExists:=(fplstat(pointer(SystemFileName),Info)>=0) and fpS_ISLNK(Info.st_mode);
  655. end;
  656. Function DirectoryExists (Const Directory : RawByteString; FollowLink : Boolean) : Boolean;
  657. Var
  658. Info : Stat;
  659. SystemFileName: RawByteString;
  660. exists: Boolean;
  661. begin
  662. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Directory);
  663. exists:=fpstat(pointer(SystemFileName),Info)>=0;
  664. DirectoryExists:=exists and fpS_ISDIR(Info.st_mode);
  665. { if we shall not follow the link we only need to check for a symlink if the
  666. target directory itself should not exist }
  667. if not exists and not FollowLink then
  668. DirectoryExists:=(fplstat(pointer(SystemFileName),Info)>=0) and fpS_ISLNK(Info.st_mode);
  669. end;
  670. { assumes that pattern and name have the same code page }
  671. Function FNMatch(const Pattern,Name:string):Boolean;
  672. Var
  673. LenPat,LenName : longint;
  674. function NameUtf8CodePointLen(index: longint): longint;
  675. var
  676. MaxLookAhead: longint;
  677. begin
  678. MaxLookAhead:=LenName-Index+1;
  679. { abs so that in case of an invalid sequence, we count this as one
  680. codepoint }
  681. NameUtf8CodePointLen:=abs(Utf8CodePointLen(pansichar(@Name[index]),MaxLookAhead,true));
  682. { if the sequence was incomplete, use the incomplete sequence as
  683. codepoint }
  684. if NameUtf8CodePointLen=0 then
  685. NameUtf8CodePointLen:=MaxLookAhead;
  686. end;
  687. procedure GoToLastByteOfUtf8CodePoint(var j: longint);
  688. begin
  689. inc(j,NameUtf8CodePointLen(j)-1);
  690. end;
  691. { input:
  692. i: current position in pattern (start of utf-8 code point)
  693. j: current position in name (start of utf-8 code point)
  694. update_i_j: should i and j be changed by the routine or not
  695. output:
  696. i: if update_i_j, then position of last matching part of code point in
  697. pattern, or first non-matching code point in pattern. Otherwise the
  698. same value as on input.
  699. j: if update_i_j, then position of last matching part of code point in
  700. name, or first non-matching code point in name. Otherwise the
  701. same value as on input.
  702. result: true if match, false if no match
  703. }
  704. function CompareUtf8CodePoint(var i,j: longint; update_i_j: boolean): Boolean;
  705. var
  706. bytes,
  707. new_i,
  708. new_j: longint;
  709. begin
  710. bytes:=NameUtf8CodePointLen(j);
  711. new_i:=i;
  712. new_j:=j;
  713. { ensure that a part of an UTF-8 codepoint isn't interpreted
  714. as '*' or '?' }
  715. repeat
  716. dec(bytes);
  717. Result:=
  718. (new_j<=LenName) and
  719. (new_i<=LenPat) and
  720. (Pattern[new_i]=Name[new_j]);
  721. inc(new_i);
  722. inc(new_j);
  723. until not(Result) or
  724. (bytes=0);
  725. if update_i_j then
  726. begin
  727. i:=new_i;
  728. j:=new_j;
  729. end;
  730. end;
  731. Function DoFNMatch(i,j:longint):Boolean;
  732. Var
  733. UTF8, Found : boolean;
  734. Begin
  735. Found:=true;
  736. { ensure that we don't skip partial characters in UTF-8-encoded strings }
  737. UTF8:=StringCodePage(Name)=CP_UTF8;
  738. While Found and (i<=LenPat) Do
  739. Begin
  740. Case Pattern[i] of
  741. '?' :
  742. begin
  743. Found:=(j<=LenName);
  744. if UTF8 then
  745. GoToLastByteOfUtf8CodePoint(j);
  746. end;
  747. '*' : Begin
  748. {find the next character in pattern, different of ? and *}
  749. while Found do
  750. begin
  751. inc(i);
  752. if i>LenPat then
  753. Break;
  754. case Pattern[i] of
  755. '*' : ;
  756. '?' : begin
  757. if j>LenName then
  758. begin
  759. DoFNMatch:=false;
  760. Exit;
  761. end;
  762. if UTF8 then
  763. GoToLastByteOfUtf8CodePoint(j);
  764. inc(j);
  765. end;
  766. else
  767. Found:=false;
  768. end;
  769. end;
  770. Assert((i>LenPat) or ( (Pattern[i]<>'*') and (Pattern[i]<>'?') ));
  771. { Now, find in name the character which i points to, if the * or
  772. ? wasn't the last character in the pattern, else, use up all
  773. the chars in name }
  774. Found:=false;
  775. if (i<=LenPat) then
  776. begin
  777. repeat
  778. {find a letter (not only first !) which maches pattern[i]}
  779. if UTF8 then
  780. begin
  781. while (j<=LenName) and
  782. ((name[j]<>pattern[i]) or
  783. not CompareUtf8CodePoint(i,j,false)) do
  784. begin
  785. GoToLastByteOfUtf8CodePoint(j);
  786. inc(j);
  787. end;
  788. end
  789. else
  790. begin
  791. while (j<=LenName) and (name[j]<>pattern[i]) do
  792. inc (j);
  793. end;
  794. if (j<LenName) then
  795. begin
  796. { while positions i/j have already been checked, in
  797. case of UTF-8 we have to ensure that we don't split
  798. a code point. Otherwise we can skip over comparing
  799. the same characters twice }
  800. if DoFnMatch(i+ord(not UTF8),j+ord(not UTF8)) then
  801. begin
  802. i:=LenPat;
  803. j:=LenName;{we can stop}
  804. Found:=true;
  805. Break;
  806. end
  807. { We didn't find one, need to look further }
  808. else
  809. begin
  810. if UTF8 then
  811. GoToLastByteOfUtf8CodePoint(j);
  812. inc(j);
  813. end;
  814. end
  815. else if j=LenName then
  816. begin
  817. Found:=true;
  818. Break;
  819. end;
  820. { This 'until' condition must be j>LenName, not j>=LenName.
  821. That's because when we 'need to look further' and
  822. j = LenName then loop must not terminate. }
  823. until (j>LenName);
  824. end
  825. else
  826. begin
  827. j:=LenName;{we can stop}
  828. Found:=true;
  829. end;
  830. end;
  831. #128..#255:
  832. begin
  833. Found:=(j<=LenName) and (pattern[i]=name[j]);
  834. if Found and UTF8 then
  835. begin
  836. { ensure that a part of an UTF-8 codepoint isn't matched with
  837. '*' or '?' }
  838. Found:=CompareUtf8CodePoint(i,j,true);
  839. { at this point, either Found is false (and we'll stop), or
  840. both pattern[i] and name[j] are the end of the current code
  841. point and equal }
  842. end
  843. end
  844. else {not a wildcard character in pattern}
  845. Found:=(j<=LenName) and (pattern[i]=name[j]);
  846. end;
  847. inc(i);
  848. inc(j);
  849. end;
  850. DoFnMatch:=Found and (j>LenName);
  851. end;
  852. Begin {start FNMatch}
  853. LenPat:=Length(Pattern);
  854. LenName:=Length(Name);
  855. FNMatch:=DoFNMatch(1,1);
  856. End;
  857. Type
  858. TUnixFindData = Record
  859. NamePos : LongInt; {to track which search this is}
  860. DirPtr : Pointer; {directory pointer for reading directory}
  861. SearchSpec : RawbyteString;
  862. SearchType : Byte; {0=normal, 1=open will close, 2=only 1 file}
  863. SearchAttr : Longint; {attribute we are searching for}
  864. End;
  865. PUnixFindData = ^TUnixFindData;
  866. Procedure InternalFindClose(var Handle: Pointer);
  867. var
  868. D: PUnixFindData absolute Handle;
  869. begin
  870. If D=Nil then
  871. Exit;
  872. if D^.SearchType=0 then
  873. begin
  874. if D^.dirptr<>nil then
  875. fpclosedir(pdir(D^.dirptr)^);
  876. end;
  877. Dispose(D);
  878. D:=nil;
  879. end;
  880. Function FindGetFileInfo(const s: RawByteString; var f: TAbstractSearchRec; var Name: RawByteString):boolean;
  881. Var
  882. {$ifdef USE_STATX}
  883. stx : {$ifdef FPC_DOTTEDUNITS}LinuxApi.{$else}linux.{$endif}tstatx;
  884. {$endif USE_STATX}
  885. st : BU.stat;
  886. WinAttr : longint;
  887. begin
  888. {$ifdef USE_STATX}
  889. {$ifdef FPC_USE_LIBC}
  890. if (@statx=nil) then
  891. FindGetFileInfo:=false
  892. else
  893. {$endif}
  894. if Assigned(f.FindHandle) and ( (PUnixFindData(F.FindHandle)^.searchattr and faSymlink) > 0) then
  895. FindGetFileInfo:=statx(AT_FDCWD,pointer(s),AT_SYMLINK_NOFOLLOW,STATX_ALL,stx)=0
  896. else
  897. begin
  898. FindGetFileInfo:=statx(AT_FDCWD,pointer(s),0,STATX_ALL,stx)=0;
  899. end;
  900. if FindGetFileInfo then
  901. begin
  902. WinAttr:=LinuxToWinAttr(s,stx);
  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:=stx.stx_Size;
  909. f.Mode:=stx.stx_mode;
  910. f.Time:=stx.stx_mtime.tv_sec;
  911. FindGetFileInfo:=true;
  912. end;
  913. end
  914. { no statx? try stat }
  915. else if fpgeterrno=ESysENOSYS then
  916. {$endif USE_STATX}
  917. begin
  918. if Assigned(f.FindHandle) and ( (PUnixFindData(F.FindHandle)^.searchattr and faSymlink) > 0) then
  919. FindGetFileInfo:=(fplstat(pointer(s),st)=0)
  920. else
  921. FindGetFileInfo:=(fpstat(pointer(s),st)=0);
  922. if not FindGetFileInfo then
  923. exit;
  924. WinAttr:=LinuxToWinAttr(s,st);
  925. FindGetFileInfo:=(WinAttr and Not(PUnixFindData(f.FindHandle)^.searchattr))=0;
  926. if FindGetFileInfo then
  927. begin
  928. Name:=ExtractFileName(s);
  929. f.Attr:=WinAttr;
  930. f.Size:=st.st_Size;
  931. f.Mode:=st.st_mode;
  932. f.Time:=st.st_mtime;
  933. FindGetFileInfo:=true;
  934. end;
  935. end;
  936. end;
  937. // Returns the FOUND filename. Error code <> 0 if no file found
  938. Function InternalFindNext (var Rslt : TAbstractSearchRec; var Name : RawByteString) : Longint;
  939. Var
  940. DirName : RawByteString;
  941. FName,
  942. SName : RawBytestring;
  943. Found,
  944. Finished : boolean;
  945. p : pdirent;
  946. UnixFindData : PUnixFindData;
  947. Begin
  948. Result:=-1;
  949. UnixFindData:=PUnixFindData(Rslt.FindHandle);
  950. { SearchSpec='' means that there were no wild cards, so only one file to
  951. find.
  952. }
  953. If (UnixFindData=Nil) or (UnixFindData^.SearchSpec='') then
  954. exit;
  955. if (UnixFindData^.SearchType=0) and
  956. (UnixFindData^.Dirptr=nil) then
  957. begin
  958. If UnixFindData^.NamePos = 0 Then
  959. DirName:='./'
  960. Else
  961. DirName:=Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos);
  962. UnixFindData^.DirPtr := fpopendir(PAnsiChar(DirName));
  963. end;
  964. SName:=Copy(UnixFindData^.SearchSpec,UnixFindData^.NamePos+1,Length(UnixFindData^.SearchSpec));
  965. Found:=False;
  966. Finished:=(UnixFindData^.dirptr=nil);
  967. While Not Finished Do
  968. Begin
  969. p:=fpreaddir(pdir(UnixFindData^.dirptr)^);
  970. if p=nil then
  971. FName:=''
  972. else
  973. FName:=p^.d_name;
  974. If FName='' Then
  975. Finished:=True
  976. Else
  977. Begin
  978. SetCodePage(FName,DefaultFileSystemCodePage,false);
  979. If FNMatch(SName,FName) Then
  980. Begin
  981. Found:=FindGetFileInfo(Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos)+FName,Rslt,Name);
  982. if Found then
  983. begin
  984. Result:=0;
  985. exit;
  986. end;
  987. End;
  988. End;
  989. End;
  990. End;
  991. Function InternalFindFirst (Const Path : RawByteString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name: RawByteString) : Longint;
  992. {
  993. opens dir and calls FindNext if needed.
  994. }
  995. var
  996. UnixFindData : PUnixFindData;
  997. Begin
  998. Result:=-1;
  999. { this is safe even though Rslt actually contains a refcounted field, because
  1000. it is declared as "out" and hence has already been initialised }
  1001. fillchar(Rslt,sizeof(Rslt),0);
  1002. if Path='' then
  1003. exit;
  1004. { Allocate UnixFindData (we always need it, for the search attributes) }
  1005. New(UnixFindData);
  1006. FillChar(UnixFindData^,sizeof(UnixFindData^),0);
  1007. Rslt.FindHandle:=UnixFindData;
  1008. {We always also search for readonly and archive, regardless of Attr:}
  1009. UnixFindData^.SearchAttr := Attr or faarchive or fareadonly;
  1010. {Wildcards?}
  1011. if (Pos('?',Path)=0) and (Pos('*',Path)=0) then
  1012. begin
  1013. if FindGetFileInfo(ToSingleByteFileSystemEncodedFileName(Path),Rslt,Name) then
  1014. Result:=0;
  1015. end
  1016. else
  1017. begin
  1018. {Create Info}
  1019. UnixFindData^.SearchSpec := ToSingleByteFileSystemEncodedFileName(Path);
  1020. UnixFindData^.NamePos := Length(UnixFindData^.SearchSpec);
  1021. while (UnixFindData^.NamePos>0) and (UnixFindData^.SearchSpec[UnixFindData^.NamePos]<>'/') do
  1022. dec(UnixFindData^.NamePos);
  1023. Result:=InternalFindNext(Rslt,Name);
  1024. end;
  1025. If (Result<>0) then
  1026. InternalFindClose(Rslt.FindHandle);
  1027. End;
  1028. Function FileGetDate (Handle : Longint) : Int64;
  1029. Var
  1030. Info : Stat;
  1031. {$ifdef USE_STATX}
  1032. Infox : TStatx;
  1033. {$endif USE_STATX}
  1034. Char0 : AnsiChar;
  1035. begin
  1036. Result:=-1;
  1037. {$ifdef USE_STATX}
  1038. Char0:=#0;
  1039. if {$ifdef FPC_USE_LIBC} (@statx<>nil) and {$endif}
  1040. (statx(Handle,@Char0,AT_EMPTY_PATH,STATX_MTIME,Infox)=0) then
  1041. Result:=Infox.stx_Mtime.tv_sec
  1042. else if fpgeterrno=ESysENOSYS then
  1043. {$endif USE_STATX}
  1044. begin
  1045. If fpFStat(Handle,Info)=0 then
  1046. Result:=Info.st_Mtime;
  1047. end;
  1048. end;
  1049. Function FileSetDate (Handle : Longint;Age : Int64) : Longint;
  1050. {$ifdef USE_FUTIMES}
  1051. var
  1052. times : TTimespecArr;
  1053. {$endif USE_FUTIMES}
  1054. begin
  1055. Result:=0;
  1056. {$ifdef USE_FUTIMES}
  1057. times[0].tv_sec:=Age;
  1058. times[0].tv_nsec:=0;
  1059. times[1].tv_sec:=Age;
  1060. times[1].tv_nsec:=0;
  1061. if fpfutimens(Handle,times) = -1 then
  1062. Result:=fpgeterrno;
  1063. {$else USE_FUTIMES}
  1064. FileSetDate:=-1;
  1065. {$endif USE_FUTIMES}
  1066. end;
  1067. Function FileGetAttr (Const FileName : RawByteString) : Longint;
  1068. Var
  1069. SystemFileName: RawByteString;
  1070. Info : Stat;
  1071. res : Integer;
  1072. begin
  1073. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1074. res:=FpLStat(pointer(SystemFileName),Info);
  1075. if res<0 then
  1076. res:=FpStat(pointer(SystemFileName),Info);
  1077. if res<0 then
  1078. Result:=-1
  1079. Else
  1080. Result:=LinuxToWinAttr(SystemFileName,Info);
  1081. end;
  1082. Function FileSetAttr (Const Filename : RawByteString; Attr: longint) : Longint;
  1083. begin
  1084. Result:=-1;
  1085. end;
  1086. Function DeleteFile (Const FileName : RawByteString) : Boolean;
  1087. var
  1088. SystemFileName: RawByteString;
  1089. begin
  1090. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1091. Result:=fpUnLink (PAnsiChar(SystemFileName))>=0;
  1092. end;
  1093. Function RenameFile (Const OldName, NewName : RawByteString) : Boolean;
  1094. var
  1095. SystemOldName, SystemNewName: RawByteString;
  1096. begin
  1097. SystemOldName:=ToSingleByteFileSystemEncodedFileName(OldName);
  1098. SystemNewName:=ToSingleByteFileSystemEncodedFileName(NewName);
  1099. RenameFile:=BU.FpRename(pointer(SystemOldName),pointer(SystemNewName))>=0;
  1100. end;
  1101. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  1102. var
  1103. SystemFileName: RawByteString;
  1104. begin
  1105. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1106. Result:=fpAccess(PAnsiChar(SystemFileName),W_OK)<>0;
  1107. end;
  1108. Function FileSetDate (Const FileName : RawByteString; Age : Int64) : Longint;
  1109. var
  1110. SystemFileName: RawByteString;
  1111. {$ifdef USE_UTIMENSAT}
  1112. times : TTimespecArr;
  1113. {$endif USE_UTIMENSAT}
  1114. t: TUTimBuf;
  1115. begin
  1116. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1117. Result:=0;
  1118. {$ifdef USE_UTIMENSAT}
  1119. times[0].tv_sec:=Age;
  1120. times[0].tv_nsec:=0;
  1121. times[1].tv_sec:=Age;
  1122. times[1].tv_nsec:=0;
  1123. if utimensat(AT_FDCWD,PAnsiChar(SystemFileName),times,0) = -1 then
  1124. Result:=fpgeterrno;
  1125. if fpgeterrno=ESysENOSYS then
  1126. {$endif USE_UTIMENSAT}
  1127. begin
  1128. Result:=0;
  1129. t.actime:= Age;
  1130. t.modtime:=Age;
  1131. if fputime(PAnsiChar(SystemFileName), @t) = -1 then
  1132. Result:=fpgeterrno;
  1133. end
  1134. end;
  1135. {$IF defined(DARWIN)}
  1136. Function IsFileNameCaseSensitive(Const aFileName : RawByteString) : Boolean;
  1137. var
  1138. res : clong;
  1139. begin
  1140. res:=FpPathconf(PAnsiChar(aFileName),11 {_PC_CASE_SENSITIVE });
  1141. { fall back to default if path is not found }
  1142. if res<0 then
  1143. Result:=FileNameCaseSensitive
  1144. else
  1145. Result:=res<>0;
  1146. end;
  1147. Function IsFileNameCaseSensitive(Const aFileName : UnicodeString) : Boolean;
  1148. begin
  1149. Result:=IsFileNameCaseSensitive(RawByteString(aFileName));
  1150. end;
  1151. Function IsFileNameCasePreserving(Const aFileName : RawByteString) : Boolean;
  1152. var
  1153. res : clong;
  1154. begin
  1155. res:=FpPathconf(PAnsiChar(aFileName),12 { _PC_CASE_PRESERVING });
  1156. if res<0 then
  1157. { fall back to default if path is not found }
  1158. Result:=FileNameCasePreserving
  1159. else
  1160. Result:=res<>0;
  1161. end;
  1162. Function IsFileNameCasePreserving(Const aFileName : UnicodeString) : Boolean;
  1163. begin
  1164. Result:=IsFileNameCasePreserving(RawByteString(aFileName));
  1165. end;
  1166. {$ENDIF defined(DARWIN)}
  1167. {****************************************************************************
  1168. Disk Functions
  1169. ****************************************************************************}
  1170. {
  1171. The Diskfree and Disksize functions need a file on the specified drive, since this
  1172. is required for the fpstatfs system call.
  1173. These filenames are set in drivestr[0..26], and have been preset to :
  1174. 0 - '.' (default drive - hence current dir is ok.)
  1175. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  1176. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  1177. 3 - '/' (C: equivalent of dos is the root partition)
  1178. 4..26 (can be set by you're own applications)
  1179. ! Use AddDisk() to Add new drives !
  1180. They both return -1 when a failure occurs.
  1181. }
  1182. Const
  1183. FixDriveStr : array[0..3] of PAnsiChar=(
  1184. '.',
  1185. '/fd0/.',
  1186. '/fd1/.',
  1187. '/.'
  1188. );
  1189. var
  1190. Drives : byte = 4;
  1191. DriveStr : array[4..26] of PAnsiChar;
  1192. Function GetDriveStr(Drive : Byte) : PAnsiChar;
  1193. begin
  1194. case Drive of
  1195. Low(FixDriveStr)..High(FixDriveStr):
  1196. Result := FixDriveStr[Drive];
  1197. Low(DriveStr)..High(DriveStr):
  1198. Result := DriveStr[Drive];
  1199. else
  1200. Result := nil;
  1201. end;
  1202. end;
  1203. Function DiskFree(Drive: Byte): int64;
  1204. var
  1205. p : PAnsiChar;
  1206. fs : TStatfs;
  1207. Begin
  1208. p:=GetDriveStr(Drive);
  1209. if (p<>nil) and (fpStatFS(p, @fs)<>-1) then
  1210. DiskFree := int64(fs.bavail)*int64(fs.bsize)
  1211. else
  1212. DiskFree := -1;
  1213. End;
  1214. Function DiskSize(Drive: Byte): int64;
  1215. var
  1216. p : PAnsiChar;
  1217. fs : TStatfs;
  1218. Begin
  1219. p:=GetDriveStr(Drive);
  1220. if (p<>nil) and (fpStatFS(p, @fs)<>-1) then
  1221. DiskSize := int64(fs.blocks)*int64(fs.bsize)
  1222. else
  1223. DiskSize := -1;
  1224. End;
  1225. Function AddDisk(const path: string): Byte;
  1226. begin
  1227. if DriveStr[Drives]<>nil then
  1228. FreeMem(DriveStr[Drives]);
  1229. GetMem(DriveStr[Drives],length(Path)+1);
  1230. StrPCopy(DriveStr[Drives],path);
  1231. Result:=Drives;
  1232. inc(Drives);
  1233. if Drives>High(DriveStr) then
  1234. Drives:=Low(DriveStr);
  1235. end;
  1236. Procedure FreeDriveStr;
  1237. var
  1238. i: longint;
  1239. begin
  1240. for i:=low(drivestr) to high(drivestr) do
  1241. if assigned(drivestr[i]) then
  1242. begin
  1243. freemem(drivestr[i]);
  1244. drivestr[i]:=nil;
  1245. end;
  1246. end;
  1247. {****************************************************************************
  1248. Misc Functions
  1249. ****************************************************************************}
  1250. {****************************************************************************
  1251. Locale Functions
  1252. ****************************************************************************}
  1253. Function GetEpochTime: time_t;
  1254. {
  1255. Get the number of seconds since 00:00, January 1 1970, GMT
  1256. the time NOT corrected any way
  1257. }
  1258. begin
  1259. GetEpochTime:=fptime;
  1260. end;
  1261. Procedure DoGetUniversalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  1262. var
  1263. tz:timeval;
  1264. begin
  1265. fpgettimeofday(@tz,nil);
  1266. EpochToUniversal(tz.tv_sec,year,month,day,hour,min,sec);
  1267. msec:=tz.tv_usec div 1000;
  1268. usec:=tz.tv_usec mod 1000;
  1269. end;
  1270. // Now, adjusted to local time.
  1271. Procedure DoGetLocalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  1272. var
  1273. tz:timeval;
  1274. begin
  1275. fpgettimeofday(@tz,nil);
  1276. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  1277. msec:=tz.tv_usec div 1000;
  1278. usec:=tz.tv_usec mod 1000;
  1279. end;
  1280. procedure GetTime(var hour,min,sec,msec,usec:word);
  1281. Var
  1282. year,day,month:Word;
  1283. begin
  1284. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1285. end;
  1286. procedure GetTime(var hour,min,sec,sec100:word);
  1287. {
  1288. Gets the current time, adjusted to local time
  1289. }
  1290. var
  1291. year,day,month,usec : word;
  1292. begin
  1293. DoGetLocalDateTime(year,month,day,hour,min,sec,sec100,usec);
  1294. sec100:=sec100 div 10;
  1295. end;
  1296. Procedure GetTime(Var Hour,Min,Sec:Word);
  1297. {
  1298. Gets the current time, adjusted to local time
  1299. }
  1300. var
  1301. year,day,month,msec,usec : Word;
  1302. Begin
  1303. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1304. End;
  1305. Procedure GetDate(Var Year,Month,Day:Word);
  1306. {
  1307. Gets the current date, adjusted to local time
  1308. }
  1309. var
  1310. hour,minute,second,msec,usec : word;
  1311. Begin
  1312. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1313. End;
  1314. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  1315. {
  1316. Gets the current date, adjusted to local time
  1317. }
  1318. Var
  1319. usec,msec : word;
  1320. Begin
  1321. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1322. End;
  1323. {$ifndef FPUNONE}
  1324. Procedure GetLocalTime(var SystemTime: TSystemTime);
  1325. var
  1326. usecs : Word;
  1327. begin
  1328. DoGetLocalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1329. SystemTime.DayOfWeek:=DayOfWeek(EncodeDate(SystemTime.Year,SystemTime.Month,SystemTime.Day))-1;
  1330. end ;
  1331. {$endif}
  1332. Procedure InitAnsi;
  1333. Var
  1334. i : longint;
  1335. begin
  1336. { Fill table entries 0 to 127 }
  1337. for i := 0 to 96 do
  1338. UpperCaseTable[i] := chr(i);
  1339. for i := 97 to 122 do
  1340. UpperCaseTable[i] := chr(i - 32);
  1341. for i := 123 to 191 do
  1342. UpperCaseTable[i] := chr(i);
  1343. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  1344. for i := 0 to 64 do
  1345. LowerCaseTable[i] := chr(i);
  1346. for i := 65 to 90 do
  1347. LowerCaseTable[i] := chr(i + 32);
  1348. for i := 91 to 191 do
  1349. LowerCaseTable[i] := chr(i);
  1350. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  1351. end;
  1352. Procedure InitInternational;
  1353. begin
  1354. InitInternationalGeneric;
  1355. InitAnsi;
  1356. end;
  1357. function SysErrorMessage(ErrorCode: Integer): String;
  1358. begin
  1359. Result:=StrError(ErrorCode);
  1360. end;
  1361. {****************************************************************************
  1362. OS utility functions
  1363. ****************************************************************************}
  1364. Function GetEnvironmentVariable(Const EnvVar : AnsiString) : AnsiString;
  1365. begin
  1366. Result:=BU.FPGetenv(PAnsiChar(pointer(EnvVar)));
  1367. end;
  1368. Function GetEnvironmentVariableCount : Integer;
  1369. begin
  1370. Result:=FPCCountEnvVar(EnvP);
  1371. end;
  1372. Function GetEnvironmentString(Index : Integer) : RTLString;
  1373. begin
  1374. Result:=FPCGetEnvStrFromP(Envp,Index);
  1375. end;
  1376. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1377. var
  1378. pid : longint;
  1379. e : EOSError;
  1380. CommandLine: RawByteString;
  1381. LPath : RawByteString;
  1382. cmdline2 : PPAnsiChar;
  1383. Begin
  1384. { always surround the name of the application by quotes
  1385. so that long filenames will always be accepted. But don't
  1386. do it if there are already double quotes!
  1387. }
  1388. // Only place we still parse
  1389. cmdline2:=nil;
  1390. LPath:=Path;
  1391. UniqueString(LPath);
  1392. SetCodePage(LPath,DefaultFileSystemCodePage,true);
  1393. if Comline<>'' Then
  1394. begin
  1395. CommandLine:=ComLine;
  1396. { Make an unique copy because stringtoppchar modifies the
  1397. string, and force conversion to intended fscp }
  1398. UniqueString(CommandLine);
  1399. SetCodePage(CommandLine,DefaultFileSystemCodePage,true);
  1400. cmdline2:=StringtoPPChar(CommandLine,1);
  1401. cmdline2^:=PAnsiChar(pointer(LPath));
  1402. end
  1403. else
  1404. begin
  1405. getmem(cmdline2,2*sizeof(PAnsiChar));
  1406. cmdline2^:=PAnsiChar(LPath);
  1407. cmdline2[1]:=nil;
  1408. end;
  1409. {$ifdef USE_VFORK}
  1410. pid:=fpvFork;
  1411. {$else USE_VFORK}
  1412. pid:=fpFork;
  1413. {$endif USE_VFORK}
  1414. if pid=0 then
  1415. begin
  1416. {The child does the actual exec, and then exits}
  1417. fpexecve(PAnsiChar(pointer(LPath)),Cmdline2,envp);
  1418. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1419. fpExit(127);
  1420. end
  1421. else
  1422. if pid=-1 then {Fork failed}
  1423. begin
  1424. e:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,-1]);
  1425. e.ErrorCode:=-1;
  1426. raise e;
  1427. end;
  1428. { We're in the parent, let's wait. }
  1429. result:=WaitProcess(pid); // WaitPid and result-convert
  1430. if Comline<>'' Then
  1431. freemem(cmdline2);
  1432. if (result<0) or (result=127) then
  1433. begin
  1434. E:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,result]);
  1435. E.ErrorCode:=result;
  1436. Raise E;
  1437. end;
  1438. End;
  1439. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array Of RawByteString;Flags:TExecuteFlags=[]):integer;
  1440. var
  1441. pid : longint;
  1442. e : EOSError;
  1443. Begin
  1444. pid:=fpFork;
  1445. if pid=0 then
  1446. begin
  1447. {The child does the actual exec, and then exits}
  1448. fpexecl(Path,Comline);
  1449. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1450. fpExit(127);
  1451. end
  1452. else
  1453. if pid=-1 then {Fork failed}
  1454. begin
  1455. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1456. e.ErrorCode:=-1;
  1457. raise e;
  1458. end;
  1459. { We're in the parent, let's wait. }
  1460. result:=WaitProcess(pid); // WaitPid and result-convert
  1461. if (result<0) or (result=127) then
  1462. begin
  1463. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1464. E.ErrorCode:=result;
  1465. raise E;
  1466. end;
  1467. End;
  1468. procedure Sleep(milliseconds: Cardinal);
  1469. Var
  1470. timeout,timeoutresult : TTimespec;
  1471. res: cint;
  1472. begin
  1473. timeout.tv_sec:=milliseconds div 1000;
  1474. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  1475. repeat
  1476. res:=fpnanosleep(@timeout,@timeoutresult);
  1477. timeout:=timeoutresult;
  1478. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  1479. end;
  1480. Function GetLastOSError : Integer;
  1481. begin
  1482. Result:=fpgetErrNo;
  1483. end;
  1484. { ---------------------------------------------------------------------
  1485. Application config files
  1486. ---------------------------------------------------------------------}
  1487. {$ifdef android}
  1488. var
  1489. _HomeDir: string;
  1490. _HasPackageDataDir: boolean;
  1491. Function GetHomeDir : String;
  1492. var
  1493. h: longint;
  1494. i: longint;
  1495. begin
  1496. Result:=_HomeDir;
  1497. if Result <> '' then
  1498. exit;
  1499. if IsLibrary then
  1500. begin
  1501. // For shared library get the package name of a host Java application
  1502. h:=FileOpen('/proc/self/cmdline', fmOpenRead or fmShareDenyNone);
  1503. if h >= 0 then
  1504. begin
  1505. SetLength(Result, MAX_PATH);
  1506. SetLength(Result, FileRead(h, Result[1], Length(Result)));
  1507. SetLength(Result, strlen(PAnsiChar(Result)));
  1508. FileClose(h);
  1509. Result:='/data/data/' + Result;
  1510. _HasPackageDataDir:=DirectoryExists(Result);
  1511. if _HasPackageDataDir then
  1512. begin
  1513. Result:=Result + '/files/';
  1514. ForceDirectories(Result);
  1515. end
  1516. else
  1517. Result:=''; // No package
  1518. end;
  1519. end;
  1520. if Result = '' then
  1521. Result:='/data/local/tmp/';
  1522. _HomeDir:=Result;
  1523. end;
  1524. Function XdgConfigHome : String;
  1525. begin
  1526. Result:=GetHomeDir;
  1527. end;
  1528. {$else}
  1529. Function GetHomeDir : String;
  1530. begin
  1531. Result:=GetEnvironmentVariable('HOME');
  1532. If (Result<>'') then
  1533. Result:=IncludeTrailingPathDelimiter(Result);
  1534. end;
  1535. { Follows base-dir spec,
  1536. see [http://freedesktop.org/Standards/basedir-spec].
  1537. Always ends with PathDelim. }
  1538. Function XdgConfigHome : String;
  1539. begin
  1540. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  1541. if (Result='') then
  1542. Result:=GetHomeDir + '.config/'
  1543. else
  1544. Result:=IncludeTrailingPathDelimiter(Result);
  1545. end;
  1546. {$endif android}
  1547. Function GetAppConfigDir(Global : Boolean) : String;
  1548. begin
  1549. If Global then
  1550. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1551. else
  1552. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1553. {$ifdef android}
  1554. if _HasPackageDataDir then
  1555. exit;
  1556. {$endif android}
  1557. if VendorName<>'' then
  1558. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1559. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1560. end;
  1561. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1562. begin
  1563. If Global then
  1564. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1565. else
  1566. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1567. {$ifdef android}
  1568. if _HasPackageDataDir then
  1569. begin
  1570. Result:=Result+'config'+ConfigExtension;
  1571. exit;
  1572. end;
  1573. {$endif android}
  1574. if SubDir then
  1575. begin
  1576. if VendorName<>'' then
  1577. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1578. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1579. end;
  1580. Result:=Result+ApplicationName+ConfigExtension;
  1581. end;
  1582. {****************************************************************************
  1583. GetTempDir
  1584. ****************************************************************************}
  1585. Function GetTempDir(Global : Boolean) : String;
  1586. begin
  1587. If Assigned(OnGetTempDir) then
  1588. Result:=OnGetTempDir(Global)
  1589. else
  1590. begin
  1591. {$ifdef android}
  1592. Result:=GetHomeDir + 'tmp';
  1593. ForceDirectories(Result);
  1594. {$else}
  1595. Result:=GetEnvironmentVariable('TEMP');
  1596. If (Result='') Then
  1597. Result:=GetEnvironmentVariable('TMP');
  1598. If (Result='') Then
  1599. Result:=GetEnvironmentVariable('TMPDIR');
  1600. if (Result='') then
  1601. Result:='/tmp/'; // fallback.
  1602. {$endif android}
  1603. end;
  1604. if (Result<>'') then
  1605. Result:=IncludeTrailingPathDelimiter(Result);
  1606. end;
  1607. {****************************************************************************
  1608. GetUserDir
  1609. ****************************************************************************}
  1610. Var
  1611. TheUserDir : String;
  1612. Function GetUserDir : String;
  1613. begin
  1614. If (TheUserDir='') then
  1615. begin
  1616. {$ifdef android}
  1617. TheUserDir:=GetHomeDir;
  1618. {$else}
  1619. TheUserDir:=GetEnvironmentVariable('HOME');
  1620. {$endif android}
  1621. if (TheUserDir<>'') then
  1622. TheUserDir:=IncludeTrailingPathDelimiter(TheUserDir)
  1623. else
  1624. TheUserDir:=GetTempDir(False);
  1625. end;
  1626. Result:=TheUserDir;
  1627. end;
  1628. Procedure SysBeep;
  1629. begin
  1630. Write(#7);
  1631. Flush(Output);
  1632. end;
  1633. function GetUniversalTime(var SystemTime: TSystemTime): Boolean;
  1634. var
  1635. usecs : Word;
  1636. begin
  1637. DoGetUniversalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1638. Result:=True;
  1639. end;
  1640. function GetLocalTimeOffset: Integer;
  1641. begin
  1642. Result := -Tzseconds div 60;
  1643. end;
  1644. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  1645. var
  1646. Year, Month, Day, Hour, Minute, Second, MilliSecond: word;
  1647. UnixTime: Int64;
  1648. lTZInfo: TTZInfo;
  1649. begin
  1650. DecodeDate(DateTime, Year, Month, Day);
  1651. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  1652. UnixTime:=UniversalToEpoch(Year, Month, Day, Hour, Minute, Second);
  1653. {$if declared(GetLocalTimezone)}
  1654. GetLocalTimeOffset:=GetLocalTimezone(UnixTime,InputIsUTC,lTZInfo);
  1655. if GetLocalTimeOffset then
  1656. Offset:=-lTZInfo.seconds div 60;
  1657. {$else}
  1658. GetLocalTimeOffset:=False;
  1659. {$endif}
  1660. end;
  1661. {$ifdef android}
  1662. procedure InitAndroid;
  1663. var
  1664. dlinfo: dl_info;
  1665. s: string;
  1666. begin
  1667. FillChar(dlinfo, sizeof(dlinfo), 0);
  1668. dladdr(@InitAndroid, @dlinfo);
  1669. s:=dlinfo.dli_fname;
  1670. if s <> '' then
  1671. SetDefaultSysLogTag(ExtractFileName(s));
  1672. end;
  1673. {$endif android}
  1674. {****************************************************************************
  1675. Initialization code
  1676. ****************************************************************************}
  1677. Initialization
  1678. InitExceptions; { Initialize exceptions. OS independent }
  1679. InitInternational; { Initialize internationalization settings }
  1680. SysConfigDir:='/etc'; { Initialize system config dir }
  1681. OnBeep:=@SysBeep;
  1682. {$ifdef android}
  1683. InitAndroid;
  1684. {$endif android}
  1685. Finalization
  1686. FreeDriveStr;
  1687. FreeTerminateProcs;
  1688. DoneExceptions;
  1689. end.