sysutils.inc 19 KB

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