sysutils.inc 19 KB

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