sysutils.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. { Read filename handling functions implementation }
  12. {$i fina.inc}
  13. { variant error codes }
  14. {$i varerror.inc}
  15. Function FileSearch (Const Name, DirList : String; ImplicitCurrentDir : Boolean = True) : String;
  16. Var
  17. I : longint;
  18. Temp : String;
  19. begin
  20. Result:=Name;
  21. temp:=SetDirSeparators(DirList);
  22. // Start with checking the file in the current directory
  23. If ImplicitCurrentDir and (Result <> '') and FileExists(Result) Then
  24. exit;
  25. while True do begin
  26. If Temp = '' then
  27. Break; // No more directories to search - fail
  28. I:=pos(PathSeparator,Temp);
  29. If I<>0 then
  30. begin
  31. Result:=Copy (Temp,1,i-1);
  32. system.Delete(Temp,1,I);
  33. end
  34. else
  35. begin
  36. Result:=Temp;
  37. Temp:='';
  38. end;
  39. If Result<>'' then
  40. Result:=IncludeTrailingPathDelimiter(Result)+name;
  41. If (Result <> '') and FileExists(Result) Then
  42. exit;
  43. end;
  44. result:='';
  45. end;
  46. Function ExeSearch (Const Name, DirList : String) : String;
  47. begin
  48. {$ifdef unix}
  49. Result := FileSearch(Name, DirList, False);
  50. {$else unix}
  51. Result := FileSearch(Name, DirList, True);
  52. {$endif unix}
  53. end;
  54. {$ifndef OS_FILEISREADONLY}
  55. Function FileIsReadOnly(const FileName: String): Boolean;
  56. begin
  57. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  58. end;
  59. {$endif OS_FILEISREADONLY}
  60. {$ifndef OS_FILESETDATEBYNAME}
  61. Function FileSetDate (Const FileName : String;Age : Longint) : Longint;
  62. Var
  63. fd : THandle;
  64. begin
  65. { at least windows requires fmOpenWrite here }
  66. fd:=FileOpen(FileName,fmOpenWrite);
  67. If (Fd<>feInvalidHandle) then
  68. try
  69. Result:=FileSetDate(fd,Age);
  70. finally
  71. FileClose(fd);
  72. end
  73. else
  74. {$ifdef HAS_OSERROR}
  75. Result:=GetLastOSError;
  76. {$else}
  77. Result:=-1;
  78. {$endif}
  79. end;
  80. {$endif}
  81. { Read String Handling functions implementation }
  82. {$i sysstr.inc}
  83. { Read date & Time function implementations }
  84. {$ifndef FPUNONE}
  85. {$i dati.inc}
  86. {$endif}
  87. { Read pchar handling functions implementation }
  88. {$i syspch.inc}
  89. { generic internationalisation code }
  90. {$i sysint.inc}
  91. { MCBS functions }
  92. {$i sysansi.inc}
  93. { wide string functions }
  94. {$i syswide.inc}
  95. {$ifdef FPC_HAS_UNICODESTRING}
  96. { unicode string functions }
  97. {$i sysuni.inc}
  98. {$endif FPC_HAS_UNICODESTRING}
  99. { threading stuff }
  100. {$i sysuthrd.inc}
  101. { OS utility code }
  102. {$i osutil.inc}
  103. procedure FreeAndNil(var obj);
  104. var
  105. temp: tobject;
  106. begin
  107. temp:=tobject(obj);
  108. pointer(obj):=nil;
  109. temp.free;
  110. end;
  111. { Interfaces support }
  112. {$i sysuintf.inc}
  113. constructor Exception.Create(const msg : string);
  114. begin
  115. inherited create;
  116. fmessage:=msg;
  117. end;
  118. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  119. begin
  120. inherited create;
  121. fmessage:=Format(msg,args);
  122. end;
  123. constructor Exception.CreateRes(ResString: PString);
  124. begin
  125. inherited create;
  126. fmessage:=ResString^;
  127. end;
  128. constructor Exception.CreateResFmt(ResString: PString; const Args: array of const);
  129. begin
  130. inherited create;
  131. fmessage:=Format(ResString^,args);
  132. end;
  133. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Integer);
  134. begin
  135. inherited create;
  136. fmessage:=Msg;
  137. fhelpcontext:=AHelpContext;
  138. end;
  139. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  140. AHelpContext: Integer);
  141. begin
  142. inherited create;
  143. fmessage:=Format(Msg,args);
  144. fhelpcontext:=AHelpContext;
  145. end;
  146. constructor Exception.CreateResHelp(ResString: PString; AHelpContext: Integer);
  147. begin
  148. inherited create;
  149. fmessage:=ResString^;
  150. fhelpcontext:=AHelpContext;
  151. end;
  152. constructor Exception.CreateResFmtHelp(ResString: PString; const Args: array of const;
  153. AHelpContext: Integer);
  154. begin
  155. inherited create;
  156. fmessage:=Format(ResString^,args);
  157. fhelpcontext:=AHelpContext;
  158. end;
  159. procedure EHeapMemoryError.FreeInstance;
  160. begin
  161. if AllowFree then
  162. inherited FreeInstance;
  163. end;
  164. Constructor EVariantError.CreateCode (Code : longint);
  165. begin
  166. case Code of
  167. VAR_OK:
  168. Create(SNoError);
  169. VAR_PARAMNOTFOUND:
  170. Create(SVarParamNotFound);
  171. VAR_TYPEMISMATCH:
  172. Create(SInvalidVarCast);
  173. VAR_BADVARTYPE:
  174. Create(SVarBadType);
  175. VAR_OVERFLOW:
  176. Create(SVarOverflow);
  177. VAR_BADINDEX:
  178. Create(SVarArrayBounds);
  179. VAR_ARRAYISLOCKED:
  180. Create(SVarArrayLocked);
  181. VAR_NOTIMPL:
  182. Create(SVarNotImplemented);
  183. VAR_OUTOFMEMORY:
  184. Create(SVarOutOfMemory);
  185. VAR_INVALIDARG:
  186. Create(SVarInvalid);
  187. VAR_UNEXPECTED,
  188. VAR_EXCEPTION:
  189. Create(SVarUnexpected);
  190. else
  191. CreateFmt(SUnknownErrorCode,[Code]);
  192. end;
  193. ErrCode:=Code;
  194. end;
  195. {$ifopt S+}
  196. {$define STACKCHECK_WAS_ON}
  197. {$S-}
  198. {$endif OPT S }
  199. Procedure CatchUnhandledException (Obj : TObject; Addr: Pointer; FrameCount: Longint; Frames: PPointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  200. Var
  201. Message : String;
  202. i : longint;
  203. hstdout : ^text;
  204. begin
  205. hstdout:=@stdout;
  206. Writeln(hstdout^,'An unhandled exception occurred at $',HexStr(PtrUInt(Addr),sizeof(PtrUInt)*2),' :');
  207. if Obj is exception then
  208. begin
  209. Message:=Exception(Obj).ClassName+' : '+Exception(Obj).Message;
  210. Writeln(hstdout^,Message);
  211. end
  212. else
  213. Writeln(hstdout^,'Exception object ',Obj.ClassName,' is not of class Exception.');
  214. Writeln(hstdout^,BackTraceStrFunc(Addr));
  215. if (FrameCount>0) then
  216. begin
  217. for i:=0 to FrameCount-1 do
  218. Writeln(hstdout^,BackTraceStrFunc(Frames[i]));
  219. end;
  220. Writeln(hstdout^,'');
  221. end;
  222. Var OutOfMemory : EOutOfMemory;
  223. InValidPointer : EInvalidPointer;
  224. Procedure RunErrorToExcept (ErrNo : Longint; Address,Frame : Pointer);
  225. Var E : Exception;
  226. HS : PString;
  227. begin
  228. Case Errno of
  229. 1,203 : E:=OutOfMemory;
  230. 204 : E:=InvalidPointer;
  231. 2,3,4,5,6,100,101,102,103,105,106 : { I/O errors }
  232. begin
  233. Case Errno of
  234. 2 : HS:=@SFileNotFound;
  235. 3 : HS:=@SInvalidFileName;
  236. 4 : HS:=@STooManyOpenFiles;
  237. 5 : HS:=@SAccessDenied;
  238. 6 : HS:=@SInvalidFileHandle;
  239. 15 : HS:=@SInvalidDrive;
  240. 100 : HS:=@SEndOfFile;
  241. 101 : HS:=@SDiskFull;
  242. 102 : HS:=@SFileNotAssigned;
  243. 103 : HS:=@SFileNotOpen;
  244. 104 : HS:=@SFileNotOpenForInput;
  245. 105 : HS:=@SFileNotOpenForOutput;
  246. 106 : HS:=@SInvalidInput;
  247. end;
  248. E:=EinOutError.Create (HS^);
  249. // this routine can be called from FPC_IOCHECK,
  250. // which clears inoutres and then passes its
  251. // original value to HandleErrorFrame() (which calls
  252. // us). So use errno rather than IOResult, and clear
  253. // InOutRes explicitly in case we can also be called
  254. // from a place that does not clear InOutRes explicitly
  255. EInoutError(E).ErrorCode:=errno;
  256. inoutres:=0;
  257. end;
  258. // We don't set abstracterrorhandler, but we do it here.
  259. // Unless the use sets another handler we'll get here anyway...
  260. 200 : E:=EDivByZero.Create(SDivByZero);
  261. 201 : E:=ERangeError.Create(SRangeError);
  262. 205 : E:=EOverflow.Create(SOverflow);
  263. 206 : E:=EOverflow.Create(SUnderflow);
  264. 207 : E:=EInvalidOp.Create(SInvalidOp);
  265. 211 : E:=EAbstractError.Create(SAbstractError);
  266. 212 : E:=EExternalException.Create(SExternalException);
  267. 214 : E:=EBusError.Create(SBusError);
  268. 215 : E:=EIntOverflow.Create(SIntOverflow);
  269. 216 : E:=EAccessViolation.Create(SAccessViolation);
  270. 217 : E:=EControlC.Create(SControlC);
  271. 218 : E:=EPrivilege.Create(SPrivilege);
  272. 219 : E:=EInvalidCast.Create(SInvalidCast);
  273. 220 : E:=EVariantError.Create(SInvalidVarCast);
  274. 221 : E:=EVariantError.Create(SInvalidVarOp);
  275. 222 : E:=EVariantError.Create(SDispatchError);
  276. 223 : E:=EVariantError.Create(SVarArrayCreate);
  277. 224 : E:=EVariantError.Create(SVarNotArray);
  278. 225 : E:=EVariantError.Create(SVarArrayBounds);
  279. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  280. 228 : E:=EIntfCastError.Create(SIntfCastError);
  281. 229 : E:=ESafecallException.Create(SSafecallException);
  282. 231 : E:=EConvertError.Create(SiconvError);
  283. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  284. 233 : E:=ENoWideStringSupport.Create(SSigQuit);
  285. 234 : E:=ENoWideStringSupport.Create(SMissingWStringManager);
  286. else
  287. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  288. end;
  289. Raise E at Address,Frame;
  290. end;
  291. {$IFDEF HAS_OSERROR}
  292. Procedure RaiseLastOSError;
  293. var
  294. ECode: Cardinal;
  295. E : EOSError;
  296. begin
  297. ECode := GetLastOSError;
  298. If (ECode<>0) then
  299. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  300. else
  301. E:=EOSError.Create(SUnkOSError);
  302. E.ErrorCode:=ECode;
  303. Raise E;
  304. end;
  305. {$else}
  306. Procedure RaiseLastOSError;
  307. begin
  308. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  309. end;
  310. {$endif}
  311. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  312. Var
  313. S : String;
  314. begin
  315. If Msg='' then
  316. S:=SAssertionFailed
  317. else
  318. S:=Msg;
  319. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at Pointer(theAddr);
  320. end;
  321. {$ifdef STACKCHECK_WAS_ON}
  322. {$S+}
  323. {$endif}
  324. Procedure InitExceptions;
  325. {
  326. Must install uncaught exception handler (ExceptProc)
  327. and install exceptions for system exceptions or signals.
  328. (e.g: SIGSEGV -> ESegFault or so.)
  329. }
  330. begin
  331. ExceptionClass := Exception;
  332. ExceptProc:=@CatchUnhandledException;
  333. // Create objects that may have problems when there is no memory.
  334. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  335. OutOfMemory.AllowFree:=false;
  336. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  337. InvalidPointer.AllowFree:=false;
  338. AssertErrorProc:=@AssertErrorHandler;
  339. ErrorProc:=@RunErrorToExcept;
  340. OnShowException:=Nil;
  341. end;
  342. Procedure DoneExceptions;
  343. begin
  344. OutOfMemory.AllowFree:=true;
  345. OutOfMemory.Free;
  346. InValidPointer.AllowFree:=true;
  347. InValidPointer.Free;
  348. end;
  349. { Exception handling routines }
  350. function ExceptObject: TObject;
  351. begin
  352. If RaiseList=Nil then
  353. Result:=Nil
  354. else
  355. Result:=RaiseList^.FObject;
  356. end;
  357. function ExceptAddr: Pointer;
  358. begin
  359. If RaiseList=Nil then
  360. Result:=Nil
  361. else
  362. Result:=RaiseList^.Addr;
  363. end;
  364. function ExceptFrameCount: Longint;
  365. begin
  366. If RaiseList=Nil then
  367. Result:=0
  368. else
  369. Result:=RaiseList^.Framecount;
  370. end;
  371. function ExceptFrames: PPointer;
  372. begin
  373. If RaiseList=Nil then
  374. Result:=Nil
  375. else
  376. Result:=RaiseList^.Frames;
  377. end;
  378. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  379. Buffer: PChar; Size: Integer): Integer;
  380. Var
  381. S : AnsiString;
  382. Len : Integer;
  383. begin
  384. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  385. If ExceptObject is Exception then
  386. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  387. Len:=Length(S);
  388. If S[Len]<>'.' then
  389. begin
  390. S:=S+'.';
  391. Inc(len);
  392. end;
  393. If Len>Size then
  394. Len:=Size;
  395. if Len > 0 then
  396. Move(S[1],Buffer^,Len);
  397. Result:=Len;
  398. end;
  399. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  400. // use shortstring. On exception, the heap may be corrupt.
  401. Var
  402. Buf : ShortString;
  403. begin
  404. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  405. If IsConsole Then
  406. writeln(Buf)
  407. else
  408. If Assigned(OnShowException) Then
  409. OnShowException (Buf);
  410. end;
  411. procedure Abort;
  412. begin
  413. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  414. end;
  415. procedure OutOfMemoryError;
  416. begin
  417. Raise OutOfMemory;
  418. end;
  419. { ---------------------------------------------------------------------
  420. Initialization/Finalization/exit code
  421. ---------------------------------------------------------------------}
  422. Type
  423. PPRecord = ^TPRecord;
  424. TPRecord = Record
  425. Func : TTerminateProc;
  426. NextFunc : PPRecord;
  427. end;
  428. Const
  429. TPList : PPRecord = Nil;
  430. procedure AddTerminateProc(TermProc: TTerminateProc);
  431. Var
  432. TPR : PPRecord;
  433. begin
  434. New(TPR);
  435. With TPR^ do
  436. begin
  437. NextFunc:=TPList;
  438. Func:=TermProc;
  439. end;
  440. TPList:=TPR;
  441. end;
  442. function CallTerminateProcs: Boolean;
  443. Var
  444. TPR : PPRecord;
  445. begin
  446. Result:=True;
  447. TPR:=TPList;
  448. While Result and (TPR<>Nil) do
  449. begin
  450. Result:=TPR^.Func();
  451. TPR:=TPR^.NextFunc;
  452. end;
  453. end;
  454. { ---------------------------------------------------------------------
  455. Diskh functions, OS independent.
  456. ---------------------------------------------------------------------}
  457. function ForceDirectories(Const Dir: string): Boolean;
  458. var
  459. E: EInOutError;
  460. ADrv : String;
  461. function DoForceDirectories(Const Dir: string): Boolean;
  462. var
  463. ADir : String;
  464. APath: String;
  465. begin
  466. Result:=True;
  467. ADir:=ExcludeTrailingPathDelimiter(Dir);
  468. if (ADir='') then Exit;
  469. if Not DirectoryExists(ADir) then
  470. begin
  471. APath := ExtractFilePath(ADir);
  472. //this can happen on Windows if user specifies Dir like \user\name/test/
  473. //and would, if not checked for, cause an infinite recusrsion and a stack overflow
  474. if (APath = ADir) then Result := False
  475. else Result:=DoForceDirectories(APath);
  476. If Result then
  477. Result := CreateDir(ADir);
  478. end;
  479. end;
  480. function IsUncDrive(const Drv: String): Boolean;
  481. begin
  482. Result := (Length(Drv) > 2) and (Drv[1] = PathDelim) and (Drv[2] = PathDelim);
  483. end;
  484. begin
  485. Result := False;
  486. ADrv := ExtractFileDrive(Dir);
  487. if (ADrv<>'') and (not DirectoryExists(ADrv))
  488. {$IFNDEF FORCEDIR_NO_UNC_SUPPORT} and (not IsUncDrive(ADrv)){$ENDIF} then Exit;
  489. if Dir='' then
  490. begin
  491. E:=EInOutError.Create(SCannotCreateEmptyDir);
  492. E.ErrorCode:=3;
  493. Raise E;
  494. end;
  495. Result := DoForceDirectories(SetDirSeparators(Dir));
  496. end;
  497. Var
  498. GUIDCalledRandomize : Boolean = False;
  499. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  500. Var
  501. I : Integer;
  502. P : PByte;
  503. begin
  504. P:=@Buf;
  505. If Not GUIDCalledRandomize then
  506. begin
  507. Randomize;
  508. GUIDCalledRandomize:=True;
  509. end;
  510. For I:=0 to NBytes-1 do
  511. P[i]:=Random(256);
  512. end;
  513. {$IFDEF HASCREATEGUID}
  514. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  515. {$ENDIF}
  516. Function CreateGUID(out GUID : TGUID) : Integer;
  517. begin
  518. If Assigned(OnCreateGUID) then
  519. Result:=OnCreateGUID(GUID)
  520. else
  521. begin
  522. {$IFDEF HASCREATEGUID}
  523. Result:=SysCreateGUID(GUID);
  524. {$ELSE}
  525. GetRandomBytes(GUID,SizeOf(Guid));
  526. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  527. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  528. Result:=0;
  529. {$ENDIF}
  530. end;
  531. end;
  532. function SafeLoadLibrary(const FileName: AnsiString;
  533. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  534. {$if defined(cpui386) or defined(cpux86_64)}
  535. var
  536. mode : DWord;
  537. fpucw : Word;
  538. ssecw : DWord;
  539. {$endif}
  540. begin
  541. {$if defined(win64) or defined(win32)}
  542. mode:=SetErrorMode(ErrorMode);
  543. {$endif}
  544. try
  545. {$if defined(cpui386) or defined(cpux86_64)}
  546. fpucw:=Get8087CW;
  547. {$ifdef cpui386}
  548. if has_sse_support then
  549. {$endif cpui386}
  550. ssecw:=GetSSECSR;
  551. {$endif}
  552. {$if defined(windows) or defined(win32)}
  553. Result:=LoadLibraryA(PChar(Filename));
  554. {$else}
  555. Result:=0;
  556. {$endif}
  557. finally
  558. {$if defined(cpui386) or defined(cpux86_64)}
  559. Set8087CW(fpucw);
  560. {$ifdef cpui386}
  561. if has_sse_support then
  562. {$endif cpui386}
  563. SetSSECSR(ssecw);
  564. {$endif}
  565. {$if defined(win64) or defined(win32)}
  566. SetErrorMode(mode);
  567. {$endif}
  568. end;
  569. end;
  570. function GetModuleName(Module: HMODULE): string;
  571. begin
  572. {$ifdef MSWINDOWS}
  573. SetLength(Result,MAX_PATH);
  574. SetLength(Result,GetModuleFileName(Module, Pchar(Result),Length(Result)));
  575. {$ELSE}
  576. Result:='';
  577. {$ENDIF}
  578. end;
  579. { Beep support }
  580. procedure Beep;
  581. begin
  582. If Assigned(OnBeep) then
  583. OnBeep;
  584. end;