sysutils.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  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. 233 : E:=ENoWideStringSupport.Create(SMissingWStringManager);
  258. else
  259. E:=Exception.CreateFmt (SUnKnownRunTimeError,[Errno]);
  260. end;
  261. Raise E at Address,Frame;
  262. end;
  263. {$IFDEF HAS_OSERROR}
  264. Procedure RaiseLastOSError;
  265. var
  266. ECode: Cardinal;
  267. E : EOSError;
  268. begin
  269. ECode := GetLastOSError;
  270. If (ECode<>0) then
  271. E:=EOSError.CreateFmt(SOSError, [ECode, SysErrorMessage(ECode)])
  272. else
  273. E:=EOSError.Create(SUnkOSError);
  274. E.ErrorCode:=ECode;
  275. Raise E;
  276. end;
  277. {$else}
  278. Procedure RaiseLastOSError;
  279. begin
  280. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  281. end;
  282. {$endif}
  283. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  284. Var
  285. S : String;
  286. begin
  287. If Msg='' then
  288. S:=SAssertionFailed
  289. else
  290. S:=Msg;
  291. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at Pointer(theAddr);
  292. end;
  293. {$ifdef STACKCHECK_WAS_ON}
  294. {$S+}
  295. {$endif}
  296. Procedure InitExceptions;
  297. {
  298. Must install uncaught exception handler (ExceptProc)
  299. and install exceptions for system exceptions or signals.
  300. (e.g: SIGSEGV -> ESegFault or so.)
  301. }
  302. begin
  303. ExceptionClass := Exception;
  304. ExceptProc:=@CatchUnhandledException;
  305. // Create objects that may have problems when there is no memory.
  306. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  307. OutOfMemory.AllowFree:=false;
  308. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  309. InvalidPointer.AllowFree:=false;
  310. AssertErrorProc:=@AssertErrorHandler;
  311. ErrorProc:=@RunErrorToExcept;
  312. OnShowException:=Nil;
  313. end;
  314. Procedure DoneExceptions;
  315. begin
  316. OutOfMemory.AllowFree:=true;
  317. OutOfMemory.Free;
  318. InValidPointer.AllowFree:=true;
  319. InValidPointer.Free;
  320. end;
  321. { Exception handling routines }
  322. function ExceptObject: TObject;
  323. begin
  324. If RaiseList=Nil then
  325. Result:=Nil
  326. else
  327. Result:=RaiseList^.FObject;
  328. end;
  329. function ExceptAddr: Pointer;
  330. begin
  331. If RaiseList=Nil then
  332. Result:=Nil
  333. else
  334. Result:=RaiseList^.Addr;
  335. end;
  336. function ExceptFrameCount: Longint;
  337. begin
  338. If RaiseList=Nil then
  339. Result:=0
  340. else
  341. Result:=RaiseList^.Framecount;
  342. end;
  343. function ExceptFrames: PPointer;
  344. begin
  345. If RaiseList=Nil then
  346. Result:=Nil
  347. else
  348. Result:=RaiseList^.Frames;
  349. end;
  350. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  351. Buffer: PChar; Size: Integer): Integer;
  352. Var
  353. S : AnsiString;
  354. Len : Integer;
  355. begin
  356. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  357. If ExceptObject is Exception then
  358. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  359. Len:=Length(S);
  360. If S[Len]<>'.' then
  361. begin
  362. S:=S+'.';
  363. Inc(len);
  364. end;
  365. If Len>Size then
  366. Len:=Size;
  367. if Len > 0 then
  368. Move(S[1],Buffer^,Len);
  369. Result:=Len;
  370. end;
  371. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  372. // use shortstring. On exception, the heap may be corrupt.
  373. Var
  374. Buf : ShortString;
  375. begin
  376. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  377. If IsConsole Then
  378. writeln(Buf)
  379. else
  380. If Assigned(OnShowException) Then
  381. OnShowException (Buf);
  382. end;
  383. procedure Abort;
  384. begin
  385. Raise EAbort.Create(SAbortError) at Pointer(Get_Caller_addr(Get_Frame));
  386. end;
  387. procedure OutOfMemoryError;
  388. begin
  389. Raise OutOfMemory;
  390. end;
  391. { ---------------------------------------------------------------------
  392. Initialization/Finalization/exit code
  393. ---------------------------------------------------------------------}
  394. Type
  395. PPRecord = ^TPRecord;
  396. TPRecord = Record
  397. Func : TTerminateProc;
  398. NextFunc : PPRecord;
  399. end;
  400. Const
  401. TPList : PPRecord = Nil;
  402. procedure AddTerminateProc(TermProc: TTerminateProc);
  403. Var
  404. TPR : PPRecord;
  405. begin
  406. New(TPR);
  407. With TPR^ do
  408. begin
  409. NextFunc:=TPList;
  410. Func:=TermProc;
  411. end;
  412. TPList:=TPR;
  413. end;
  414. function CallTerminateProcs: Boolean;
  415. Var
  416. TPR : PPRecord;
  417. begin
  418. Result:=True;
  419. TPR:=TPList;
  420. While Result and (TPR<>Nil) do
  421. begin
  422. Result:=TPR^.Func();
  423. TPR:=TPR^.NextFunc;
  424. end;
  425. end;
  426. { ---------------------------------------------------------------------
  427. Diskh functions, OS independent.
  428. ---------------------------------------------------------------------}
  429. function ForceDirectories(Const Dir: string): Boolean;
  430. var
  431. E: EInOutError;
  432. ADrv : String;
  433. function DoForceDirectories(Const Dir: string): Boolean;
  434. var
  435. ADir : String;
  436. APath: String;
  437. begin
  438. Result:=True;
  439. ADir:=ExcludeTrailingPathDelimiter(Dir);
  440. if (ADir='') then Exit;
  441. if Not DirectoryExists(ADir) then
  442. begin
  443. APath := ExtractFilePath(ADir);
  444. //this can happen on Windows if user specifies Dir like \user\name/test/
  445. //and would, if not checked for, cause an infinite recusrsion and a stack overflow
  446. if (APath = ADir) then Result := False
  447. else Result:=DoForceDirectories(APath);
  448. If Result then
  449. Result := CreateDir(ADir);
  450. end;
  451. end;
  452. function IsUncDrive(const Drv: String): Boolean;
  453. begin
  454. Result := (Length(Drv) > 2) and (Drv[1] = PathDelim) and (Drv[2] = PathDelim);
  455. end;
  456. begin
  457. Result := False;
  458. ADrv := ExtractFileDrive(Dir);
  459. if (ADrv<>'') and (not DirectoryExists(ADrv))
  460. {$IFNDEF FORCEDIR_NO_UNC_SUPPORT} and (not IsUncDrive(ADrv)){$ENDIF} then Exit;
  461. if Dir='' then
  462. begin
  463. E:=EInOutError.Create(SCannotCreateEmptyDir);
  464. E.ErrorCode:=3;
  465. Raise E;
  466. end;
  467. Result := DoForceDirectories(SetDirSeparators(Dir));
  468. end;
  469. Var
  470. GUIDCalledRandomize : Boolean = False;
  471. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  472. Var
  473. I : Integer;
  474. P : PByte;
  475. begin
  476. P:=@Buf;
  477. If Not GUIDCalledRandomize then
  478. begin
  479. Randomize;
  480. GUIDCalledRandomize:=True;
  481. end;
  482. For I:=0 to NBytes-1 do
  483. P[i]:=Random(256);
  484. end;
  485. {$IFDEF HASCREATEGUID}
  486. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  487. {$ENDIF}
  488. Function CreateGUID(out GUID : TGUID) : Integer;
  489. begin
  490. If Assigned(OnCreateGUID) then
  491. Result:=OnCreateGUID(GUID)
  492. else
  493. begin
  494. {$IFDEF HASCREATEGUID}
  495. Result:=SysCreateGUID(GUID);
  496. {$ELSE}
  497. GetRandomBytes(GUID,SizeOf(Guid));
  498. Result:=0;
  499. {$ENDIF}
  500. end;
  501. end;
  502. function SafeLoadLibrary(const FileName: AnsiString;
  503. ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  504. {$if defined(cpui386) or defined(cpux86_64)}
  505. var
  506. mode : DWord;
  507. fpucw : Word;
  508. ssecw : DWord;
  509. {$endif}
  510. begin
  511. {$if defined(win64) or defined(win32)}
  512. mode:=SetErrorMode(ErrorMode);
  513. {$endif}
  514. try
  515. {$if defined(cpui386) or defined(cpux86_64)}
  516. fpucw:=Get8087CW;
  517. {$ifdef cpui386}
  518. if has_sse_support then
  519. {$endif cpui386}
  520. ssecw:=GetSSECSR;
  521. {$endif}
  522. {$if defined(windows) or defined(win32)}
  523. Result:=LoadLibraryA(PChar(Filename));
  524. {$else}
  525. Result:=0;
  526. {$endif}
  527. finally
  528. {$if defined(cpui386) or defined(cpux86_64)}
  529. Set8087CW(fpucw);
  530. {$ifdef cpui386}
  531. if has_sse_support then
  532. {$endif cpui386}
  533. SetSSECSR(ssecw);
  534. {$endif}
  535. {$if defined(win64) or defined(win32)}
  536. SetErrorMode(mode);
  537. {$endif}
  538. end;
  539. end;
  540. function GetModuleName(Module: HMODULE): string;
  541. begin
  542. {$ifdef MSWINDOWS}
  543. SetLength(Result,MAX_PATH);
  544. SetLength(Result,GetModuleFileName(Module, Pchar(Result),Length(Result)));
  545. {$ELSE}
  546. Result:='';
  547. {$ENDIF}
  548. end;