2
0

sysutils.pp 48 KB

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