sysutils.pp 45 KB

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