sysutils.inc 16 KB

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