sysutils.pp 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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) 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. uses
  28. Unix,errors,sysconst,Unixtype;
  29. { Include platform independent interface part }
  30. {$i sysutilh.inc}
  31. Procedure AddDisk(const path:string);
  32. { the following is Kylix compatibility stuff, it should be moved to a
  33. special compatibilty unit (FK) }
  34. const
  35. RTL_SIGINT = 0;
  36. RTL_SIGFPE = 1;
  37. RTL_SIGSEGV = 2;
  38. RTL_SIGILL = 3;
  39. RTL_SIGBUS = 4;
  40. RTL_SIGQUIT = 5;
  41. RTL_SIGLAST = RTL_SIGQUIT;
  42. RTL_SIGDEFAULT = -1;
  43. type
  44. TSignalState = (ssNotHooked, ssHooked, ssOverridden);
  45. function InquireSignal(RtlSigNum: Integer): TSignalState;
  46. procedure AbandonSignalHandler(RtlSigNum: Integer);
  47. procedure HookSignal(RtlSigNum: Integer);
  48. procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean = True);
  49. implementation
  50. Uses
  51. {$ifdef FPC_USE_LIBC}initc{$ELSE}Syscall{$ENDIF}, Baseunix, unixutil;
  52. function InquireSignal(RtlSigNum: Integer): TSignalState;
  53. begin
  54. end;
  55. procedure AbandonSignalHandler(RtlSigNum: Integer);
  56. begin
  57. end;
  58. procedure HookSignal(RtlSigNum: Integer);
  59. begin
  60. end;
  61. procedure UnhookSignal(RtlSigNum: Integer; OnlyIfHooked: Boolean = True);
  62. begin
  63. end;
  64. {$Define OS_FILEISREADONLY} // Specific implementation for Unix.
  65. {$DEFINE FPC_FEXPAND_TILDE} { Tilde is expanded to home }
  66. {$DEFINE FPC_FEXPAND_GETENVPCHAR} { GetEnv result is a PChar }
  67. { Include platform independent implementation part }
  68. {$i sysutils.inc}
  69. { Include SysCreateGUID function }
  70. {$i suuid.inc}
  71. Const
  72. {Date Translation}
  73. C1970=2440588;
  74. D0 = 1461;
  75. D1 = 146097;
  76. D2 =1721119;
  77. Procedure JulianToGregorian(JulianDN:LongInt;Var Year,Month,Day:Word);
  78. Var
  79. YYear,XYear,Temp,TempMonth : LongInt;
  80. Begin
  81. Temp:=((JulianDN-D2) shl 2)-1;
  82. JulianDN:=Temp Div D1;
  83. XYear:=(Temp Mod D1) or 3;
  84. YYear:=(XYear Div D0);
  85. Temp:=((((XYear mod D0)+4) shr 2)*5)-3;
  86. Day:=((Temp Mod 153)+5) Div 5;
  87. TempMonth:=Temp Div 153;
  88. If TempMonth>=10 Then
  89. Begin
  90. inc(YYear);
  91. dec(TempMonth,12);
  92. End;
  93. inc(TempMonth,3);
  94. Month := TempMonth;
  95. Year:=YYear+(JulianDN*100);
  96. end;
  97. Procedure EpochToLocal(epoch:longint;var year,month,day,hour,minute,second:Word);
  98. {
  99. Transforms Epoch time into local time (hour, minute,seconds)
  100. }
  101. Var
  102. DateNum: LongInt;
  103. Begin
  104. inc(Epoch,TZSeconds);
  105. Datenum:=(Epoch Div 86400) + c1970;
  106. JulianToGregorian(DateNum,Year,Month,day);
  107. Epoch:=Abs(Epoch Mod 86400);
  108. Hour:=Epoch Div 3600;
  109. Epoch:=Epoch Mod 3600;
  110. Minute:=Epoch Div 60;
  111. Second:=Epoch Mod 60;
  112. End;
  113. {****************************************************************************
  114. File Functions
  115. ****************************************************************************}
  116. Procedure FSplit(const Path:PathStr;Var Dir:DirStr;Var Name:NameStr;Var Ext:ExtStr);
  117. Var
  118. DotPos,SlashPos,i : longint;
  119. Begin
  120. SlashPos:=0;
  121. DotPos:=256;
  122. i:=Length(Path);
  123. While (i>0) and (SlashPos=0) Do
  124. Begin
  125. If (DotPos=256) and (Path[i]='.') Then
  126. begin
  127. DotPos:=i;
  128. end;
  129. If (Path[i]='/') Then
  130. SlashPos:=i;
  131. Dec(i);
  132. End;
  133. Ext:=Copy(Path,DotPos,255);
  134. Dir:=Copy(Path,1,SlashPos);
  135. Name:=Copy(Path,SlashPos + 1,DotPos - SlashPos - 1);
  136. End;
  137. Function FileOpen (Const FileName : string; Mode : Integer) : Longint;
  138. Var LinuxFlags : longint;
  139. BEGIN
  140. LinuxFlags:=0;
  141. Case (Mode and 3) of
  142. 0 : LinuxFlags:=LinuxFlags or O_RdOnly;
  143. 1 : LinuxFlags:=LinuxFlags or O_WrOnly;
  144. 2 : LinuxFlags:=LinuxFlags or O_RdWr;
  145. end;
  146. FileOpen:=fpOpen (FileName,LinuxFlags);
  147. //!! We need to set locking based on Mode !!
  148. end;
  149. Function FileCreate (Const FileName : String) : Longint;
  150. begin
  151. FileCreate:=fpOpen(FileName,O_RdWr or O_Creat or O_Trunc);
  152. end;
  153. Function FileCreate (Const FileName : String;Mode : Longint) : Longint;
  154. Var LinuxFlags : longint;
  155. BEGIN
  156. LinuxFlags:=0;
  157. Case (Mode and 3) of
  158. 0 : LinuxFlags:=LinuxFlags or O_RdOnly;
  159. 1 : LinuxFlags:=LinuxFlags or O_WrOnly;
  160. 2 : LinuxFlags:=LinuxFlags or O_RdWr;
  161. end;
  162. FileCreate:=fpOpen(FileName,LinuxFlags or O_Creat or O_Trunc);
  163. end;
  164. Function FileRead (Handle : Longint; Var Buffer; Count : longint) : Longint;
  165. begin
  166. FileRead:=fpRead (Handle,Buffer,Count);
  167. end;
  168. Function FileWrite (Handle : Longint; const Buffer; Count : Longint) : Longint;
  169. begin
  170. FileWrite:=fpWrite (Handle,Buffer,Count);
  171. end;
  172. Function FileSeek (Handle,FOffset,Origin : Longint) : Longint;
  173. begin
  174. FileSeek:=fplSeek (Handle,FOffset,Origin);
  175. end;
  176. Function FileSeek (Handle : Longint; FOffset,Origin : Int64) : Int64;
  177. begin
  178. {$warning need to add 64bit call }
  179. FileSeek:=fplSeek (Handle,FOffset,Origin);
  180. end;
  181. Procedure FileClose (Handle : Longint);
  182. begin
  183. fpclose(Handle);
  184. end;
  185. Function FileTruncate (Handle,Size: Longint) : boolean;
  186. begin
  187. FileTruncate:=fpftruncate(Handle,Size)>=0;
  188. end;
  189. Function UnixToWinAge(UnixAge : time_t): Longint;
  190. Var
  191. Y,M,D,hh,mm,ss : word;
  192. begin
  193. EpochToLocal(UnixAge,y,m,d,hh,mm,ss);
  194. Result:=DateTimeToFileDate(EncodeDate(y,m,d)+EncodeTime(hh,mm,ss,0));
  195. end;
  196. Function FileAge (Const FileName : String): Longint;
  197. Var Info : Stat;
  198. begin
  199. If fpstat (FileName,Info)<0 then
  200. exit(-1)
  201. else
  202. Result:=UnixToWinAge(info.st_mtime);
  203. end;
  204. Function FileExists (Const FileName : String) : Boolean;
  205. Var Info : Stat;
  206. begin
  207. FileExists:=fpstat(filename,Info)>=0;
  208. end;
  209. Function DirectoryExists (Const Directory : String) : Boolean;
  210. Var Info : Stat;
  211. begin
  212. DirectoryExists:=(fpstat(Directory,Info)>=0) and fpS_ISDIR(Info.st_mode);
  213. end;
  214. Function LinuxToWinAttr (FN : Pchar; Const Info : Stat) : Longint;
  215. begin
  216. Result:=faArchive;
  217. If fpS_ISDIR(Info.st_mode) then
  218. Result:=Result or faDirectory;
  219. If (FN[0]='.') and (not (FN[1] in [#0,'.'])) then
  220. Result:=Result or faHidden;
  221. If (Info.st_Mode and S_IWUSR)=0 Then
  222. Result:=Result or faReadOnly;
  223. 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
  224. Result:=Result or faSysFile;
  225. If fpS_ISLNK(Info.st_mode) Then
  226. Result:=Result or faSymLink;
  227. end;
  228. type
  229. pglob = ^tglob;
  230. tglob = record
  231. name : pchar;
  232. next : pglob;
  233. end;
  234. Function Dirname(Const path:pathstr):pathstr;
  235. {
  236. This function returns the directory part of a complete path.
  237. Unless the directory is root '/', The last character is not
  238. a slash.
  239. }
  240. var
  241. Dir : DirStr;
  242. Name : NameStr;
  243. Ext : ExtStr;
  244. begin
  245. FSplit(Path,Dir,Name,Ext);
  246. if length(Dir)>1 then
  247. Delete(Dir,length(Dir),1);
  248. DirName:=Dir;
  249. end;
  250. Function Basename(Const path:pathstr;Const suf:pathstr):pathstr;
  251. {
  252. This function returns the filename part of a complete path. If suf is
  253. supplied, it is cut off the filename.
  254. }
  255. var
  256. Dir : DirStr;
  257. Name : NameStr;
  258. Ext : ExtStr;
  259. begin
  260. FSplit(Path,Dir,Name,Ext);
  261. if Suf<>Ext then
  262. Name:=Name+Ext;
  263. BaseName:=Name;
  264. end;
  265. Function FNMatch(const Pattern,Name:shortstring):Boolean;
  266. Var
  267. LenPat,LenName : longint;
  268. Function DoFNMatch(i,j:longint):Boolean;
  269. Var
  270. Found : boolean;
  271. Begin
  272. Found:=true;
  273. While Found and (i<=LenPat) Do
  274. Begin
  275. Case Pattern[i] of
  276. '?' : Found:=(j<=LenName);
  277. '*' : Begin
  278. {find the next character in pattern, different of ? and *}
  279. while Found do
  280. begin
  281. inc(i);
  282. if i>LenPat then Break;
  283. case Pattern[i] of
  284. '*' : ;
  285. '?' : begin
  286. if j>LenName then begin DoFNMatch:=false; Exit; end;
  287. inc(j);
  288. end;
  289. else
  290. Found:=false;
  291. end;
  292. end;
  293. Assert((i>LenPat) or ( (Pattern[i]<>'*') and (Pattern[i]<>'?') ));
  294. {Now, find in name the character which i points to, if the * or ?
  295. wasn't the last character in the pattern, else, use up all the
  296. chars in name}
  297. Found:=false;
  298. if (i<=LenPat) then
  299. begin
  300. repeat
  301. {find a letter (not only first !) which maches pattern[i]}
  302. while (j<=LenName) and (name[j]<>pattern[i]) do
  303. inc (j);
  304. if (j<LenName) then
  305. begin
  306. if DoFnMatch(i+1,j+1) then
  307. begin
  308. i:=LenPat;
  309. j:=LenName;{we can stop}
  310. Found:=true;
  311. Break;
  312. end else
  313. inc(j);{We didn't find one, need to look further}
  314. end else
  315. if j=LenName then
  316. begin
  317. Found:=true;
  318. Break;
  319. end;
  320. { This 'until' condition must be j>LenName, not j>=LenName.
  321. That's because when we 'need to look further' and
  322. j = LenName then loop must not terminate. }
  323. until (j>LenName);
  324. end else
  325. begin
  326. j:=LenName;{we can stop}
  327. Found:=true;
  328. end;
  329. end;
  330. else {not a wildcard character in pattern}
  331. Found:=(j<=LenName) and (pattern[i]=name[j]);
  332. end;
  333. inc(i);
  334. inc(j);
  335. end;
  336. DoFnMatch:=Found and (j>LenName);
  337. end;
  338. Begin {start FNMatch}
  339. LenPat:=Length(Pattern);
  340. LenName:=Length(Name);
  341. FNMatch:=DoFNMatch(1,1);
  342. End;
  343. Procedure Globfree(var p : pglob);
  344. {
  345. Release memory occupied by pglob structure, and names in it.
  346. sets p to nil.
  347. }
  348. var
  349. temp : pglob;
  350. begin
  351. while assigned(p) do
  352. begin
  353. temp:=p^.next;
  354. if assigned(p^.name) then
  355. freemem(p^.name);
  356. dispose(p);
  357. p:=temp;
  358. end;
  359. end;
  360. Function Glob(Const path:pathstr):pglob;
  361. {
  362. Fills a tglob structure with entries matching path,
  363. and returns a pointer to it. Returns nil on error,
  364. linuxerror is set accordingly.
  365. }
  366. var
  367. temp,
  368. temp2 : string[255];
  369. thedir : pdir;
  370. buffer : pdirent;
  371. root,
  372. current : pglob;
  373. begin
  374. { Get directory }
  375. temp:=dirname(path);
  376. if temp='' then
  377. temp:='.';
  378. temp:=temp+#0;
  379. thedir:=fpopendir(@temp[1]);
  380. if thedir=nil then
  381. exit(nil);
  382. temp:=basename(path,''); { get the pattern }
  383. if thedir^.dd_fd<0 then
  384. exit(nil);
  385. {get the entries}
  386. root:=nil;
  387. current:=nil;
  388. repeat
  389. buffer:=fpreaddir(thedir^);
  390. if buffer=nil then
  391. break;
  392. temp2:=strpas(@(buffer^.d_name[0]));
  393. if fnmatch(temp,temp2) then
  394. begin
  395. if root=nil then
  396. begin
  397. new(root);
  398. current:=root;
  399. end
  400. else
  401. begin
  402. new(current^.next);
  403. current:=current^.next;
  404. end;
  405. if current=nil then
  406. begin
  407. fpseterrno(ESysENOMEM);
  408. globfree(root);
  409. break;
  410. end;
  411. current^.next:=nil;
  412. getmem(current^.name,length(temp2)+1);
  413. if current^.name=nil then
  414. begin
  415. fpseterrno(ESysENOMEM);
  416. globfree(root);
  417. break;
  418. end;
  419. move(buffer^.d_name[0],current^.name^,length(temp2)+1);
  420. end;
  421. until false;
  422. fpclosedir(thedir^);
  423. glob:=root;
  424. end;
  425. {
  426. GlobToSearch takes a glob entry, stats the file.
  427. The glob entry is removed.
  428. If FileAttributes match, the entry is reused
  429. }
  430. Type
  431. TGlobSearchRec = Record
  432. Path : shortString;
  433. GlobHandle : PGlob;
  434. end;
  435. PGlobSearchRec = ^TGlobSearchRec;
  436. Function GlobToTSearchRec (Var Info : TSearchRec) : Boolean;
  437. Var SInfo : Stat;
  438. p : Pglob;
  439. GlobSearchRec : PGlobSearchrec;
  440. begin
  441. GlobSearchRec:=Info.FindHandle;
  442. P:=GlobSearchRec^.GlobHandle;
  443. Result:=P<>Nil;
  444. If Result then
  445. begin
  446. GlobSearchRec^.GlobHandle:=P^.Next;
  447. Result:=Fpstat(GlobSearchRec^.Path+StrPas(p^.name),SInfo)>=0;
  448. Info.PathOnly:=GlobSearchRec^.Path;
  449. If Result then
  450. begin
  451. Info.Attr:=LinuxToWinAttr(p^.name,SInfo);
  452. Result:=(Info.ExcludeAttr and Info.Attr)=0;
  453. If Result Then
  454. With Info do
  455. begin
  456. Attr:=Info.Attr;
  457. If P^.Name<>Nil then
  458. Name:=strpas(p^.name);
  459. Time:=UnixToWinAge(Sinfo.st_mtime);
  460. Size:=Sinfo.st_Size;
  461. Mode:=Sinfo.st_mode;
  462. end;
  463. end;
  464. P^.Next:=Nil;
  465. GlobFree(P);
  466. end;
  467. end;
  468. Function DoFind(Var Rslt : TSearchRec) : Longint;
  469. Var
  470. GlobSearchRec : PGlobSearchRec;
  471. begin
  472. Result:=-1;
  473. GlobSearchRec:=Rslt.FindHandle;
  474. If (GlobSearchRec^.GlobHandle<>Nil) then
  475. While (GlobSearchRec^.GlobHandle<>Nil) and not (Result=0) do
  476. If GlobToTSearchRec(Rslt) Then Result:=0;
  477. end;
  478. Function FindFirst (Const Path : String; Attr : Longint; out Rslt : TSearchRec) : Longint;
  479. Var
  480. GlobSearchRec : PGlobSearchRec;
  481. begin
  482. New(GlobSearchRec);
  483. GlobSearchRec^.Path:=ExpandFileName(ExtractFilePath(Path));
  484. GlobSearchRec^.GlobHandle:=Glob(Path);
  485. Rslt.ExcludeAttr:=Not Attr and (faHidden or faSysFile or faVolumeID or faDirectory); //!! Not correct !!
  486. Rslt.FindHandle:=GlobSearchRec;
  487. Result:=DoFind (Rslt);
  488. end;
  489. Function FindNext (Var Rslt : TSearchRec) : Longint;
  490. begin
  491. Result:=DoFind (Rslt);
  492. end;
  493. Procedure FindClose (Var F : TSearchrec);
  494. Var
  495. GlobSearchRec : PGlobSearchRec;
  496. begin
  497. GlobSearchRec:=F.FindHandle;
  498. GlobFree (GlobSearchRec^.GlobHandle);
  499. Dispose(GlobSearchRec);
  500. end;
  501. Function FileGetDate (Handle : Longint) : Longint;
  502. Var Info : Stat;
  503. begin
  504. If (fpFStat(Handle,Info))<0 then
  505. Result:=-1
  506. else
  507. Result:=Info.st_Mtime;
  508. end;
  509. Function FileSetDate (Handle,Age : Longint) : Longint;
  510. begin
  511. // Impossible under Linux from FileHandle !!
  512. FileSetDate:=-1;
  513. end;
  514. Function FileGetAttr (Const FileName : String) : Longint;
  515. Var Info : Stat;
  516. begin
  517. If FpStat (FileName,Info)<0 then
  518. Result:=-1
  519. Else
  520. Result:=LinuxToWinAttr(Pchar(ExtractFileName(FileName)),Info);
  521. end;
  522. Function FileSetAttr (Const Filename : String; Attr: longint) : Longint;
  523. begin
  524. Result:=-1;
  525. end;
  526. Function DeleteFile (Const FileName : String) : Boolean;
  527. begin
  528. Result:=fpUnLink (FileName)>=0;
  529. end;
  530. Function RenameFile (Const OldName, NewName : String) : Boolean;
  531. begin
  532. RenameFile:=BaseUnix.FpRename(OldNAme,NewName)>=0;
  533. end;
  534. Function FileIsReadOnly(const FileName: String): Boolean;
  535. begin
  536. Result := fpAccess(PChar(FileName),W_OK)<>0;
  537. end;
  538. Function FileSetDate (Const FileName : String;Age : Longint) : Longint;
  539. var
  540. t: TUTimBuf;
  541. begin
  542. Result := 0;
  543. t.actime := Age;
  544. t.modtime := Age;
  545. if fputime(PChar(FileName), @t) = -1 then
  546. Result := fpgeterrno;
  547. end;
  548. {****************************************************************************
  549. Disk Functions
  550. ****************************************************************************}
  551. {
  552. The Diskfree and Disksize functions need a file on the specified drive, since this
  553. is required for the statfs system call.
  554. These filenames are set in drivestr[0..26], and have been preset to :
  555. 0 - '.' (default drive - hence current dir is ok.)
  556. 1 - '/fd0/.' (floppy drive 1 - should be adapted to local system )
  557. 2 - '/fd1/.' (floppy drive 2 - should be adapted to local system )
  558. 3 - '/' (C: equivalent of dos is the root partition)
  559. 4..26 (can be set by you're own applications)
  560. ! Use AddDisk() to Add new drives !
  561. They both return -1 when a failure occurs.
  562. }
  563. Const
  564. FixDriveStr : array[0..3] of pchar=(
  565. '.',
  566. '/fd0/.',
  567. '/fd1/.',
  568. '/.'
  569. );
  570. var
  571. Drives : byte;
  572. DriveStr : array[4..26] of pchar;
  573. Procedure AddDisk(const path:string);
  574. begin
  575. if not (DriveStr[Drives]=nil) then
  576. FreeMem(DriveStr[Drives],StrLen(DriveStr[Drives])+1);
  577. GetMem(DriveStr[Drives],length(Path)+1);
  578. StrPCopy(DriveStr[Drives],path);
  579. inc(Drives);
  580. if Drives>26 then
  581. Drives:=4;
  582. end;
  583. Function DiskFree(Drive: Byte): int64;
  584. var
  585. fs : tstatfs;
  586. Begin
  587. if ((Drive<4) and (not (fixdrivestr[Drive]=nil)) and (statfs(StrPas(fixdrivestr[drive]),fs)<>-1)) or
  588. ((not (drivestr[Drive]=nil)) and (statfs(StrPas(drivestr[drive]),fs)<>-1)) then
  589. Diskfree:=int64(fs.bavail)*int64(fs.bsize)
  590. else
  591. Diskfree:=-1;
  592. End;
  593. Function DiskSize(Drive: Byte): int64;
  594. var
  595. fs : tstatfs;
  596. Begin
  597. if ((Drive<4) and (not (fixdrivestr[Drive]=nil)) and (statfs(StrPas(fixdrivestr[drive]),fs)<>-1)) or
  598. ((not (drivestr[Drive]=nil)) and (statfs(StrPas(drivestr[drive]),fs)<>-1)) then
  599. DiskSize:=int64(fs.blocks)*int64(fs.bsize)
  600. else
  601. DiskSize:=-1;
  602. End;
  603. Function GetCurrentDir : String;
  604. begin
  605. GetDir (0,Result);
  606. end;
  607. Function SetCurrentDir (Const NewDir : String) : Boolean;
  608. begin
  609. {$I-}
  610. ChDir(NewDir);
  611. {$I+}
  612. result := (IOResult = 0);
  613. end;
  614. Function CreateDir (Const NewDir : String) : Boolean;
  615. begin
  616. {$I-}
  617. MkDir(NewDir);
  618. {$I+}
  619. result := (IOResult = 0);
  620. end;
  621. Function RemoveDir (Const Dir : String) : Boolean;
  622. begin
  623. {$I-}
  624. RmDir(Dir);
  625. {$I+}
  626. result := (IOResult = 0);
  627. end;
  628. {****************************************************************************
  629. Misc Functions
  630. ****************************************************************************}
  631. procedure Beep;
  632. begin
  633. end;
  634. {****************************************************************************
  635. Locale Functions
  636. ****************************************************************************}
  637. Function GetEpochTime: cint;
  638. {
  639. Get the number of seconds since 00:00, January 1 1970, GMT
  640. the time NOT corrected any way
  641. }
  642. begin
  643. GetEpochTime:=fptime;
  644. end;
  645. procedure GetTime(var hour,min,sec,msec,usec:word);
  646. {
  647. Gets the current time, adjusted to local time
  648. }
  649. var
  650. year,day,month:Word;
  651. tz:timeval;
  652. begin
  653. fpgettimeofday(@tz,nil);
  654. EpochToLocal(tz.tv_sec,year,month,day,hour,min,sec);
  655. msec:=tz.tv_usec div 1000;
  656. usec:=tz.tv_usec mod 1000;
  657. end;
  658. procedure GetTime(var hour,min,sec,sec100:word);
  659. {
  660. Gets the current time, adjusted to local time
  661. }
  662. var
  663. usec : word;
  664. begin
  665. gettime(hour,min,sec,sec100,usec);
  666. sec100:=sec100 div 10;
  667. end;
  668. Procedure GetTime(Var Hour,Min,Sec:Word);
  669. {
  670. Gets the current time, adjusted to local time
  671. }
  672. var
  673. msec,usec : Word;
  674. Begin
  675. gettime(hour,min,sec,msec,usec);
  676. End;
  677. Procedure GetDate(Var Year,Month,Day:Word);
  678. {
  679. Gets the current date, adjusted to local time
  680. }
  681. var
  682. hour,minute,second : word;
  683. Begin
  684. EpochToLocal(fptime,year,month,day,hour,minute,second);
  685. End;
  686. Procedure GetDateTime(Var Year,Month,Day,hour,minute,second:Word);
  687. {
  688. Gets the current date, adjusted to local time
  689. }
  690. Begin
  691. EpochToLocal(fptime,year,month,day,hour,minute,second);
  692. End;
  693. Procedure GetLocalTime(var SystemTime: TSystemTime);
  694. var
  695. usecs : Word;
  696. begin
  697. GetTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond, usecs);
  698. GetDate(SystemTime.Year, SystemTime.Month, SystemTime.Day);
  699. // SystemTime.MilliSecond := 0;
  700. end ;
  701. Procedure InitAnsi;
  702. Var
  703. i : longint;
  704. begin
  705. { Fill table entries 0 to 127 }
  706. for i := 0 to 96 do
  707. UpperCaseTable[i] := chr(i);
  708. for i := 97 to 122 do
  709. UpperCaseTable[i] := chr(i - 32);
  710. for i := 123 to 191 do
  711. UpperCaseTable[i] := chr(i);
  712. Move (CPISO88591UCT,UpperCaseTable[192],SizeOf(CPISO88591UCT));
  713. for i := 0 to 64 do
  714. LowerCaseTable[i] := chr(i);
  715. for i := 65 to 90 do
  716. LowerCaseTable[i] := chr(i + 32);
  717. for i := 91 to 191 do
  718. LowerCaseTable[i] := chr(i);
  719. Move (CPISO88591LCT,LowerCaseTable[192],SizeOf(CPISO88591UCT));
  720. end;
  721. Procedure InitInternational;
  722. begin
  723. InitInternationalGeneric;
  724. InitAnsi;
  725. end;
  726. function SysErrorMessage(ErrorCode: Integer): String;
  727. begin
  728. Result:=StrError(ErrorCode);
  729. end;
  730. {****************************************************************************
  731. OS utility functions
  732. ****************************************************************************}
  733. Function GetEnvironmentVariable(Const EnvVar : String) : String;
  734. begin
  735. Result:=StrPas(BaseUnix.FPGetenv(PChar(EnvVar)));
  736. end;
  737. Function GetEnvironmentVariableCount : Integer;
  738. begin
  739. Result:=FPCCountEnvVar(EnvP);
  740. end;
  741. Function GetEnvironmentString(Index : Integer) : String;
  742. begin
  743. Result:=FPCGetEnvStrFromP(Envp,Index);
  744. end;
  745. {$define FPC_USE_FPEXEC} // leave the old code under IFDEF for a while.
  746. function ExecuteProcess(Const Path: AnsiString; Const ComLine: AnsiString):integer;
  747. var
  748. pid : longint;
  749. e : EOSError;
  750. CommandLine: AnsiString;
  751. cmdline2 : ppchar;
  752. Begin
  753. { always surround the name of the application by quotes
  754. so that long filenames will always be accepted. But don't
  755. do it if there are already double quotes!
  756. }
  757. {$ifdef FPC_USE_FPEXEC} // Only place we still parse
  758. cmdline2:=nil;
  759. if Comline<>'' Then
  760. begin
  761. CommandLine:=ComLine;
  762. { Make an unique copy because stringtoppchar modifies the
  763. string }
  764. UniqueString(CommandLine);
  765. cmdline2:=StringtoPPChar(CommandLine,1);
  766. cmdline2^:=pchar(Path);
  767. end
  768. else
  769. begin
  770. getmem(cmdline2,2*sizeof(pchar));
  771. cmdline2^:=pchar(Path);
  772. cmdline2[1]:=nil;
  773. end;
  774. {$else}
  775. if Pos ('"', Path) = 0 then
  776. CommandLine := '"' + Path + '"'
  777. else
  778. CommandLine := Path;
  779. if ComLine <> '' then
  780. CommandLine := Commandline + ' ' + ComLine;
  781. {$endif}
  782. {$ifdef USE_VFORK}
  783. pid:=fpvFork;
  784. {$else USE_VFORK}
  785. pid:=fpFork;
  786. {$endif USE_VFORK}
  787. if pid=0 then
  788. begin
  789. {The child does the actual exec, and then exits}
  790. {$ifdef FPC_USE_FPEXEC}
  791. fpexecv(pchar(Path),Cmdline2);
  792. {$else}
  793. Execl(CommandLine);
  794. {$endif}
  795. { If the execve fails, we return an exitvalue of 127, to let it be known}
  796. fpExit(127);
  797. end
  798. else
  799. if pid=-1 then {Fork failed}
  800. begin
  801. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  802. e.ErrorCode:=-1;
  803. raise e;
  804. end;
  805. { We're in the parent, let's wait. }
  806. result:=WaitProcess(pid); // WaitPid and result-convert
  807. if (result<0) or (result=127) then
  808. begin
  809. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  810. E.ErrorCode:=result;
  811. Raise E;
  812. end;
  813. End;
  814. function ExecuteProcess(Const Path: AnsiString; Const ComLine: Array Of AnsiString):integer;
  815. var
  816. pid : longint;
  817. e : EOSError;
  818. Begin
  819. pid:=fpFork;
  820. if pid=0 then
  821. begin
  822. {The child does the actual exec, and then exits}
  823. fpexecl(Path,Comline);
  824. { If the execve fails, we return an exitvalue of 127, to let it be known}
  825. fpExit(127);
  826. end
  827. else
  828. if pid=-1 then {Fork failed}
  829. begin
  830. e:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,-1]);
  831. e.ErrorCode:=-1;
  832. raise e;
  833. end;
  834. { We're in the parent, let's wait. }
  835. result:=WaitProcess(pid); // WaitPid and result-convert
  836. if (result<0) or (result=127) then
  837. begin
  838. E:=EOSError.CreateFmt(SExecuteProcessFailed,[Path,result]);
  839. E.ErrorCode:=result;
  840. raise E;
  841. end;
  842. End;
  843. procedure Sleep(milliseconds: Cardinal);
  844. Var
  845. timeout,timeoutresult : TTimespec;
  846. begin
  847. timeout.tv_sec:=milliseconds div 1000;
  848. timeout.tv_nsec:=1000*1000*(milliseconds mod 1000);
  849. fpnanosleep(@timeout,@timeoutresult);
  850. end;
  851. Function GetLastOSError : Integer;
  852. begin
  853. Result:=fpgetErrNo;
  854. end;
  855. { ---------------------------------------------------------------------
  856. Application config files
  857. ---------------------------------------------------------------------}
  858. Function GetHomeDir : String;
  859. begin
  860. Result:=GetEnvironmentVariable('HOME');
  861. If (Result<>'') then
  862. Result:=IncludeTrailingPathDelimiter(Result);
  863. end;
  864. { Follows base-dir spec,
  865. see [http://freedesktop.org/Standards/basedir-spec].
  866. Always ends with PathDelim. }
  867. Function XdgConfigHome : String;
  868. begin
  869. Result:=GetEnvironmentVariable('XDG_CONFIG_HOME');
  870. if (Result='') then
  871. Result:=GetHomeDir + '.config/'
  872. else
  873. Result:=IncludeTrailingPathDelimiter(Result);
  874. end;
  875. Function GetAppConfigDir(Global : Boolean) : String;
  876. begin
  877. If Global then
  878. Result:=SysConfigDir
  879. else
  880. Result:=XdgConfigHome + ApplicationName;
  881. end;
  882. Function GetAppConfigFile(Global : Boolean; SubDir : Boolean) : String;
  883. begin
  884. if Global then
  885. begin
  886. Result:=IncludeTrailingPathDelimiter(SysConfigDir);
  887. if SubDir then
  888. Result:=IncludeTrailingPathDelimiter(Result+ApplicationName);
  889. Result:=Result+ApplicationName+ConfigExtension;
  890. end
  891. else
  892. begin
  893. if SubDir then
  894. begin
  895. Result:=IncludeTrailingPathDelimiter(GetAppConfigDir(False));
  896. Result:=Result+ApplicationName+ConfigExtension;
  897. end
  898. else
  899. begin
  900. Result:=XdgConfigHome + ApplicationName + ConfigExtension;
  901. end;
  902. end;
  903. end;
  904. {****************************************************************************
  905. Initialization code
  906. ****************************************************************************}
  907. Function GetTempDir(Global : Boolean) : String;
  908. begin
  909. If Assigned(OnGetTempDir) then
  910. Result:=OnGetTempDir(Global)
  911. else
  912. begin
  913. Result:=GetEnvironmentVariable('TEMP');
  914. If (Result='') Then
  915. Result:=GetEnvironmentVariable('TMP');
  916. if (Result='') then
  917. Result:='/tmp/' // fallback.
  918. end;
  919. if (Result<>'') then
  920. Result:=IncludeTrailingPathDelimiter(Result);
  921. end;
  922. {****************************************************************************
  923. Initialization code
  924. ****************************************************************************}
  925. Initialization
  926. InitExceptions; { Initialize exceptions. OS independent }
  927. InitInternational; { Initialize internationalization settings }
  928. SysConfigDir:='/etc'; { Initialize system config dir }
  929. Finalization
  930. DoneExceptions;
  931. end.