sysutils.pp 42 KB

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