sysutils.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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 CheckOSError(LastError: Integer);
  404. begin
  405. if LastError <> 0 then
  406. RaiseLastOSError(LastError);
  407. end;
  408. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  409. Var
  410. S : String;
  411. begin
  412. If Msg='' then
  413. S:=SAssertionFailed
  414. else
  415. S:=Msg;
  416. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  417. end;
  418. {$pop} //{$S-} for Error handling functions
  419. Procedure InitExceptions;
  420. {
  421. Must install uncaught exception handler (ExceptProc)
  422. and install exceptions for system exceptions or signals.
  423. (e.g: SIGSEGV -> ESegFault or so.)
  424. }
  425. begin
  426. ExceptionClass := Exception;
  427. ExceptProc:=@CatchUnhandledException;
  428. // Create objects that may have problems when there is no memory.
  429. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  430. OutOfMemory.AllowFree:=false;
  431. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  432. InvalidPointer.AllowFree:=false;
  433. AssertErrorProc:=@AssertErrorHandler;
  434. ErrorProc:=@RunErrorToExcept;
  435. OnShowException:=Nil;
  436. end;
  437. Procedure DoneExceptions;
  438. begin
  439. OutOfMemory.AllowFree:=true;
  440. OutOfMemory.Free;
  441. InValidPointer.AllowFree:=true;
  442. InValidPointer.Free;
  443. end;
  444. { Exception handling routines }
  445. function ExceptObject: TObject;
  446. begin
  447. If RaiseList=Nil then
  448. Result:=Nil
  449. else
  450. Result:=RaiseList^.FObject;
  451. end;
  452. function ExceptAddr: CodePointer;
  453. begin
  454. If RaiseList=Nil then
  455. Result:=Nil
  456. else
  457. Result:=RaiseList^.Addr;
  458. end;
  459. function ExceptFrameCount: Longint;
  460. begin
  461. If RaiseList=Nil then
  462. Result:=0
  463. else
  464. Result:=RaiseList^.Framecount;
  465. end;
  466. function ExceptFrames: PCodePointer;
  467. begin
  468. If RaiseList=Nil then
  469. Result:=Nil
  470. else
  471. Result:=RaiseList^.Frames;
  472. end;
  473. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  474. Buffer: PChar; Size: Integer): Integer;
  475. Var
  476. S : AnsiString;
  477. Len : Integer;
  478. begin
  479. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  480. If ExceptObject is Exception then
  481. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  482. Len:=Length(S);
  483. If S[Len]<>'.' then
  484. begin
  485. S:=S+'.';
  486. Inc(len);
  487. end;
  488. If Len>Size then
  489. Len:=Size;
  490. if Len > 0 then
  491. Move(S[1],Buffer^,Len);
  492. Result:=Len;
  493. end;
  494. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  495. // use shortstring. On exception, the heap may be corrupt.
  496. Var
  497. Buf : ShortString;
  498. begin
  499. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  500. If IsConsole Then
  501. writeln(Buf)
  502. else
  503. If Assigned(OnShowException) Then
  504. OnShowException (Buf);
  505. end;
  506. procedure Abort;
  507. begin
  508. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  509. end;
  510. procedure OutOfMemoryError;
  511. begin
  512. Raise OutOfMemory;
  513. end;
  514. { ---------------------------------------------------------------------
  515. Initialization/Finalization/exit code
  516. ---------------------------------------------------------------------}
  517. Type
  518. PPRecord = ^TPRecord;
  519. TPRecord = Record
  520. Func : TTerminateProc;
  521. NextFunc : PPRecord;
  522. end;
  523. Const
  524. TPList : PPRecord = Nil;
  525. procedure AddTerminateProc(TermProc: TTerminateProc);
  526. Var
  527. TPR : PPRecord;
  528. begin
  529. New(TPR);
  530. With TPR^ do
  531. begin
  532. NextFunc:=TPList;
  533. Func:=TermProc;
  534. end;
  535. TPList:=TPR;
  536. end;
  537. function CallTerminateProcs: Boolean;
  538. Var
  539. TPR : PPRecord;
  540. begin
  541. Result:=True;
  542. TPR:=TPList;
  543. While Result and (TPR<>Nil) do
  544. begin
  545. Result:=TPR^.Func();
  546. TPR:=TPR^.NextFunc;
  547. end;
  548. end;
  549. { ---------------------------------------------------------------------
  550. Diskh functions, OS independent.
  551. ---------------------------------------------------------------------}
  552. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  553. begin
  554. GetDir(0,Result);
  555. end;
  556. { ---------------------------------------------------------------------
  557. Other functions, OS independent.
  558. ---------------------------------------------------------------------}
  559. Var
  560. GUIDCalledRandomize : Boolean = False;
  561. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  562. Var
  563. I : Integer;
  564. P : PByte;
  565. begin
  566. P:=@Buf;
  567. If Not GUIDCalledRandomize then
  568. begin
  569. Randomize;
  570. GUIDCalledRandomize:=True;
  571. end;
  572. For I:=0 to NBytes-1 do
  573. P[i]:=Random(256);
  574. end;
  575. {$IFDEF HASCREATEGUID}
  576. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  577. {$ENDIF}
  578. Function CreateGUID(out GUID : TGUID) : Integer;
  579. begin
  580. If Assigned(OnCreateGUID) then
  581. Result:=OnCreateGUID(GUID)
  582. else
  583. begin
  584. {$IFDEF HASCREATEGUID}
  585. Result:=SysCreateGUID(GUID);
  586. {$ELSE}
  587. GetRandomBytes(GUID,SizeOf(Guid));
  588. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  589. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  590. Result:=0;
  591. {$ENDIF}
  592. end;
  593. end;
  594. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  595. {$if defined(win64) or defined(win32)}
  596. var
  597. mode : DWord;
  598. begin
  599. mode:=SetErrorMode(ErrorMode);
  600. try
  601. Result:=System.SafeLoadLibrary(FileName);
  602. finally
  603. SetErrorMode(mode);
  604. end;
  605. end;
  606. {$else}
  607. begin
  608. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  609. Result:=System.SafeLoadLibrary(FileName);
  610. {$else}
  611. Result:=HModule(nil);
  612. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  613. end;
  614. {$endif}
  615. {$if defined(win32) or defined(win64) or defined(wince)}
  616. function GetModuleName(Module: HMODULE): string;
  617. var
  618. ResultLength, BufferLength: DWORD;
  619. Buffer: UnicodeString;
  620. begin
  621. BufferLength := MAX_PATH div 2;
  622. repeat
  623. Inc(BufferLength, BufferLength);
  624. SetLength(Buffer, BufferLength);
  625. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  626. if ResultLength = 0 then
  627. Exit('');
  628. until ResultLength < BufferLength;
  629. SetLength(Buffer, ResultLength);
  630. Result := Buffer;
  631. end;
  632. {$elseif defined(win16)}
  633. function GetModuleName(Module: HMODULE): string;
  634. var
  635. ResultLength, BufferLength: DWORD;
  636. Buffer: RawByteString;
  637. begin
  638. BufferLength := MAX_PATH div 2;
  639. repeat
  640. Inc(BufferLength, BufferLength);
  641. SetLength(Buffer, BufferLength);
  642. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  643. if ResultLength = 0 then
  644. Exit('');
  645. until ResultLength < BufferLength;
  646. SetLength(Buffer, ResultLength);
  647. Result := Buffer;
  648. end;
  649. {$else}
  650. function GetModuleName(Module: HMODULE): string;
  651. begin
  652. Result:='';
  653. end;
  654. {$endif}
  655. { Beep support }
  656. procedure Beep;
  657. begin
  658. If Assigned(OnBeep) then
  659. OnBeep;
  660. end;
  661. // OSes that only provide 1 byte versions can enable the following define
  662. {$ifdef executeprocuni}
  663. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  664. begin
  665. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  666. end;
  667. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  668. var
  669. ComLineA : array of RawByteString;
  670. I : Integer;
  671. begin
  672. SetLength(ComLineA,high(comline)-low(comline)+1);
  673. For I:=0 to length(ComLineA)-1 Do
  674. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  675. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  676. end;
  677. {$endif}