sysutils.inc 15 KB

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