sysutils.pp 46 KB

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