sysutils.pp 49 KB

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