sysutils.pp 46 KB

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