sysutils.pp 50 KB

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