sysutils.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. EInoutError(E).ErrorCode:=IOresult; // Clears InOutRes !!
  230. end;
  231. // We don't set abstracterrorhandler, but we do it here.
  232. // Unless the use sets another handler we'll get here anyway...
  233. 200 : E:=EDivByZero.Create(SDivByZero);
  234. 201 : E:=ERangeError.Create(SRangeError);
  235. 205 : E:=EOverflow.Create(SOverflow);
  236. 206 : E:=EOverflow.Create(SUnderflow);
  237. 207 : E:=EInvalidOp.Create(SInvalidOp);
  238. 211 : E:=EAbstractError.Create(SAbstractError);
  239. 212 : E:=EExternalException.Create(SExternalException);
  240. 214 : E:=EBusError.Create(SBusError);
  241. 215 : E:=EIntOverflow.Create(SIntOverflow);
  242. 216 : E:=EAccessViolation.Create(SAccessViolation);
  243. 217 : E:=EControlC.Create(SControlC);
  244. 218 : E:=EPrivilege.Create(SPrivilege);
  245. 219 : E:=EInvalidCast.Create(SInvalidCast);
  246. 220 : E:=EVariantError.Create(SInvalidVarCast);
  247. 221 : E:=EVariantError.Create(SInvalidVarOp);
  248. 222 : E:=EVariantError.Create(SDispatchError);
  249. 223 : E:=EVariantError.Create(SVarArrayCreate);
  250. 224 : E:=EVariantError.Create(SVarNotArray);
  251. 225 : E:=EVariantError.Create(SVarArrayBounds);
  252. 227 : E:=EAssertionFailed.Create(SAssertionFailed);
  253. 228 : E:=EIntfCastError.Create(SIntfCastError);
  254. 229 : E:=ESafecallException.Create(SSafecallException);
  255. 231 : E:=EConvertError.Create(SiconvError);
  256. 232 : E:=ENoThreadSupport.Create(SNoThreadSupport);
  257. else
  258. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  259. end;
  260. Raise E at Address,Frame;
  261. end;
  262. {$IFDEF HAS_OSERROR}
  263. Procedure RaiseLastOSError;
  264. var
  265. ECode: Cardinal;
  266. E : EOSError;
  267. begin
  268. ECode := GetLastOSError;
  269. If (ECode<>0) then
  270. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  271. else
  272. E:=EOSError.Create(SUnkOSError);
  273. E.ErrorCode:=ECode;
  274. Raise E;
  275. end;
  276. {$else}
  277. Procedure RaiseLastOSError;
  278. begin
  279. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  280. end;
  281. {$endif}
  282. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  283. Var
  284. S : String;
  285. begin
  286. If Msg='' then
  287. S:=SAssertionFailed
  288. else
  289. S:=Msg;
  290. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at Pointer(theAddr);
  291. end;
  292. {$ifdef STACKCHECK_WAS_ON}
  293. {$S+}
  294. {$endif}
  295. Procedure InitExceptions;
  296. {
  297. Must install uncaught exception handler (ExceptProc)
  298. and install exceptions for system exceptions or signals.
  299. (e.g: SIGSEGV -> ESegFault or so.)
  300. }
  301. begin
  302. ExceptionClass := Exception;
  303. ExceptProc:=@CatchUnhandledException;
  304. // Create objects that may have problems when there is no memory.
  305. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  306. OutOfMemory.AllowFree:=false;
  307. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  308. InvalidPointer.AllowFree:=false;
  309. AssertErrorProc:=@AssertErrorHandler;
  310. ErrorProc:=@RunErrorToExcept;
  311. OnShowException:=Nil;
  312. end;
  313. Procedure DoneExceptions;
  314. begin
  315. OutOfMemory.AllowFree:=true;
  316. OutOfMemory.Free;
  317. InValidPointer.AllowFree:=true;
  318. InValidPointer.Free;
  319. end;
  320. { Exception handling routines }
  321. function ExceptObject: TObject;
  322. begin
  323. If RaiseList=Nil then
  324. Result:=Nil
  325. else
  326. Result:=RaiseList^.FObject;
  327. end;
  328. function ExceptAddr: Pointer;
  329. begin
  330. If RaiseList=Nil then
  331. Result:=Nil
  332. else
  333. Result:=RaiseList^.Addr;
  334. end;
  335. function ExceptFrameCount: Longint;
  336. begin
  337. If RaiseList=Nil then
  338. Result:=0
  339. else
  340. Result:=RaiseList^.Framecount;
  341. end;
  342. function ExceptFrames: PPointer;
  343. begin
  344. If RaiseList=Nil then
  345. Result:=Nil
  346. else
  347. Result:=RaiseList^.Frames;
  348. end;
  349. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  350. Buffer: PChar; Size: Integer): Integer;
  351. Var
  352. S : AnsiString;
  353. Len : Integer;
  354. begin
  355. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  356. If ExceptObject is Exception then
  357. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  358. Len:=Length(S);
  359. If S[Len]<>'.' then
  360. begin
  361. S:=S+'.';
  362. Inc(len);
  363. end;
  364. If Len>Size then
  365. Len:=Size;
  366. if Len > 0 then
  367. Move(S[1],Buffer^,Len);
  368. Result:=Len;
  369. end;
  370. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  371. // use shortstring. On exception, the heap may be corrupt.
  372. Var
  373. Buf : ShortString;
  374. begin
  375. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  376. If IsConsole Then
  377. writeln(Buf)
  378. else
  379. If Assigned(OnShowException) Then
  380. OnShowException (Buf);
  381. end;
  382. procedure Abort;
  383. begin
  384. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  385. end;
  386. procedure OutOfMemoryError;
  387. begin
  388. Raise OutOfMemory;
  389. end;
  390. { ---------------------------------------------------------------------
  391. Initialization/Finalization/exit code
  392. ---------------------------------------------------------------------}
  393. Type
  394. PPRecord = ^TPRecord;
  395. TPRecord = Record
  396. Func : TTerminateProc;
  397. NextFunc : PPRecord;
  398. end;
  399. Const
  400. TPList : PPRecord = Nil;
  401. procedure AddTerminateProc(TermProc: TTerminateProc);
  402. Var
  403. TPR : PPRecord;
  404. begin
  405. New(TPR);
  406. With TPR^ do
  407. begin
  408. NextFunc:=TPList;
  409. Func:=TermProc;
  410. end;
  411. TPList:=TPR;
  412. end;
  413. function CallTerminateProcs: Boolean;
  414. Var
  415. TPR : PPRecord;
  416. begin
  417. Result:=True;
  418. TPR:=TPList;
  419. While Result and (TPR<>Nil) do
  420. begin
  421. Result:=TPR^.Func();
  422. TPR:=TPR^.NextFunc;
  423. end;
  424. end;
  425. { ---------------------------------------------------------------------
  426. Diskh functions, OS independent.
  427. ---------------------------------------------------------------------}
  428. function ForceDirectories(Const Dir: string): Boolean;
  429. var
  430. E: EInOutError;
  431. ADrv : String;
  432. function DoForceDirectories(Const Dir: string): Boolean;
  433. var
  434. ADir : String;
  435. begin
  436. Result:=True;
  437. ADir:=ExcludeTrailingPathDelimiter(Dir);
  438. if (ADir='') then Exit;
  439. if Not DirectoryExists(ADir) then
  440. begin
  441. Result:=DoForceDirectories(ExtractFilePath(ADir));
  442. If Result then
  443. Result := CreateDir(ADir);
  444. end;
  445. end;
  446. begin
  447. Result := False;
  448. ADrv := ExtractFileDrive(Dir);
  449. if (ADrv<>'') and (not DirectoryExists(ADrv)) then Exit;
  450. if Dir='' then
  451. begin
  452. E:=EInOutError.Create(SCannotCreateEmptyDir);
  453. E.ErrorCode:=3;
  454. Raise E;
  455. end;
  456. Result := DoForceDirectories(SetDirSeparators(Dir));
  457. end;
  458. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  459. Var
  460. I : Integer;
  461. P : PByte;
  462. begin
  463. P:=@Buf;
  464. Randomize;
  465. For I:=0 to NBytes-1 do
  466. P[i]:=Random(256);
  467. end;
  468. {$IFDEF HASCREATEGUID}
  469. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  470. {$ENDIF}
  471. Function CreateGUID(out GUID : TGUID) : Integer;
  472. begin
  473. If Assigned(OnCreateGUID) then
  474. Result:=OnCreateGUID(GUID)
  475. else
  476. begin
  477. {$IFDEF HASCREATEGUID}
  478. Result:=SysCreateGUID(GUID);
  479. {$ELSE}
  480. GetRandomBytes(GUID,SizeOf(Guid));
  481. Result:=0;
  482. {$ENDIF}
  483. end;
  484. end;
  485. function SafeLoadLibrary(const FileName: AnsiString;
  486. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  487. {$if defined(cpui386) or defined(cpux86_64)}
  488. var
  489. mode : DWord;
  490. fpucw : Word;
  491. ssecw : DWord;
  492. {$endif}
  493. begin
  494. {$if defined(win64) or defined(win32)}
  495. mode:=SetErrorMode(ErrorMode);
  496. {$endif}
  497. try
  498. {$if defined(cpui386) or defined(cpux86_64)}
  499. fpucw:=Get8087CW;
  500. {$ifdef cpui386}
  501. if has_sse_support then
  502. {$endif cpui386}
  503. ssecw:=GetSSECSR;
  504. {$endif}
  505. {$if defined(windows) or defined(win32)}
  506. Result:=LoadLibraryA(PChar(Filename));
  507. {$else}
  508. Result:=0;
  509. {$endif}
  510. finally
  511. {$if defined(cpui386) or defined(cpux86_64)}
  512. Set8087CW(fpucw);
  513. {$ifdef cpui386}
  514. if has_sse_support then
  515. {$endif cpui386}
  516. SetSSECSR(ssecw);
  517. {$endif}
  518. {$if defined(win64) or defined(win32)}
  519. SetErrorMode(mode);
  520. {$endif}
  521. end;
  522. end;
  523. function GetModuleName(Module: HMODULE): string;
  524. begin
  525. {$ifdef MSWINDOWS}
  526. SetLength(Result,MAX_PATH);
  527. SetLength(Result,GetModuleFileName(Module, Pchar(Result),Length(Result)));
  528. {$ELSE}
  529. Result:='';
  530. {$ENDIF}
  531. end;