sysutils.pp 45 KB

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