sysutils.pp 50 KB

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