sysutils.inc 15 KB

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