sysutils.pp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  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): Longint;
  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 FileExists (Const FileName : RawByteString) : Boolean;
  521. var
  522. SystemFileName: RawByteString;
  523. begin
  524. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  525. // Don't use stat. It fails on files >2 GB.
  526. // Access obeys the same access rules, so the result should be the same.
  527. FileExists:=fpAccess(pointer(SystemFileName),F_OK)=0;
  528. end;
  529. Function DirectoryExists (Const Directory : RawByteString) : Boolean;
  530. Var
  531. Info : Stat;
  532. SystemFileName: RawByteString;
  533. begin
  534. SystemFileName:=ToSingleByteFileSystemEncodedFileName(Directory);
  535. DirectoryExists:=(fpstat(pointer(SystemFileName),Info)>=0) and fpS_ISDIR(Info.st_mode);
  536. end;
  537. Function LinuxToWinAttr (const FN : RawByteString; Const Info : Stat) : Longint;
  538. Var
  539. LinkInfo : Stat;
  540. nm : RawByteString;
  541. begin
  542. Result:=faArchive;
  543. If fpS_ISDIR(Info.st_mode) then
  544. Result:=Result or faDirectory;
  545. nm:=ExtractFileName(FN);
  546. If (Length(nm)>=2) and
  547. (nm[1]='.') and
  548. (nm[2]<>'.') then
  549. Result:=Result or faHidden;
  550. If (Info.st_Mode and S_IWUSR)=0 Then
  551. Result:=Result or faReadOnly;
  552. 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
  553. Result:=Result or faSysFile;
  554. If fpS_ISLNK(Info.st_mode) Then
  555. begin
  556. Result:=Result or faSymLink;
  557. // Windows reports if the link points to a directory.
  558. if (fpstat(pchar(FN),LinkInfo)>=0) and fpS_ISDIR(LinkInfo.st_mode) then
  559. Result := Result or faDirectory;
  560. end;
  561. end;
  562. { assumes that pattern and name have the same code page }
  563. Function FNMatch(const Pattern,Name:string):Boolean;
  564. Var
  565. LenPat,LenName : longint;
  566. function NameUtf8CodePointLen(index: longint): longint;
  567. var
  568. MaxLookAhead: longint;
  569. begin
  570. MaxLookAhead:=LenName-Index+1;
  571. { abs so that in case of an invalid sequence, we count this as one
  572. codepoint }
  573. NameUtf8CodePointLen:=abs(Utf8CodePointLen(pansichar(@Name[index]),MaxLookAhead,true));
  574. { if the sequence was incomplete, use the incomplete sequence as
  575. codepoint }
  576. if NameUtf8CodePointLen=0 then
  577. NameUtf8CodePointLen:=MaxLookAhead;
  578. end;
  579. procedure GoToLastByteOfUtf8CodePoint(var j: longint);
  580. begin
  581. inc(j,NameUtf8CodePointLen(j)-1);
  582. end;
  583. { input:
  584. i: current position in pattern (start of utf-8 code point)
  585. j: current position in name (start of utf-8 code point)
  586. update_i_j: should i and j be changed by the routine or not
  587. output:
  588. i: if update_i_j, then position of last matching part of code point in
  589. pattern, or first non-matching code point in pattern. Otherwise the
  590. same value as on input.
  591. j: if update_i_j, then position of last matching part of code point in
  592. name, or first non-matching code point in name. Otherwise the
  593. same value as on input.
  594. result: true if match, false if no match
  595. }
  596. function CompareUtf8CodePoint(var i,j: longint; update_i_j: boolean): Boolean;
  597. var
  598. bytes,
  599. new_i,
  600. new_j: longint;
  601. begin
  602. bytes:=NameUtf8CodePointLen(j);
  603. new_i:=i;
  604. new_j:=j;
  605. { ensure that a part of an UTF-8 codepoint isn't interpreted
  606. as '*' or '?' }
  607. repeat
  608. dec(bytes);
  609. Result:=
  610. (new_j<=LenName) and
  611. (new_i<=LenPat) and
  612. (Pattern[new_i]=Name[new_j]);
  613. inc(new_i);
  614. inc(new_j);
  615. until not(Result) or
  616. (bytes=0);
  617. if update_i_j then
  618. begin
  619. i:=new_i;
  620. j:=new_j;
  621. end;
  622. end;
  623. Function DoFNMatch(i,j:longint):Boolean;
  624. Var
  625. UTF8, Found : boolean;
  626. Begin
  627. Found:=true;
  628. { ensure that we don't skip partial characters in UTF-8-encoded strings }
  629. UTF8:=StringCodePage(Name)=CP_UTF8;
  630. While Found and (i<=LenPat) Do
  631. Begin
  632. Case Pattern[i] of
  633. '?' :
  634. begin
  635. Found:=(j<=LenName);
  636. if UTF8 then
  637. GoToLastByteOfUtf8CodePoint(j);
  638. end;
  639. '*' : Begin
  640. {find the next character in pattern, different of ? and *}
  641. while Found do
  642. begin
  643. inc(i);
  644. if i>LenPat then
  645. Break;
  646. case Pattern[i] of
  647. '*' : ;
  648. '?' : begin
  649. if j>LenName then
  650. begin
  651. DoFNMatch:=false;
  652. Exit;
  653. end;
  654. if UTF8 then
  655. GoToLastByteOfUtf8CodePoint(j);
  656. inc(j);
  657. end;
  658. else
  659. Found:=false;
  660. end;
  661. end;
  662. Assert((i>LenPat) or ( (Pattern[i]<>'*') and (Pattern[i]<>'?') ));
  663. { Now, find in name the character which i points to, if the * or
  664. ? wasn't the last character in the pattern, else, use up all
  665. the chars in name }
  666. Found:=false;
  667. if (i<=LenPat) then
  668. begin
  669. repeat
  670. {find a letter (not only first !) which maches pattern[i]}
  671. if UTF8 then
  672. begin
  673. while (j<=LenName) and
  674. ((name[j]<>pattern[i]) or
  675. not CompareUtf8CodePoint(i,j,false)) do
  676. begin
  677. GoToLastByteOfUtf8CodePoint(j);
  678. inc(j);
  679. end;
  680. end
  681. else
  682. begin
  683. while (j<=LenName) and (name[j]<>pattern[i]) do
  684. inc (j);
  685. end;
  686. if (j<LenName) then
  687. begin
  688. { while positions i/j have already been checked, in
  689. case of UTF-8 we have to ensure that we don't split
  690. a code point. Otherwise we can skip over comparing
  691. the same characters twice }
  692. if DoFnMatch(i+ord(not UTF8),j+ord(not UTF8)) then
  693. begin
  694. i:=LenPat;
  695. j:=LenName;{we can stop}
  696. Found:=true;
  697. Break;
  698. end
  699. { We didn't find one, need to look further }
  700. else
  701. begin
  702. if UTF8 then
  703. GoToLastByteOfUtf8CodePoint(j);
  704. inc(j);
  705. end;
  706. end
  707. else if j=LenName then
  708. begin
  709. Found:=true;
  710. Break;
  711. end;
  712. { This 'until' condition must be j>LenName, not j>=LenName.
  713. That's because when we 'need to look further' and
  714. j = LenName then loop must not terminate. }
  715. until (j>LenName);
  716. end
  717. else
  718. begin
  719. j:=LenName;{we can stop}
  720. Found:=true;
  721. end;
  722. end;
  723. #128..#255:
  724. begin
  725. Found:=(j<=LenName) and (pattern[i]=name[j]);
  726. if Found and UTF8 then
  727. begin
  728. { ensure that a part of an UTF-8 codepoint isn't matched with
  729. '*' or '?' }
  730. Found:=CompareUtf8CodePoint(i,j,true);
  731. { at this point, either Found is false (and we'll stop), or
  732. both pattern[i] and name[j] are the end of the current code
  733. point and equal }
  734. end
  735. end
  736. else {not a wildcard character in pattern}
  737. Found:=(j<=LenName) and (pattern[i]=name[j]);
  738. end;
  739. inc(i);
  740. inc(j);
  741. end;
  742. DoFnMatch:=Found and (j>LenName);
  743. end;
  744. Begin {start FNMatch}
  745. LenPat:=Length(Pattern);
  746. LenName:=Length(Name);
  747. FNMatch:=DoFNMatch(1,1);
  748. End;
  749. Type
  750. TUnixFindData = Record
  751. NamePos : LongInt; {to track which search this is}
  752. DirPtr : Pointer; {directory pointer for reading directory}
  753. SearchSpec : RawbyteString;
  754. SearchType : Byte; {0=normal, 1=open will close, 2=only 1 file}
  755. SearchAttr : Longint; {attribute we are searching for}
  756. End;
  757. PUnixFindData = ^TUnixFindData;
  758. Procedure InternalFindClose(var Handle: Pointer);
  759. var
  760. D: PUnixFindData absolute Handle;
  761. begin
  762. If D=Nil then
  763. Exit;
  764. if D^.SearchType=0 then
  765. begin
  766. if D^.dirptr<>nil then
  767. fpclosedir(pdir(D^.dirptr)^);
  768. end;
  769. Dispose(D);
  770. D:=nil;
  771. end;
  772. Function FindGetFileInfo(const s: RawByteString; var f: TAbstractSearchRec; var Name: RawByteString):boolean;
  773. Var
  774. st : baseunix.stat;
  775. WinAttr : longint;
  776. begin
  777. if Assigned(f.FindHandle) and ( (PUnixFindData(F.FindHandle)^.searchattr and faSymlink) > 0) then
  778. FindGetFileInfo:=(fplstat(pointer(s),st)=0)
  779. else
  780. FindGetFileInfo:=(fpstat(pointer(s),st)=0);
  781. if not FindGetFileInfo then
  782. exit;
  783. WinAttr:=LinuxToWinAttr(s,st);
  784. FindGetFileInfo:=(WinAttr and Not(PUnixFindData(f.FindHandle)^.searchattr))=0;
  785. if FindGetFileInfo then
  786. begin
  787. Name:=ExtractFileName(s);
  788. f.Attr:=WinAttr;
  789. f.Size:=st.st_Size;
  790. f.Mode:=st.st_mode;
  791. f.Time:=st.st_mtime;
  792. FindGetFileInfo:=true;
  793. end;
  794. end;
  795. // Returns the FOUND filename. Error code <> 0 if no file found
  796. Function InternalFindNext (var Rslt : TAbstractSearchRec; var Name : RawByteString) : Longint;
  797. Var
  798. DirName : RawByteString;
  799. FName,
  800. SName : RawBytestring;
  801. Found,
  802. Finished : boolean;
  803. p : pdirent;
  804. UnixFindData : PUnixFindData;
  805. Begin
  806. Result:=-1;
  807. UnixFindData:=PUnixFindData(Rslt.FindHandle);
  808. { SearchSpec='' means that there were no wild cards, so only one file to
  809. find.
  810. }
  811. If (UnixFindData=Nil) or (UnixFindData^.SearchSpec='') then
  812. exit;
  813. if (UnixFindData^.SearchType=0) and
  814. (UnixFindData^.Dirptr=nil) then
  815. begin
  816. If UnixFindData^.NamePos = 0 Then
  817. DirName:='./'
  818. Else
  819. DirName:=Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos);
  820. UnixFindData^.DirPtr := fpopendir(Pchar(DirName));
  821. end;
  822. SName:=Copy(UnixFindData^.SearchSpec,UnixFindData^.NamePos+1,Length(UnixFindData^.SearchSpec));
  823. Found:=False;
  824. Finished:=(UnixFindData^.dirptr=nil);
  825. While Not Finished Do
  826. Begin
  827. p:=fpreaddir(pdir(UnixFindData^.dirptr)^);
  828. if p=nil then
  829. FName:=''
  830. else
  831. FName:=p^.d_name;
  832. If FName='' Then
  833. Finished:=True
  834. Else
  835. Begin
  836. SetCodePage(FName,DefaultFileSystemCodePage,false);
  837. If FNMatch(SName,FName) Then
  838. Begin
  839. Found:=FindGetFileInfo(Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos)+FName,Rslt,Name);
  840. if Found then
  841. begin
  842. Result:=0;
  843. exit;
  844. end;
  845. End;
  846. End;
  847. End;
  848. End;
  849. Function InternalFindFirst (Const Path : RawByteString; Attr : Longint; out Rslt : TAbstractSearchRec; var Name: RawByteString) : Longint;
  850. {
  851. opens dir and calls FindNext if needed.
  852. }
  853. var
  854. UnixFindData : PUnixFindData;
  855. Begin
  856. Result:=-1;
  857. { this is safe even though Rslt actually contains a refcounted field, because
  858. it is declared as "out" and hence has already been initialised }
  859. fillchar(Rslt,sizeof(Rslt),0);
  860. if Path='' then
  861. exit;
  862. { Allocate UnixFindData (we always need it, for the search attributes) }
  863. New(UnixFindData);
  864. FillChar(UnixFindData^,sizeof(UnixFindData^),0);
  865. Rslt.FindHandle:=UnixFindData;
  866. {We always also search for readonly and archive, regardless of Attr:}
  867. UnixFindData^.SearchAttr := Attr or faarchive or fareadonly;
  868. {Wildcards?}
  869. if (Pos('?',Path)=0) and (Pos('*',Path)=0) then
  870. begin
  871. if FindGetFileInfo(ToSingleByteFileSystemEncodedFileName(Path),Rslt,Name) then
  872. Result:=0;
  873. end
  874. else
  875. begin
  876. {Create Info}
  877. UnixFindData^.SearchSpec := ToSingleByteFileSystemEncodedFileName(Path);
  878. UnixFindData^.NamePos := Length(UnixFindData^.SearchSpec);
  879. while (UnixFindData^.NamePos>0) and (UnixFindData^.SearchSpec[UnixFindData^.NamePos]<>'/') do
  880. dec(UnixFindData^.NamePos);
  881. Result:=InternalFindNext(Rslt,Name);
  882. end;
  883. If (Result<>0) then
  884. InternalFindClose(Rslt.FindHandle);
  885. End;
  886. Function FileGetDate (Handle : Longint) : Longint;
  887. Var Info : Stat;
  888. begin
  889. If (fpFStat(Handle,Info))<0 then
  890. Result:=-1
  891. else
  892. Result:=Info.st_Mtime;
  893. end;
  894. Function FileSetDate (Handle,Age : Longint) : Longint;
  895. begin
  896. // Impossible under Linux from FileHandle !!
  897. FileSetDate:=-1;
  898. end;
  899. Function FileGetAttr (Const FileName : RawByteString) : Longint;
  900. Var
  901. SystemFileName: RawByteString;
  902. Info : Stat;
  903. res : Integer;
  904. begin
  905. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  906. res:=FpLStat(pointer(SystemFileName),Info);
  907. if res<0 then
  908. res:=FpStat(pointer(SystemFileName),Info);
  909. if res<0 then
  910. Result:=-1
  911. Else
  912. Result:=LinuxToWinAttr(SystemFileName,Info);
  913. end;
  914. Function FileSetAttr (Const Filename : RawByteString; Attr: longint) : Longint;
  915. begin
  916. Result:=-1;
  917. end;
  918. Function DeleteFile (Const FileName : RawByteString) : Boolean;
  919. var
  920. SystemFileName: RawByteString;
  921. begin
  922. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  923. Result:=fpUnLink (pchar(SystemFileName))>=0;
  924. end;
  925. Function RenameFile (Const OldName, NewName : RawByteString) : Boolean;
  926. var
  927. SystemOldName, SystemNewName: RawByteString;
  928. begin
  929. SystemOldName:=ToSingleByteFileSystemEncodedFileName(OldName);
  930. SystemNewName:=ToSingleByteFileSystemEncodedFileName(NewName);
  931. RenameFile:=BaseUnix.FpRename(pointer(SystemOldName),pointer(SystemNewName))>=0;
  932. end;
  933. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  934. var
  935. SystemFileName: RawByteString;
  936. begin
  937. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  938. Result:=fpAccess(PChar(SystemFileName),W_OK)<>0;
  939. end;
  940. Function FileSetDate (Const FileName : RawByteString; Age : Longint) : Longint;
  941. var
  942. SystemFileName: RawByteString;
  943. t: TUTimBuf;
  944. begin
  945. SystemFileName:=ToSingleByteFileSystemEncodedFileName(FileName);
  946. Result:=0;
  947. t.actime:= Age;
  948. t.modtime:=Age;
  949. if fputime(PChar(SystemFileName), @t) = -1 then
  950. Result:=fpgeterrno;
  951. end;
  952. {****************************************************************************
  953. Disk Functions
  954. ****************************************************************************}
  955. {
  956. The Diskfree and Disksize functions need a file on the specified drive, since this
  957. is required for the fpstatfs system call.
  958. These filenames are set in drivestr[0..26], and have been preset to :
  959. 0 - '.' (default drive - hence current dir is ok.)
  960. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  961. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  962. 3 - '/' (C: equivalent of dos is the root partition)
  963. 4..26 (can be set by you're own applications)
  964. ! Use AddDisk() to Add new drives !
  965. They both return -1 when a failure occurs.
  966. }
  967. Const
  968. FixDriveStr : array[0..3] of pchar=(
  969. '.',
  970. '/fd0/.',
  971. '/fd1/.',
  972. '/.'
  973. );
  974. var
  975. Drives : byte = 4;
  976. DriveStr : array[4..26] of pchar;
  977. Function AddDisk(const path:string) : Byte;
  978. begin
  979. if not (DriveStr[Drives]=nil) then
  980. FreeMem(DriveStr[Drives]);
  981. GetMem(DriveStr[Drives],length(Path)+1);
  982. StrPCopy(DriveStr[Drives],path);
  983. Result:=Drives;
  984. inc(Drives);
  985. if Drives>26 then
  986. Drives:=4;
  987. end;
  988. Function DiskFree(Drive: Byte): int64;
  989. var
  990. fs : tstatfs;
  991. Begin
  992. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (fpstatfs(StrPas(fixdrivestr[drive]),@fs)<>-1)) or
  993. ((Drive in [Low(DriveStr)..High(DriveStr)]) and (not (drivestr[Drive]=nil)) and (fpstatfs(StrPas(drivestr[drive]),@fs)<>-1)) then
  994. Diskfree:=int64(fs.bavail)*int64(fs.bsize)
  995. else
  996. Diskfree:=-1;
  997. End;
  998. Function DiskSize(Drive: Byte): int64;
  999. var
  1000. fs : tstatfs;
  1001. Begin
  1002. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (fpstatfs(StrPas(fixdrivestr[drive]),@fs)<>-1)) or
  1003. ((Drive in [Low(DriveStr)..High(DriveStr)]) and (not (drivestr[Drive]=nil)) and (fpstatfs(StrPas(drivestr[drive]),@fs)<>-1)) then
  1004. DiskSize:=int64(fs.blocks)*int64(fs.bsize)
  1005. else
  1006. DiskSize:=-1;
  1007. End;
  1008. Procedure FreeDriveStr;
  1009. var
  1010. i: longint;
  1011. begin
  1012. for i:=low(drivestr) to high(drivestr) do
  1013. if assigned(drivestr[i]) then
  1014. begin
  1015. freemem(drivestr[i]);
  1016. drivestr[i]:=nil;
  1017. end;
  1018. end;
  1019. {****************************************************************************
  1020. Misc Functions
  1021. ****************************************************************************}
  1022. {****************************************************************************
  1023. Locale Functions
  1024. ****************************************************************************}
  1025. Function GetEpochTime: cint;
  1026. {
  1027. Get the number of seconds since 00:00, January 1 1970, GMT
  1028. the time NOT corrected any way
  1029. }
  1030. begin
  1031. GetEpochTime:=fptime;
  1032. end;
  1033. // Now, adjusted to local time.
  1034. Procedure DoGetLocalDateTime(var year, month, day, hour, min, sec, msec, usec : word);
  1035. var
  1036. tz:timeval;
  1037. begin
  1038. fpgettimeofday(@tz,nil);
  1039. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  1040. msec:=tz.tv_usec div 1000;
  1041. usec:=tz.tv_usec mod 1000;
  1042. end;
  1043. procedure GetTime(var hour,min,sec,msec,usec:word);
  1044. Var
  1045. year,day,month:Word;
  1046. begin
  1047. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1048. end;
  1049. procedure GetTime(var hour,min,sec,sec100:word);
  1050. {
  1051. Gets the current time, adjusted to local time
  1052. }
  1053. var
  1054. year,day,month,usec : word;
  1055. begin
  1056. DoGetLocalDateTime(year,month,day,hour,min,sec,sec100,usec);
  1057. sec100:=sec100 div 10;
  1058. end;
  1059. Procedure GetTime(Var Hour,Min,Sec:Word);
  1060. {
  1061. Gets the current time, adjusted to local time
  1062. }
  1063. var
  1064. year,day,month,msec,usec : Word;
  1065. Begin
  1066. DoGetLocalDateTime(year,month,day,hour,min,sec,msec,usec);
  1067. End;
  1068. Procedure GetDate(Var Year,Month,Day:Word);
  1069. {
  1070. Gets the current date, adjusted to local time
  1071. }
  1072. var
  1073. hour,minute,second,msec,usec : word;
  1074. Begin
  1075. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1076. End;
  1077. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  1078. {
  1079. Gets the current date, adjusted to local time
  1080. }
  1081. Var
  1082. usec,msec : word;
  1083. Begin
  1084. DoGetLocalDateTime(year,month,day,hour,minute,second,msec,usec);
  1085. End;
  1086. {$ifndef FPUNONE}
  1087. Procedure GetLocalTime(var SystemTime: TSystemTime);
  1088. var
  1089. usecs : Word;
  1090. begin
  1091. DoGetLocalDateTime(SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  1092. end ;
  1093. {$endif}
  1094. Procedure InitAnsi;
  1095. Var
  1096. i : longint;
  1097. begin
  1098. { Fill table entries 0 to 127 }
  1099. for i := 0 to 96 do
  1100. UpperCaseTable[i] := chr(i);
  1101. for i := 97 to 122 do
  1102. UpperCaseTable[i] := chr(i - 32);
  1103. for i := 123 to 191 do
  1104. UpperCaseTable[i] := chr(i);
  1105. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  1106. for i := 0 to 64 do
  1107. LowerCaseTable[i] := chr(i);
  1108. for i := 65 to 90 do
  1109. LowerCaseTable[i] := chr(i + 32);
  1110. for i := 91 to 191 do
  1111. LowerCaseTable[i] := chr(i);
  1112. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  1113. end;
  1114. Procedure InitInternational;
  1115. begin
  1116. InitInternationalGeneric;
  1117. InitAnsi;
  1118. end;
  1119. function SysErrorMessage(ErrorCode: Integer): String;
  1120. begin
  1121. Result:=StrError(ErrorCode);
  1122. end;
  1123. {****************************************************************************
  1124. OS utility functions
  1125. ****************************************************************************}
  1126. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  1127. begin
  1128. { no need to adjust the code page of EnvVar to DefaultSystemCodePage, as only
  1129. ASCII identifiers are supported }
  1130. Result:=BaseUnix.FPGetenv(PChar(pointer(EnvVar)));
  1131. end;
  1132. Function GetEnvironmentVariableCount : Integer;
  1133. begin
  1134. Result:=FPCCountEnvVar(EnvP);
  1135. end;
  1136. Function GetEnvironmentString(Index : Integer) : {$ifdef FPC_RTL_UNICODE}UnicodeString{$else}AnsiString{$endif};
  1137. begin
  1138. Result:=FPCGetEnvStrFromP(Envp,Index);
  1139. end;
  1140. function ExecuteProcess(Const Path: RawByteString; Const ComLine: RawByteString;Flags:TExecuteFlags=[]):integer;
  1141. var
  1142. pid : longint;
  1143. e : EOSError;
  1144. CommandLine: RawByteString;
  1145. LPath : RawByteString;
  1146. cmdline2 : ppchar;
  1147. Begin
  1148. { always surround the name of the application by quotes
  1149. so that long filenames will always be accepted. But don't
  1150. do it if there are already double quotes!
  1151. }
  1152. // Only place we still parse
  1153. cmdline2:=nil;
  1154. LPath:=Path;
  1155. UniqueString(LPath);
  1156. SetCodePage(LPath,DefaultFileSystemCodePage,true);
  1157. if Comline<>'' Then
  1158. begin
  1159. CommandLine:=ComLine;
  1160. { Make an unique copy because stringtoppchar modifies the
  1161. string, and force conversion to intended fscp }
  1162. UniqueString(CommandLine);
  1163. SetCodePage(CommandLine,DefaultFileSystemCodePage,true);
  1164. cmdline2:=StringtoPPChar(CommandLine,1);
  1165. cmdline2^:=pchar(pointer(LPath));
  1166. end
  1167. else
  1168. begin
  1169. getmem(cmdline2,2*sizeof(pchar));
  1170. cmdline2^:=pchar(LPath);
  1171. cmdline2[1]:=nil;
  1172. end;
  1173. {$ifdef USE_VFORK}
  1174. pid:=fpvFork;
  1175. {$else USE_VFORK}
  1176. pid:=fpFork;
  1177. {$endif USE_VFORK}
  1178. if pid=0 then
  1179. begin
  1180. {The child does the actual exec, and then exits}
  1181. fpexecv(pchar(pointer(LPath)),Cmdline2);
  1182. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1183. fpExit(127);
  1184. end
  1185. else
  1186. if pid=-1 then {Fork failed}
  1187. begin
  1188. e:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,-1]);
  1189. e.ErrorCode:=-1;
  1190. raise e;
  1191. end;
  1192. { We're in the parent, let's wait. }
  1193. result:=WaitProcess(pid); // WaitPid and result-convert
  1194. if Comline<>'' Then
  1195. freemem(cmdline2);
  1196. if (result<0) or (result=127) then
  1197. begin
  1198. E:=EOSError.CreateFmt(SExecuteProcessFailed,[LPath,result]);
  1199. E.ErrorCode:=result;
  1200. Raise E;
  1201. end;
  1202. End;
  1203. function ExecuteProcess(Const Path: RawByteString; Const ComLine: Array Of RawByteString;Flags:TExecuteFlags=[]):integer;
  1204. var
  1205. pid : longint;
  1206. e : EOSError;
  1207. Begin
  1208. pid:=fpFork;
  1209. if pid=0 then
  1210. begin
  1211. {The child does the actual exec, and then exits}
  1212. fpexecl(Path,Comline);
  1213. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1214. fpExit(127);
  1215. end
  1216. else
  1217. if pid=-1 then {Fork failed}
  1218. begin
  1219. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1220. e.ErrorCode:=-1;
  1221. raise e;
  1222. end;
  1223. { We're in the parent, let's wait. }
  1224. result:=WaitProcess(pid); // WaitPid and result-convert
  1225. if (result<0) or (result=127) then
  1226. begin
  1227. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1228. E.ErrorCode:=result;
  1229. raise E;
  1230. end;
  1231. End;
  1232. procedure Sleep(milliseconds: Cardinal);
  1233. Var
  1234. timeout,timeoutresult : TTimespec;
  1235. res: cint;
  1236. begin
  1237. timeout.tv_sec:=milliseconds div 1000;
  1238. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  1239. repeat
  1240. res:=fpnanosleep(@timeout,@timeoutresult);
  1241. timeout:=timeoutresult;
  1242. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  1243. end;
  1244. Function GetLastOSError : Integer;
  1245. begin
  1246. Result:=fpgetErrNo;
  1247. end;
  1248. { ---------------------------------------------------------------------
  1249. Application config files
  1250. ---------------------------------------------------------------------}
  1251. {$ifdef android}
  1252. var
  1253. _HomeDir: string;
  1254. _HasPackageDataDir: boolean;
  1255. Function GetHomeDir : String;
  1256. var
  1257. h: longint;
  1258. i: longint;
  1259. begin
  1260. Result:=_HomeDir;
  1261. if Result <> '' then
  1262. exit;
  1263. if IsLibrary then
  1264. begin
  1265. // For shared library get the package name of a host Java application
  1266. h:=FileOpen('/proc/self/cmdline', fmOpenRead or fmShareDenyNone);
  1267. if h >= 0 then
  1268. begin
  1269. SetLength(Result, MAX_PATH);
  1270. SetLength(Result, FileRead(h, Result[1], Length(Result)));
  1271. SetLength(Result, strlen(PChar(Result)));
  1272. FileClose(h);
  1273. Result:='/data/data/' + Result;
  1274. _HasPackageDataDir:=DirectoryExists(Result);
  1275. if _HasPackageDataDir then
  1276. begin
  1277. Result:=Result + '/files/';
  1278. ForceDirectories(Result);
  1279. end
  1280. else
  1281. Result:=''; // No package
  1282. end;
  1283. end;
  1284. if Result = '' then
  1285. Result:='/data/local/tmp/';
  1286. _HomeDir:=Result;
  1287. end;
  1288. Function XdgConfigHome : String;
  1289. begin
  1290. Result:=GetHomeDir;
  1291. end;
  1292. {$else}
  1293. Function GetHomeDir : String;
  1294. begin
  1295. Result:=GetEnvironmentVariable('HOME');
  1296. If (Result<>'') then
  1297. Result:=IncludeTrailingPathDelimiter(Result);
  1298. end;
  1299. { Follows base-dir spec,
  1300. see [http://freedesktop.org/Standards/basedir-spec].
  1301. Always ends with PathDelim. }
  1302. Function XdgConfigHome : String;
  1303. begin
  1304. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  1305. if (Result='') then
  1306. Result:=GetHomeDir + '.config/'
  1307. else
  1308. Result:=IncludeTrailingPathDelimiter(Result);
  1309. end;
  1310. {$endif android}
  1311. Function GetAppConfigDir(Global : Boolean) : String;
  1312. begin
  1313. If Global then
  1314. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1315. else
  1316. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1317. {$ifdef android}
  1318. if _HasPackageDataDir then
  1319. exit;
  1320. {$endif android}
  1321. if VendorName<>'' then
  1322. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1323. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1324. end;
  1325. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1326. begin
  1327. If Global then
  1328. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1329. else
  1330. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1331. {$ifdef android}
  1332. if _HasPackageDataDir then
  1333. begin
  1334. Result:=Result+'config'+ConfigExtension;
  1335. exit;
  1336. end;
  1337. {$endif android}
  1338. if SubDir then
  1339. begin
  1340. if VendorName<>'' then
  1341. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1342. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1343. end;
  1344. Result:=Result+ApplicationName+ConfigExtension;
  1345. end;
  1346. {****************************************************************************
  1347. GetTempDir
  1348. ****************************************************************************}
  1349. Function GetTempDir(Global : Boolean) : String;
  1350. begin
  1351. If Assigned(OnGetTempDir) then
  1352. Result:=OnGetTempDir(Global)
  1353. else
  1354. begin
  1355. {$ifdef android}
  1356. Result:=GetHomeDir + 'tmp';
  1357. ForceDirectories(Result);
  1358. {$else}
  1359. Result:=GetEnvironmentVariable('TEMP');
  1360. If (Result='') Then
  1361. Result:=GetEnvironmentVariable('TMP');
  1362. If (Result='') Then
  1363. Result:=GetEnvironmentVariable('TMPDIR');
  1364. if (Result='') then
  1365. Result:='/tmp/'; // fallback.
  1366. {$endif android}
  1367. end;
  1368. if (Result<>'') then
  1369. Result:=IncludeTrailingPathDelimiter(Result);
  1370. end;
  1371. {****************************************************************************
  1372. GetUserDir
  1373. ****************************************************************************}
  1374. Var
  1375. TheUserDir : String;
  1376. Function GetUserDir : String;
  1377. begin
  1378. If (TheUserDir='') then
  1379. begin
  1380. {$ifdef android}
  1381. TheUserDir:=GetHomeDir;
  1382. {$else}
  1383. TheUserDir:=GetEnvironmentVariable('HOME');
  1384. {$endif android}
  1385. if (TheUserDir<>'') then
  1386. TheUserDir:=IncludeTrailingPathDelimiter(TheUserDir)
  1387. else
  1388. TheUserDir:=GetTempDir(False);
  1389. end;
  1390. Result:=TheUserDir;
  1391. end;
  1392. Procedure SysBeep;
  1393. begin
  1394. Write(#7);
  1395. Flush(Output);
  1396. end;
  1397. function GetLocalTimeOffset: Integer;
  1398. begin
  1399. Result := -Tzseconds div 60;
  1400. end;
  1401. {$ifdef android}
  1402. procedure InitAndroid;
  1403. var
  1404. dlinfo: dl_info;
  1405. s: string;
  1406. begin
  1407. FillChar(dlinfo, sizeof(dlinfo), 0);
  1408. dladdr(@InitAndroid, @dlinfo);
  1409. s:=dlinfo.dli_fname;
  1410. if s <> '' then
  1411. SetDefaultSysLogTag(ExtractFileName(s));
  1412. end;
  1413. {$endif android}
  1414. {****************************************************************************
  1415. Initialization code
  1416. ****************************************************************************}
  1417. Initialization
  1418. InitExceptions; { Initialize exceptions. OS independent }
  1419. InitInternational; { Initialize internationalization settings }
  1420. SysConfigDir:='/etc'; { Initialize system config dir }
  1421. OnBeep:=@SysBeep;
  1422. {$ifdef android}
  1423. InitAndroid;
  1424. {$endif android}
  1425. Finalization
  1426. FreeDriveStr;
  1427. DoneExceptions;
  1428. end.