sysutils.inc 16 KB

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