sysutils.pp 25 KB

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