sysutils.inc 19 KB

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