sysutils.pp 34 KB

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