sysutils.inc 15 KB

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