sysutils.inc 19 KB

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