sysutils.pp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  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 (FN : Pchar; Const Info : Stat) : Longint;
  453. Var
  454. FNL : String;
  455. LinkInfo : Stat;
  456. begin
  457. Result:=faArchive;
  458. If fpS_ISDIR(Info.st_mode) then
  459. Result:=Result or faDirectory;
  460. If (FN[0]='.') and (not (FN[1] in [#0,'.'])) then
  461. Result:=Result or faHidden;
  462. If (Info.st_Mode and S_IWUSR)=0 Then
  463. Result:=Result or faReadOnly;
  464. 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
  465. Result:=Result or faSysFile;
  466. If fpS_ISLNK(Info.st_mode) Then
  467. begin
  468. Result:=Result or faSymLink;
  469. // Windows reports if the link points to a directory.
  470. FNL:=StrPas(FN);
  471. if (fpstat(FNL,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. Var
  563. CurrSearchNum : LongInt;
  564. Procedure FindClose(Var f: TSearchRec);
  565. var
  566. UnixFindData : PUnixFindData;
  567. Begin
  568. UnixFindData:=PUnixFindData(f.FindHandle);
  569. If (UnixFindData=Nil) then
  570. Exit;
  571. if UnixFindData^.SearchType=0 then
  572. begin
  573. if UnixFindData^.dirptr<>nil then
  574. fpclosedir(pdir(UnixFindData^.dirptr)^);
  575. end;
  576. Dispose(UnixFindData);
  577. f.FindHandle:=nil;
  578. End;
  579. Function FindGetFileInfo(const s:string;var f:TSearchRec):boolean;
  580. var
  581. st : baseunix.stat;
  582. WinAttr : longint;
  583. ResolvedPath : string;
  584. LinkLen : ssize_t;
  585. begin
  586. FindGetFileInfo:=false;
  587. If Assigned(F.FindHandle) and ((((PUnixFindData(f.FindHandle)^.searchattr)) and faSymlink) > 0) then
  588. FindGetFileInfo:=(fplstat(pointer(s),st)=0)
  589. else
  590. FindGetFileInfo:=(fpstat(pointer(s),st)=0);
  591. If not FindGetFileInfo then
  592. exit;
  593. WinAttr:=LinuxToWinAttr(PChar(pointer(s)),st);
  594. If ((WinAttr and Not(PUnixFindData(f.FindHandle)^.searchattr))=0) Then
  595. Begin
  596. f.Name:=ExtractFileName(s);
  597. f.Attr:=WinAttr;
  598. f.Size:=st.st_Size;
  599. f.Mode:=st.st_mode;
  600. {$ifndef FPUNONE}
  601. f.Time:=UnixToWinAge(st.st_mtime);
  602. {$endif}
  603. FindGetFileInfo:=true;
  604. End
  605. else
  606. FindGetFileInfo:=false;
  607. end;
  608. Function FindNext (Var Rslt : TSearchRec) : Longint;
  609. {
  610. re-opens dir if not already in array and calls FindGetFileInfo
  611. }
  612. Var
  613. DirName : String;
  614. FName,
  615. SName : string;
  616. Found,
  617. Finished : boolean;
  618. p : pdirent;
  619. UnixFindData : PUnixFindData;
  620. Begin
  621. Result:=-1;
  622. UnixFindData:=PUnixFindData(Rslt.FindHandle);
  623. { SearchSpec='' means that there were no wild cards, so only one file to
  624. find.
  625. }
  626. If (UnixFindData=Nil) then
  627. exit;
  628. if UnixFindData^.SearchSpec='' then
  629. exit;
  630. if (UnixFindData^.SearchType=0) and
  631. (UnixFindData^.Dirptr=nil) then
  632. begin
  633. If UnixFindData^.NamePos = 0 Then
  634. DirName:='./'
  635. Else
  636. DirName:=Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos);
  637. UnixFindData^.DirPtr := fpopendir(Pchar(pointer(DirName)));
  638. end;
  639. SName:=Copy(UnixFindData^.SearchSpec,UnixFindData^.NamePos+1,Length(UnixFindData^.SearchSpec));
  640. Found:=False;
  641. Finished:=(UnixFindData^.dirptr=nil);
  642. While Not Finished Do
  643. Begin
  644. p:=fpreaddir(pdir(UnixFindData^.dirptr)^);
  645. if p=nil then
  646. FName:=''
  647. else
  648. FName:=p^.d_name;
  649. If FName='' Then
  650. Finished:=True
  651. Else
  652. Begin
  653. If FNMatch(SName,FName) Then
  654. Begin
  655. Found:=FindGetFileInfo(Copy(UnixFindData^.SearchSpec,1,UnixFindData^.NamePos)+FName,Rslt);
  656. if Found then
  657. begin
  658. Result:=0;
  659. exit;
  660. end;
  661. End;
  662. End;
  663. End;
  664. End;
  665. Function FindFirst (Const Path : String; Attr : Longint; out Rslt : TSearchRec) : Longint;
  666. {
  667. opens dir and calls FindNext if needed.
  668. }
  669. var
  670. UnixFindData : PUnixFindData;
  671. Begin
  672. Result:=-1;
  673. fillchar(Rslt,sizeof(Rslt),0);
  674. if Path='' then
  675. exit;
  676. { Allocate UnixFindData (we always need it, for the search attributes) }
  677. New(UnixFindData);
  678. FillChar(UnixFindData^,sizeof(UnixFindData^),0);
  679. Rslt.FindHandle:=UnixFindData;
  680. {We always also search for readonly and archive, regardless of Attr:}
  681. UnixFindData^.SearchAttr := Attr or faarchive or fareadonly;
  682. {Wildcards?}
  683. if (Pos('?',Path)=0) and (Pos('*',Path)=0) then
  684. begin
  685. if FindGetFileInfo(Path,Rslt) then
  686. Result:=0;
  687. end
  688. else
  689. begin
  690. {Create Info}
  691. UnixFindData^.SearchSpec := Path;
  692. UnixFindData^.NamePos := Length(UnixFindData^.SearchSpec);
  693. while (UnixFindData^.NamePos>0) and (UnixFindData^.SearchSpec[UnixFindData^.NamePos]<>'/') do
  694. dec(UnixFindData^.NamePos);
  695. Result:=FindNext(Rslt);
  696. end;
  697. If (Result<>0) then
  698. FindClose(Rslt);
  699. End;
  700. Function FileGetDate (Handle : Longint) : Longint;
  701. Var Info : Stat;
  702. begin
  703. If (fpFStat(Handle,Info))<0 then
  704. Result:=-1
  705. else
  706. Result:=Info.st_Mtime;
  707. end;
  708. Function FileSetDate (Handle,Age : Longint) : Longint;
  709. begin
  710. // Impossible under Linux from FileHandle !!
  711. FileSetDate:=-1;
  712. end;
  713. Function FileGetAttr (Const FileName : String) : Longint;
  714. Var Info : Stat;
  715. begin
  716. If FpStat (pointer(FileName),Info)<0 then
  717. Result:=-1
  718. Else
  719. Result:=LinuxToWinAttr(Pchar(ExtractFileName(FileName)),Info);
  720. end;
  721. Function FileSetAttr (Const Filename : String; Attr: longint) : Longint;
  722. begin
  723. Result:=-1;
  724. end;
  725. Function DeleteFile (Const FileName : String) : Boolean;
  726. begin
  727. Result:=fpUnLink (pointer(FileName))>=0;
  728. end;
  729. Function RenameFile (Const OldName, NewName : String) : Boolean;
  730. begin
  731. RenameFile:=BaseUnix.FpRename(pointer(OldNAme),pointer(NewName))>=0;
  732. end;
  733. Function FileIsReadOnly(const FileName: String): Boolean;
  734. begin
  735. Result := fpAccess(PChar(pointer(FileName)),W_OK)<>0;
  736. end;
  737. Function FileSetDate (Const FileName : String;Age : Longint) : Longint;
  738. var
  739. t: TUTimBuf;
  740. begin
  741. Result := 0;
  742. t.actime := Age;
  743. t.modtime := Age;
  744. if fputime(PChar(pointer(FileName)), @t) = -1 then
  745. Result := fpgeterrno;
  746. end;
  747. {****************************************************************************
  748. Disk Functions
  749. ****************************************************************************}
  750. {
  751. The Diskfree and Disksize functions need a file on the specified drive, since this
  752. is required for the statfs system call.
  753. These filenames are set in drivestr[0..26], and have been preset to :
  754. 0 - '.' (default drive - hence current dir is ok.)
  755. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  756. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  757. 3 - '/' (C: equivalent of dos is the root partition)
  758. 4..26 (can be set by you're own applications)
  759. ! Use AddDisk() to Add new drives !
  760. They both return -1 when a failure occurs.
  761. }
  762. Const
  763. FixDriveStr : array[0..3] of pchar=(
  764. '.',
  765. '/fd0/.',
  766. '/fd1/.',
  767. '/.'
  768. );
  769. var
  770. Drives : byte = 4;
  771. DriveStr : array[4..26] of pchar;
  772. Function AddDisk(const path:string) : Byte;
  773. begin
  774. if not (DriveStr[Drives]=nil) then
  775. FreeMem(DriveStr[Drives]);
  776. GetMem(DriveStr[Drives],length(Path)+1);
  777. StrPCopy(DriveStr[Drives],path);
  778. Result:=Drives;
  779. inc(Drives);
  780. if Drives>26 then
  781. Drives:=4;
  782. end;
  783. Function DiskFree(Drive: Byte): int64;
  784. var
  785. fs : tstatfs;
  786. Begin
  787. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (statfs(StrPas(fixdrivestr[drive]),fs)<>-1)) or
  788. ((Drive <= High(drivestr)) and (not (drivestr[Drive]=nil)) and (statfs(StrPas(drivestr[drive]),fs)<>-1)) then
  789. Diskfree:=int64(fs.bavail)*int64(fs.bsize)
  790. else
  791. Diskfree:=-1;
  792. End;
  793. Function DiskSize(Drive: Byte): int64;
  794. var
  795. fs : tstatfs;
  796. Begin
  797. if ((Drive in [Low(FixDriveStr)..High(FixDriveStr)]) and (not (fixdrivestr[Drive]=nil)) and (statfs(StrPas(fixdrivestr[drive]),fs)<>-1)) or
  798. ((drive <= High(drivestr)) and (not (drivestr[Drive]=nil)) and (statfs(StrPas(drivestr[drive]),fs)<>-1)) then
  799. DiskSize:=int64(fs.blocks)*int64(fs.bsize)
  800. else
  801. DiskSize:=-1;
  802. End;
  803. Procedure FreeDriveStr;
  804. var
  805. i: longint;
  806. begin
  807. for i:=low(drivestr) to high(drivestr) do
  808. if assigned(drivestr[i]) then
  809. begin
  810. freemem(drivestr[i]);
  811. drivestr[i]:=nil;
  812. end;
  813. end;
  814. Function GetCurrentDir : String;
  815. begin
  816. GetDir (0,Result);
  817. end;
  818. Function SetCurrentDir (Const NewDir : String) : Boolean;
  819. begin
  820. {$I-}
  821. ChDir(NewDir);
  822. {$I+}
  823. result := (IOResult = 0);
  824. end;
  825. Function CreateDir (Const NewDir : String) : Boolean;
  826. begin
  827. {$I-}
  828. MkDir(NewDir);
  829. {$I+}
  830. result := (IOResult = 0);
  831. end;
  832. Function RemoveDir (Const Dir : String) : Boolean;
  833. begin
  834. {$I-}
  835. RmDir(Dir);
  836. {$I+}
  837. result := (IOResult = 0);
  838. end;
  839. {****************************************************************************
  840. Misc Functions
  841. ****************************************************************************}
  842. procedure Beep;
  843. begin
  844. end;
  845. {****************************************************************************
  846. Locale Functions
  847. ****************************************************************************}
  848. Function GetEpochTime: cint;
  849. {
  850. Get the number of seconds since 00:00, January 1 1970, GMT
  851. the time NOT corrected any way
  852. }
  853. begin
  854. GetEpochTime:=fptime;
  855. end;
  856. procedure GetTime(var hour,min,sec,msec,usec:word);
  857. {
  858. Gets the current time, adjusted to local time
  859. }
  860. var
  861. year,day,month:Word;
  862. tz:timeval;
  863. begin
  864. fpgettimeofday(@tz,nil);
  865. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  866. msec:=tz.tv_usec div 1000;
  867. usec:=tz.tv_usec mod 1000;
  868. end;
  869. procedure GetTime(var hour,min,sec,sec100:word);
  870. {
  871. Gets the current time, adjusted to local time
  872. }
  873. var
  874. usec : word;
  875. begin
  876. gettime(hour,min,sec,sec100,usec);
  877. sec100:=sec100 div 10;
  878. end;
  879. Procedure GetTime(Var Hour,Min,Sec:Word);
  880. {
  881. Gets the current time, adjusted to local time
  882. }
  883. var
  884. msec,usec : Word;
  885. Begin
  886. gettime(hour,min,sec,msec,usec);
  887. End;
  888. Procedure GetDate(Var Year,Month,Day:Word);
  889. {
  890. Gets the current date, adjusted to local time
  891. }
  892. var
  893. hour,minute,second : word;
  894. Begin
  895. EpochToLocal(fptime,year,month,day,hour,minute,second);
  896. End;
  897. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  898. {
  899. Gets the current date, adjusted to local time
  900. }
  901. Begin
  902. EpochToLocal(fptime,year,month,day,hour,minute,second);
  903. End;
  904. {$ifndef FPUNONE}
  905. Procedure GetLocalTime(var SystemTime: TSystemTime);
  906. var
  907. usecs : Word;
  908. begin
  909. GetTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  910. GetDate(SystemTime.Year, SystemTime.Month, SystemTime.Day);
  911. // SystemTime.MilliSecond := 0;
  912. end ;
  913. {$endif}
  914. Procedure InitAnsi;
  915. Var
  916. i : longint;
  917. begin
  918. { Fill table entries 0 to 127 }
  919. for i := 0 to 96 do
  920. UpperCaseTable[i] := chr(i);
  921. for i := 97 to 122 do
  922. UpperCaseTable[i] := chr(i - 32);
  923. for i := 123 to 191 do
  924. UpperCaseTable[i] := chr(i);
  925. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  926. for i := 0 to 64 do
  927. LowerCaseTable[i] := chr(i);
  928. for i := 65 to 90 do
  929. LowerCaseTable[i] := chr(i + 32);
  930. for i := 91 to 191 do
  931. LowerCaseTable[i] := chr(i);
  932. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  933. end;
  934. Procedure InitInternational;
  935. begin
  936. InitInternationalGeneric;
  937. InitAnsi;
  938. end;
  939. function SysErrorMessage(ErrorCode: Integer): String;
  940. begin
  941. Result:=StrError(ErrorCode);
  942. end;
  943. {****************************************************************************
  944. OS utility functions
  945. ****************************************************************************}
  946. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  947. begin
  948. Result:=StrPas(BaseUnix.FPGetenv(PChar(pointer(EnvVar))));
  949. end;
  950. Function GetEnvironmentVariableCount : Integer;
  951. begin
  952. Result:=FPCCountEnvVar(EnvP);
  953. end;
  954. Function GetEnvironmentString(Index : Integer) : String;
  955. begin
  956. Result:=FPCGetEnvStrFromP(Envp,Index);
  957. end;
  958. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  959. var
  960. pid : longint;
  961. e : EOSError;
  962. CommandLine: AnsiString;
  963. cmdline2 : ppchar;
  964. Begin
  965. { always surround the name of the application by quotes
  966. so that long filenames will always be accepted. But don't
  967. do it if there are already double quotes!
  968. }
  969. // Only place we still parse
  970. cmdline2:=nil;
  971. if Comline<>'' Then
  972. begin
  973. CommandLine:=ComLine;
  974. { Make an unique copy because stringtoppchar modifies the
  975. string }
  976. UniqueString(CommandLine);
  977. cmdline2:=StringtoPPChar(CommandLine,1);
  978. cmdline2^:=pchar(pointer(Path));
  979. end
  980. else
  981. begin
  982. getmem(cmdline2,2*sizeof(pchar));
  983. cmdline2^:=pchar(Path);
  984. cmdline2[1]:=nil;
  985. end;
  986. {$ifdef USE_VFORK}
  987. pid:=fpvFork;
  988. {$else USE_VFORK}
  989. pid:=fpFork;
  990. {$endif USE_VFORK}
  991. if pid=0 then
  992. begin
  993. {The child does the actual exec, and then exits}
  994. fpexecv(pchar(pointer(Path)),Cmdline2);
  995. { If the execve fails, we return an exitvalue of 127, to let it be known}
  996. fpExit(127);
  997. end
  998. else
  999. if pid=-1 then {Fork failed}
  1000. begin
  1001. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1002. e.ErrorCode:=-1;
  1003. raise e;
  1004. end;
  1005. { We're in the parent, let's wait. }
  1006. result:=WaitProcess(pid); // WaitPid and result-convert
  1007. if Comline<>'' Then
  1008. freemem(cmdline2);
  1009. if (result<0) or (result=127) then
  1010. begin
  1011. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1012. E.ErrorCode:=result;
  1013. Raise E;
  1014. end;
  1015. End;
  1016. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array Of AnsiString):integer;
  1017. var
  1018. pid : longint;
  1019. e : EOSError;
  1020. Begin
  1021. pid:=fpFork;
  1022. if pid=0 then
  1023. begin
  1024. {The child does the actual exec, and then exits}
  1025. fpexecl(Path,Comline);
  1026. { If the execve fails, we return an exitvalue of 127, to let it be known}
  1027. fpExit(127);
  1028. end
  1029. else
  1030. if pid=-1 then {Fork failed}
  1031. begin
  1032. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  1033. e.ErrorCode:=-1;
  1034. raise e;
  1035. end;
  1036. { We're in the parent, let's wait. }
  1037. result:=WaitProcess(pid); // WaitPid and result-convert
  1038. if (result<0) or (result=127) then
  1039. begin
  1040. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  1041. E.ErrorCode:=result;
  1042. raise E;
  1043. end;
  1044. End;
  1045. procedure Sleep(milliseconds: Cardinal);
  1046. Var
  1047. timeout,timeoutresult : TTimespec;
  1048. res: cint;
  1049. begin
  1050. timeout.tv_sec:=milliseconds div 1000;
  1051. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  1052. repeat
  1053. res:=fpnanosleep(@timeout,@timeoutresult);
  1054. timeout:=timeoutresult;
  1055. until (res<>-1) or (fpgeterrno<>ESysEINTR);
  1056. end;
  1057. Function GetLastOSError : Integer;
  1058. begin
  1059. Result:=fpgetErrNo;
  1060. end;
  1061. { ---------------------------------------------------------------------
  1062. Application config files
  1063. ---------------------------------------------------------------------}
  1064. Function GetHomeDir : String;
  1065. begin
  1066. Result:=GetEnvironmentVariable('HOME');
  1067. If (Result<>'') then
  1068. Result:=IncludeTrailingPathDelimiter(Result);
  1069. end;
  1070. { Follows base-dir spec,
  1071. see [http://freedesktop.org/Standards/basedir-spec].
  1072. Always ends with PathDelim. }
  1073. Function XdgConfigHome : String;
  1074. begin
  1075. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  1076. if (Result='') then
  1077. Result:=GetHomeDir + '.config/'
  1078. else
  1079. Result:=IncludeTrailingPathDelimiter(Result);
  1080. end;
  1081. Function GetAppConfigDir(Global : Boolean) : String;
  1082. begin
  1083. If Global then
  1084. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1085. else
  1086. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1087. if VendorName<>'' then
  1088. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1089. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1090. end;
  1091. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  1092. begin
  1093. If Global then
  1094. Result:=IncludeTrailingPathDelimiter(SysConfigDir)
  1095. else
  1096. Result:=IncludeTrailingPathDelimiter(XdgConfigHome);
  1097. if SubDir then
  1098. begin
  1099. if VendorName<>'' then
  1100. Result:=IncludeTrailingPathDelimiter(Result+VendorName);
  1101. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  1102. end;
  1103. Result:=Result+ApplicationName+ConfigExtension;
  1104. end;
  1105. {****************************************************************************
  1106. GetTempDir
  1107. ****************************************************************************}
  1108. Function GetTempDir(Global : Boolean) : String;
  1109. begin
  1110. If Assigned(OnGetTempDir) then
  1111. Result:=OnGetTempDir(Global)
  1112. else
  1113. begin
  1114. Result:=GetEnvironmentVariable('TEMP');
  1115. If (Result='') Then
  1116. Result:=GetEnvironmentVariable('TMP');
  1117. if (Result='') then
  1118. Result:='/tmp/' // fallback.
  1119. end;
  1120. if (Result<>'') then
  1121. Result:=IncludeTrailingPathDelimiter(Result);
  1122. end;
  1123. {****************************************************************************
  1124. GetUserDir
  1125. ****************************************************************************}
  1126. Var
  1127. TheUserDir : String;
  1128. Function GetUserDir : String;
  1129. begin
  1130. If (TheUserDir='') then
  1131. begin
  1132. TheUserDir:=GetEnvironmentVariable('HOME');
  1133. if (TheUserDir<>'') then
  1134. TheUserDir:=IncludeTrailingPathDelimiter(TheUserDir)
  1135. else
  1136. TheUserDir:=GetTempDir(False);
  1137. end;
  1138. Result:=TheUserDir;
  1139. end;
  1140. {****************************************************************************
  1141. Initialization code
  1142. ****************************************************************************}
  1143. Initialization
  1144. InitExceptions; { Initialize exceptions. OS independent }
  1145. InitInternational; { Initialize internationalization settings }
  1146. SysConfigDir:='/etc'; { Initialize system config dir }
  1147. Finalization
  1148. FreeDriveStr;
  1149. DoneExceptions;
  1150. end.