sysutils.pp 51 KB

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