sysutils.inc 16 KB

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