2
0

sysutils.pp 34 KB

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