sysutils.pp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804
  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)<=4}
  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 : Statx;
  480. {$endif USE_STATX}
  481. begin
  482. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  483. {$ifdef USE_STATX}
  484. { first try statx }
  485. if (Fpstatx(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 : Statx) : 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.statx;
  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:=Fpstatx(AT_FDCWD,pointer(s),AT_SYMLINK_NOFOLLOW,STATX_ALL,stx)=0
  828. else
  829. FindGetFileInfo:=Fpstatx(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 Info : Stat;
  960. begin
  961. If (fpFStat(Handle,Info))<0 then
  962. Result:=-1
  963. else
  964. Result:=Info.st_Mtime;
  965. end;
  966. Function FileSetDate (Handle : Longint;Age : Int64) : Longint;
  967. {$ifdef USE_FUTIMES}
  968. var
  969. times : tkernel_timespecs;
  970. {$endif USE_FUTIMES}
  971. begin
  972. Result:=0;
  973. {$ifdef USE_FUTIMES}
  974. times[0].tv_sec:=Age;
  975. times[0].tv_nsec:=0;
  976. times[1].tv_sec:=Age;
  977. times[1].tv_nsec:=0;
  978. if fpfutimens(Handle,times) = -1 then
  979. Result:=fpgeterrno;
  980. {$else USE_FUTIMES}
  981. FileSetDate:=-1;
  982. {$endif USE_FUTIMES}
  983. end;
  984. Function FileGetAttr (Const FileName : RawByteString) : Longint;
  985. Var
  986. SystemFileName: RawByteString;
  987. Info : Stat;
  988. res : Integer;
  989. begin
  990. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  991. res:=FpLStat(pointer(SystemFileName),Info);
  992. if res<0 then
  993. res:=FpStat(pointer(SystemFileName),Info);
  994. if res<0 then
  995. Result:=-1
  996. Else
  997. Result:=LinuxToWinAttr(SystemFileName,Info);
  998. end;
  999. Function FileSetAttr (Const Filename : RawByteString; Attr: longint) : Longint;
  1000. begin
  1001. Result:=-1;
  1002. end;
  1003. Function DeleteFile (Const FileName : RawByteString) : Boolean;
  1004. var
  1005. SystemFileName: RawByteString;
  1006. begin
  1007. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1008. Result:=fpUnLink (pchar(SystemFileName))>=0;
  1009. end;
  1010. Function RenameFile (Const OldName, NewName : RawByteString) : Boolean;
  1011. var
  1012. SystemOldName, SystemNewName: RawByteString;
  1013. begin
  1014. SystemOldName:=ToSingleByteFileSystemEncodedFileName(OldName);
  1015. SystemNewName:=ToSingleByteFileSystemEncodedFileName(NewName);
  1016. RenameFile:=BaseUnix.FpRename(pointer(SystemOldName),pointer(SystemNewName))>=0;
  1017. end;
  1018. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  1019. var
  1020. SystemFileName: RawByteString;
  1021. begin
  1022. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1023. Result:=fpAccess(PChar(SystemFileName),W_OK)<>0;
  1024. end;
  1025. Function FileSetDate (Const FileName : RawByteString; Age : Int64) : Longint;
  1026. var
  1027. SystemFileName: RawByteString;
  1028. {$ifdef USE_UTIMENSAT}
  1029. times : tkernel_timespecs;
  1030. {$endif USE_UTIMENSAT}
  1031. t: TUTimBuf;
  1032. begin
  1033. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  1034. Result:=0;
  1035. {$ifdef USE_UTIMENSAT}
  1036. times[0].tv_sec:=Age;
  1037. times[0].tv_nsec:=0;
  1038. times[1].tv_sec:=Age;
  1039. times[1].tv_nsec:=0;
  1040. if fputimensat(AT_FDCWD,PChar(SystemFileName),times,0) = -1 then
  1041. Result:=fpgeterrno;
  1042. if fpgeterrno=ESysENOSYS then
  1043. {$endif USE_UTIMENSAT}
  1044. begin
  1045. Result:=0;
  1046. t.actime:= Age;
  1047. t.modtime:=Age;
  1048. if fputime(PChar(SystemFileName), @t) = -1 then
  1049. Result:=fpgeterrno;
  1050. end
  1051. end;
  1052. {****************************************************************************
  1053. Disk Functions
  1054. ****************************************************************************}
  1055. {
  1056. The Diskfree and Disksize functions need a file on the specified drive, since this
  1057. is required for the fpstatfs system call.
  1058. These filenames are set in drivestr[0..26], and have been preset to :
  1059. 0 - '.' (default drive - hence current dir is ok.)
  1060. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  1061. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  1062. 3 - '/' (C: equivalent of dos is the root partition)
  1063. 4..26 (can be set by you're own applications)
  1064. ! Use AddDisk() to Add new drives !
  1065. They both return -1 when a failure occurs.
  1066. }
  1067. Const
  1068. FixDriveStr : array[0..3] of pchar=(
  1069. '.',
  1070. '/fd0/.',
  1071. '/fd1/.',
  1072. '/.'
  1073. );
  1074. var
  1075. Drives : byte = 4;
  1076. DriveStr : array[4..26] of pchar;
  1077. Function AddDisk(const path:string) : Byte;
  1078. begin
  1079. if not (DriveStr[Drives]=nil) then
  1080. FreeMem(DriveStr[Drives]);
  1081. GetMem(DriveStr[Drives],length(Path)+1);
  1082. StrPCopy(DriveStr[Drives],path);
  1083. Result:=Drives;
  1084. inc(Drives);
  1085. if Drives>26 then
  1086. Drives:=4;
  1087. end;
  1088. Function DiskFree(Drive: Byte): int64;
  1089. var
  1090. fs : tstatfs;
  1091. Begin
  1092. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (fpstatfs(StrPas(fixdrivestr[drive]),@fs)<>-1)) or
  1093. ((Drive in [Low(DriveStr)..High(DriveStr)]) and (not (drivestr[Drive]=nil)) and (fpstatfs(StrPas(drivestr[drive]),@fs)<>-1)) then
  1094. Diskfree:=int64(fs.bavail)*int64(fs.bsize)
  1095. else
  1096. Diskfree:=-1;
  1097. End;
  1098. Function DiskSize(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. DiskSize:=int64(fs.blocks)*int64(fs.bsize)
  1105. else
  1106. DiskSize:=-1;
  1107. End;
  1108. Procedure FreeDriveStr;
  1109. var
  1110. i: longint;
  1111. begin
  1112. for i:=low(drivestr) to high(drivestr) do
  1113. if assigned(drivestr[i]) then
  1114. begin
  1115. freemem(drivestr[i]);
  1116. drivestr[i]:=nil;
  1117. end;
  1118. end;
  1119. {****************************************************************************
  1120. Misc Functions
  1121. ****************************************************************************}
  1122. {****************************************************************************
  1123. Locale Functions
  1124. ****************************************************************************}
  1125. Function GetEpochTime: cint;
  1126. {
  1127. Get the number of seconds since 00:00, January 1 1970, GMT
  1128. the time NOT corrected any way
  1129. }
  1130. begin
  1131. GetEpochTime:=fptime;
  1132. end;
  1133. Procedure DoGetUniversalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  1134. var
  1135. tz:timeval;
  1136. begin
  1137. fpgettimeofday(@tz,nil);
  1138. EpochToUniversal(tz.tv_sec,year,month,day,hour,min,sec);
  1139. msec:=tz.tv_usec div 1000;
  1140. usec:=tz.tv_usec mod 1000;
  1141. end;
  1142. // Now, adjusted to local time.
  1143. Procedure DoGetLocalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  1144. var
  1145. tz:timeval;
  1146. begin
  1147. fpgettimeofday(@tz,nil);
  1148. EpochToLocal(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. procedure GetTime(var hour,min,sec,msec,usec:word);
  1153. Var
  1154. year,day,month:Word;
  1155. begin
  1156. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1157. end;
  1158. procedure GetTime(var hour,min,sec,sec100:word);
  1159. {
  1160. Gets the current time, adjusted to local time
  1161. }
  1162. var
  1163. year,day,month,usec : word;
  1164. begin
  1165. DoGetLocalDateTime(year,month,day,hour,min,sec,sec100,usec);
  1166. sec100:=sec100 div 10;
  1167. end;
  1168. Procedure GetTime(Var Hour,Min,Sec:Word);
  1169. {
  1170. Gets the current time, adjusted to local time
  1171. }
  1172. var
  1173. year,day,month,msec,usec : Word;
  1174. Begin
  1175. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1176. End;
  1177. Procedure GetDate(Var Year,Month,Day:Word);
  1178. {
  1179. Gets the current date, adjusted to local time
  1180. }
  1181. var
  1182. hour,minute,second,msec,usec : word;
  1183. Begin
  1184. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1185. End;
  1186. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  1187. {
  1188. Gets the current date, adjusted to local time
  1189. }
  1190. Var
  1191. usec,msec : word;
  1192. Begin
  1193. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1194. End;
  1195. {$ifndef FPUNONE}
  1196. Procedure GetLocalTime(var SystemTime: TSystemTime);
  1197. var
  1198. usecs : Word;
  1199. begin
  1200. DoGetLocalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1201. end ;
  1202. {$endif}
  1203. Procedure InitAnsi;
  1204. Var
  1205. i : longint;
  1206. begin
  1207. { Fill table entries 0 to 127 }
  1208. for i := 0 to 96 do
  1209. UpperCaseTable[i] := chr(i);
  1210. for i := 97 to 122 do
  1211. UpperCaseTable[i] := chr(i - 32);
  1212. for i := 123 to 191 do
  1213. UpperCaseTable[i] := chr(i);
  1214. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  1215. for i := 0 to 64 do
  1216. LowerCaseTable[i] := chr(i);
  1217. for i := 65 to 90 do
  1218. LowerCaseTable[i] := chr(i + 32);
  1219. for i := 91 to 191 do
  1220. LowerCaseTable[i] := chr(i);
  1221. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  1222. end;
  1223. Procedure InitInternational;
  1224. begin
  1225. InitInternationalGeneric;
  1226. InitAnsi;
  1227. end;
  1228. function SysErrorMessage(ErrorCode: Integer): String;
  1229. begin
  1230. Result:=StrError(ErrorCode);
  1231. end;
  1232. {****************************************************************************
  1233. OS utility functions
  1234. ****************************************************************************}
  1235. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1236. begin
  1237. { no need to adjust the code page of EnvVar to DefaultSystemCodePage, as only
  1238. ASCII identifiers are supported }
  1239. Result:=BaseUnix.FPGetenv(PChar(pointer(EnvVar)));
  1240. end;
  1241. Function GetEnvironmentVariableCount : Integer;
  1242. begin
  1243. Result:=FPCCountEnvVar(EnvP);
  1244. end;
  1245. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1246. begin
  1247. Result:=FPCGetEnvStrFromP(Envp,Index);
  1248. end;
  1249. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1250. var
  1251. pid : longint;
  1252. e : EOSError;
  1253. CommandLine: RawByteString;
  1254. LPath : RawByteString;
  1255. cmdline2 : ppchar;
  1256. Begin
  1257. { always surround the name of the application by quotes
  1258. so that long filenames will always be accepted. But don't
  1259. do it if there are already double quotes!
  1260. }
  1261. // Only place we still parse
  1262. cmdline2:=nil;
  1263. LPath:=Path;
  1264. UniqueString(LPath);
  1265. SetCodePage(LPath,DefaultFileSystemCodePage,true);
  1266. if Comline<>'' Then
  1267. begin
  1268. CommandLine:=ComLine;
  1269. { Make an unique copy because stringtoppchar modifies the
  1270. string, and force conversion to intended fscp }
  1271. UniqueString(CommandLine);
  1272. SetCodePage(CommandLine,DefaultFileSystemCodePage,true);
  1273. cmdline2:=StringtoPPChar(CommandLine,1);
  1274. cmdline2^:=pchar(pointer(LPath));
  1275. end
  1276. else
  1277. begin
  1278. getmem(cmdline2,2*sizeof(pchar));
  1279. cmdline2^:=pchar(LPath);
  1280. cmdline2[1]:=nil;
  1281. end;
  1282. {$ifdef USE_VFORK}
  1283. pid:=fpvFork;
  1284. {$else USE_VFORK}
  1285. pid:=fpFork;
  1286. {$endif USE_VFORK}
  1287. if pid=0 then
  1288. begin
  1289. {The child does the actual exec, and then exits}
  1290. fpexecve(pchar(pointer(LPath)),Cmdline2,envp);
  1291. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1292. fpExit(127);
  1293. end
  1294. else
  1295. if pid=-1 then {Fork failed}
  1296. begin
  1297. e:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,-1]);
  1298. e.ErrorCode:=-1;
  1299. raise e;
  1300. end;
  1301. { We're in the parent, let's wait. }
  1302. result:=WaitProcess(pid); // WaitPid and result-convert
  1303. if Comline<>'' Then
  1304. freemem(cmdline2);
  1305. if (result<0) or (result=127) then
  1306. begin
  1307. E:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,result]);
  1308. E.ErrorCode:=result;
  1309. Raise E;
  1310. end;
  1311. End;
  1312. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array Of RawByteString;Flags:TExecuteFlags=[]):integer;
  1313. var
  1314. pid : longint;
  1315. e : EOSError;
  1316. Begin
  1317. pid:=fpFork;
  1318. if pid=0 then
  1319. begin
  1320. {The child does the actual exec, and then exits}
  1321. fpexecl(Path,Comline);
  1322. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1323. fpExit(127);
  1324. end
  1325. else
  1326. if pid=-1 then {Fork failed}
  1327. begin
  1328. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1329. e.ErrorCode:=-1;
  1330. raise e;
  1331. end;
  1332. { We're in the parent, let's wait. }
  1333. result:=WaitProcess(pid); // WaitPid and result-convert
  1334. if (result<0) or (result=127) then
  1335. begin
  1336. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1337. E.ErrorCode:=result;
  1338. raise E;
  1339. end;
  1340. End;
  1341. procedure Sleep(milliseconds: Cardinal);
  1342. Var
  1343. timeout,timeoutresult : TTimespec;
  1344. res: cint;
  1345. begin
  1346. timeout.tv_sec:=milliseconds div 1000;
  1347. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  1348. repeat
  1349. res:=fpnanosleep(@timeout,@timeoutresult);
  1350. timeout:=timeoutresult;
  1351. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  1352. end;
  1353. Function GetLastOSError : Integer;
  1354. begin
  1355. Result:=fpgetErrNo;
  1356. end;
  1357. { ---------------------------------------------------------------------
  1358. Application config files
  1359. ---------------------------------------------------------------------}
  1360. {$ifdef android}
  1361. var
  1362. _HomeDir: string;
  1363. _HasPackageDataDir: boolean;
  1364. Function GetHomeDir : String;
  1365. var
  1366. h: longint;
  1367. i: longint;
  1368. begin
  1369. Result:=_HomeDir;
  1370. if Result <> '' then
  1371. exit;
  1372. if IsLibrary then
  1373. begin
  1374. // For shared library get the package name of a host Java application
  1375. h:=FileOpen('/proc/self/cmdline', fmOpenRead or fmShareDenyNone);
  1376. if h >= 0 then
  1377. begin
  1378. SetLength(Result, MAX_PATH);
  1379. SetLength(Result, FileRead(h, Result[1], Length(Result)));
  1380. SetLength(Result, strlen(PChar(Result)));
  1381. FileClose(h);
  1382. Result:='/data/data/' + Result;
  1383. _HasPackageDataDir:=DirectoryExists(Result);
  1384. if _HasPackageDataDir then
  1385. begin
  1386. Result:=Result + '/files/';
  1387. ForceDirectories(Result);
  1388. end
  1389. else
  1390. Result:=''; // No package
  1391. end;
  1392. end;
  1393. if Result = '' then
  1394. Result:='/data/local/tmp/';
  1395. _HomeDir:=Result;
  1396. end;
  1397. Function XdgConfigHome : String;
  1398. begin
  1399. Result:=GetHomeDir;
  1400. end;
  1401. {$else}
  1402. Function GetHomeDir : String;
  1403. begin
  1404. Result:=GetEnvironmentVariable('HOME');
  1405. If (Result<>'') then
  1406. Result:=IncludeTrailingPathDelimiter(Result);
  1407. end;
  1408. { Follows base-dir spec,
  1409. see [http://freedesktop.org/Standards/basedir-spec].
  1410. Always ends with PathDelim. }
  1411. Function XdgConfigHome : String;
  1412. begin
  1413. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  1414. if (Result='') then
  1415. Result:=GetHomeDir + '.config/'
  1416. else
  1417. Result:=IncludeTrailingPathDelimiter(Result);
  1418. end;
  1419. {$endif android}
  1420. Function GetAppConfigDir(Global : Boolean) : String;
  1421. begin
  1422. If Global then
  1423. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1424. else
  1425. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1426. {$ifdef android}
  1427. if _HasPackageDataDir then
  1428. exit;
  1429. {$endif android}
  1430. if VendorName<>'' then
  1431. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1432. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1433. end;
  1434. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1435. begin
  1436. If Global then
  1437. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1438. else
  1439. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1440. {$ifdef android}
  1441. if _HasPackageDataDir then
  1442. begin
  1443. Result:=Result+'config'+ConfigExtension;
  1444. exit;
  1445. end;
  1446. {$endif android}
  1447. if SubDir then
  1448. begin
  1449. if VendorName<>'' then
  1450. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1451. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1452. end;
  1453. Result:=Result+ApplicationName+ConfigExtension;
  1454. end;
  1455. {****************************************************************************
  1456. GetTempDir
  1457. ****************************************************************************}
  1458. Function GetTempDir(Global : Boolean) : String;
  1459. begin
  1460. If Assigned(OnGetTempDir) then
  1461. Result:=OnGetTempDir(Global)
  1462. else
  1463. begin
  1464. {$ifdef android}
  1465. Result:=GetHomeDir + 'tmp';
  1466. ForceDirectories(Result);
  1467. {$else}
  1468. Result:=GetEnvironmentVariable('TEMP');
  1469. If (Result='') Then
  1470. Result:=GetEnvironmentVariable('TMP');
  1471. If (Result='') Then
  1472. Result:=GetEnvironmentVariable('TMPDIR');
  1473. if (Result='') then
  1474. Result:='/tmp/'; // fallback.
  1475. {$endif android}
  1476. end;
  1477. if (Result<>'') then
  1478. Result:=IncludeTrailingPathDelimiter(Result);
  1479. end;
  1480. {****************************************************************************
  1481. GetUserDir
  1482. ****************************************************************************}
  1483. Var
  1484. TheUserDir : String;
  1485. Function GetUserDir : String;
  1486. begin
  1487. If (TheUserDir='') then
  1488. begin
  1489. {$ifdef android}
  1490. TheUserDir:=GetHomeDir;
  1491. {$else}
  1492. TheUserDir:=GetEnvironmentVariable('HOME');
  1493. {$endif android}
  1494. if (TheUserDir<>'') then
  1495. TheUserDir:=IncludeTrailingPathDelimiter(TheUserDir)
  1496. else
  1497. TheUserDir:=GetTempDir(False);
  1498. end;
  1499. Result:=TheUserDir;
  1500. end;
  1501. Procedure SysBeep;
  1502. begin
  1503. Write(#7);
  1504. Flush(Output);
  1505. end;
  1506. function GetUniversalTime(var SystemTime: TSystemTime): Boolean;
  1507. var
  1508. usecs : Word;
  1509. begin
  1510. DoGetUniversalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1511. Result:=True;
  1512. end;
  1513. function GetLocalTimeOffset: Integer;
  1514. begin
  1515. Result := -Tzseconds div 60;
  1516. end;
  1517. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  1518. var
  1519. Year, Month, Day, Hour, Minute, Second, MilliSecond: word;
  1520. UnixTime: Int64;
  1521. lTZInfo: TTZInfo;
  1522. begin
  1523. DecodeDate(DateTime, Year, Month, Day);
  1524. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  1525. UnixTime:=UniversalToEpoch(Year, Month, Day, Hour, Minute, Second);
  1526. {$if declared(GetLocalTimezone)}
  1527. GetLocalTimeOffset:=GetLocalTimezone(UnixTime,InputIsUTC,lTZInfo);
  1528. if GetLocalTimeOffset then
  1529. Offset:=-lTZInfo.seconds div 60;
  1530. {$else}
  1531. GetLocalTimeOffset:=False;
  1532. {$endif}
  1533. end;
  1534. {$ifdef android}
  1535. procedure InitAndroid;
  1536. var
  1537. dlinfo: dl_info;
  1538. s: string;
  1539. begin
  1540. FillChar(dlinfo, sizeof(dlinfo), 0);
  1541. dladdr(@InitAndroid, @dlinfo);
  1542. s:=dlinfo.dli_fname;
  1543. if s <> '' then
  1544. SetDefaultSysLogTag(ExtractFileName(s));
  1545. end;
  1546. {$endif android}
  1547. {****************************************************************************
  1548. Initialization code
  1549. ****************************************************************************}
  1550. Initialization
  1551. InitExceptions; { Initialize exceptions. OS independent }
  1552. InitInternational; { Initialize internationalization settings }
  1553. SysConfigDir:='/etc'; { Initialize system config dir }
  1554. OnBeep:=@SysBeep;
  1555. {$ifdef android}
  1556. InitAndroid;
  1557. {$endif android}
  1558. Finalization
  1559. FreeDriveStr;
  1560. FreeTerminateProcs;
  1561. DoneExceptions;
  1562. end.