sysutils.inc 16 KB

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