sysutils.inc 14 KB

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