sysutils.inc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  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..30] 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: ESigQuit; msg: @SSigQuit),
  313. (code: 234; cls: ENoWideStringSupport; msg: @SMissingWStringManager),
  314. (code: 235; cls: ENoDynLibsSupport; msg: @SNoDynLibsSupport),
  315. (code: 236; cls: EThreadError; msg: @SThreadError)
  316. );
  317. function FindExceptMapEntry(err: longint): PExceptMapEntry;
  318. var
  319. i: longint;
  320. begin
  321. for i:=low(exceptmap) to high(exceptmap) do
  322. if err=exceptmap[i].code then
  323. begin
  324. result:=@exceptmap[i];
  325. exit;
  326. end;
  327. result:=nil;
  328. end;
  329. Var OutOfMemory : EOutOfMemory;
  330. InValidPointer : EInvalidPointer;
  331. Procedure RunErrorToExcept (ErrNo : Longint; Address : CodePointer; Frame : Pointer);
  332. var
  333. E: Exception;
  334. HS: PString;
  335. Entry: PExceptMapEntry;
  336. begin
  337. Case Errno of
  338. 1,203 : E:=OutOfMemory;
  339. 204 : E:=InvalidPointer;
  340. else
  341. Entry:=FindExceptMapEntry(ErrNo);
  342. if Assigned(Entry) then
  343. E:=Entry^.cls.CreateRes(Entry^.msg)
  344. else
  345. begin
  346. HS:=nil;
  347. Case Errno of
  348. 2 : HS:=@SFileNotFound;
  349. 3 : HS:=@SInvalidFileName;
  350. 4 : HS:=@STooManyOpenFiles;
  351. 5 : HS:=@SAccessDenied;
  352. 6 : HS:=@SInvalidFileHandle;
  353. 15 : HS:=@SInvalidDrive;
  354. 100 : HS:=@SEndOfFile;
  355. 101 : HS:=@SDiskFull;
  356. 102 : HS:=@SFileNotAssigned;
  357. 103 : HS:=@SFileNotOpen;
  358. 104 : HS:=@SFileNotOpenForInput;
  359. 105 : HS:=@SFileNotOpenForOutput;
  360. 106 : HS:=@SInvalidInput;
  361. end;
  362. if Assigned(HS) then
  363. E:=EInOutError.CreateRes(HS)
  364. else
  365. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  366. // this routine can be called from FPC_IOCHECK,
  367. // which clears inoutres and then passes its
  368. // original value to HandleErrorFrame() (which calls
  369. // us). So use errno rather than IOResult, and clear
  370. // InOutRes explicitly in case we can also be called
  371. // from a place that does not clear InOutRes explicitly
  372. EInoutError(E).ErrorCode:=errno;
  373. inoutres:=0;
  374. end;
  375. end;
  376. Raise E at Address,Frame;
  377. end;
  378. {$IFDEF HAS_OSERROR}
  379. Procedure RaiseLastOSError;overload;
  380. begin
  381. RaiseLastOSError(GetLastOSError);
  382. end;
  383. Procedure RaiseLastOSError(LastError: Integer);overload;
  384. var
  385. E : EOSError;
  386. begin
  387. If (LastError<>0) then
  388. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  389. else
  390. E:=EOSError.Create(SUnkOSError);
  391. E.ErrorCode:=LastError;
  392. Raise E;
  393. end;
  394. {$else}
  395. Procedure RaiseLastOSError;overload;
  396. begin
  397. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  398. end;
  399. Procedure RaiseLastOSError(LastError: Integer);overload;
  400. begin
  401. RaiseLastOSError;
  402. end;
  403. {$endif}
  404. procedure CheckOSError(LastError: Integer);
  405. begin
  406. if LastError <> 0 then
  407. RaiseLastOSError(LastError);
  408. end;
  409. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  410. Var
  411. S : String;
  412. begin
  413. If Msg='' then
  414. S:=SAssertionFailed
  415. else
  416. S:=Msg;
  417. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  418. end;
  419. {$pop} //{$S-} for Error handling functions
  420. Procedure InitExceptions;
  421. {
  422. Must install uncaught exception handler (ExceptProc)
  423. and install exceptions for system exceptions or signals.
  424. (e.g: SIGSEGV -> ESegFault or so.)
  425. }
  426. begin
  427. ExceptionClass := Exception;
  428. ExceptProc:=@CatchUnhandledException;
  429. // Create objects that may have problems when there is no memory.
  430. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  431. OutOfMemory.AllowFree:=false;
  432. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  433. InvalidPointer.AllowFree:=false;
  434. AssertErrorProc:=@AssertErrorHandler;
  435. ErrorProc:=@RunErrorToExcept;
  436. OnShowException:=Nil;
  437. end;
  438. Procedure DoneExceptions;
  439. begin
  440. OutOfMemory.AllowFree:=true;
  441. OutOfMemory.Free;
  442. InValidPointer.AllowFree:=true;
  443. InValidPointer.Free;
  444. end;
  445. { Exception handling routines }
  446. function ExceptObject: TObject;
  447. begin
  448. If RaiseList=Nil then
  449. Result:=Nil
  450. else
  451. Result:=RaiseList^.FObject;
  452. end;
  453. function ExceptAddr: CodePointer;
  454. begin
  455. If RaiseList=Nil then
  456. Result:=Nil
  457. else
  458. Result:=RaiseList^.Addr;
  459. end;
  460. function ExceptFrameCount: Longint;
  461. begin
  462. If RaiseList=Nil then
  463. Result:=0
  464. else
  465. Result:=RaiseList^.Framecount;
  466. end;
  467. function ExceptFrames: PCodePointer;
  468. begin
  469. If RaiseList=Nil then
  470. Result:=Nil
  471. else
  472. Result:=RaiseList^.Frames;
  473. end;
  474. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  475. Buffer: PChar; Size: Integer): Integer;
  476. Var
  477. S : AnsiString;
  478. Len : Integer;
  479. begin
  480. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  481. If ExceptObject is Exception then
  482. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  483. Len:=Length(S);
  484. If S[Len]<>'.' then
  485. begin
  486. S:=S+'.';
  487. Inc(len);
  488. end;
  489. If Len>Size then
  490. Len:=Size;
  491. if Len > 0 then
  492. Move(S[1],Buffer^,Len);
  493. Result:=Len;
  494. end;
  495. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  496. // use shortstring. On exception, the heap may be corrupt.
  497. Var
  498. Buf : ShortString;
  499. begin
  500. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  501. If IsConsole Then
  502. writeln(Buf)
  503. else
  504. If Assigned(OnShowException) Then
  505. OnShowException (Buf);
  506. end;
  507. procedure Abort;
  508. begin
  509. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  510. end;
  511. procedure OutOfMemoryError;
  512. begin
  513. Raise OutOfMemory;
  514. end;
  515. { ---------------------------------------------------------------------
  516. Initialization/Finalization/exit code
  517. ---------------------------------------------------------------------}
  518. Type
  519. PPRecord = ^TPRecord;
  520. TPRecord = Record
  521. Func : TTerminateProc;
  522. NextFunc : PPRecord;
  523. end;
  524. Const
  525. TPList : PPRecord = Nil;
  526. procedure AddTerminateProc(TermProc: TTerminateProc);
  527. Var
  528. TPR : PPRecord;
  529. begin
  530. New(TPR);
  531. With TPR^ do
  532. begin
  533. NextFunc:=TPList;
  534. Func:=TermProc;
  535. end;
  536. TPList:=TPR;
  537. end;
  538. function CallTerminateProcs: Boolean;
  539. Var
  540. TPR : PPRecord;
  541. begin
  542. Result:=True;
  543. TPR:=TPList;
  544. While Result and (TPR<>Nil) do
  545. begin
  546. Result:=TPR^.Func();
  547. TPR:=TPR^.NextFunc;
  548. end;
  549. end;
  550. { ---------------------------------------------------------------------
  551. Diskh functions, OS independent.
  552. ---------------------------------------------------------------------}
  553. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  554. begin
  555. GetDir(0,Result);
  556. end;
  557. { ---------------------------------------------------------------------
  558. Other functions, OS independent.
  559. ---------------------------------------------------------------------}
  560. Var
  561. GUIDCalledRandomize : Boolean = False;
  562. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  563. Var
  564. I : Integer;
  565. P : PByte;
  566. begin
  567. P:=@Buf;
  568. If Not GUIDCalledRandomize then
  569. begin
  570. Randomize;
  571. GUIDCalledRandomize:=True;
  572. end;
  573. For I:=0 to NBytes-1 do
  574. P[i]:=Random(256);
  575. end;
  576. {$IFDEF HASCREATEGUID}
  577. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  578. {$ENDIF}
  579. Function CreateGUID(out GUID : TGUID) : Integer;
  580. begin
  581. If Assigned(OnCreateGUID) then
  582. Result:=OnCreateGUID(GUID)
  583. else
  584. begin
  585. {$IFDEF HASCREATEGUID}
  586. Result:=SysCreateGUID(GUID);
  587. {$ELSE}
  588. GetRandomBytes(GUID,SizeOf(Guid));
  589. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  590. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  591. Result:=0;
  592. {$ENDIF}
  593. end;
  594. end;
  595. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  596. {$if defined(win64) or defined(win32)}
  597. var
  598. mode : DWord;
  599. begin
  600. mode:=SetErrorMode(ErrorMode);
  601. try
  602. Result:=System.SafeLoadLibrary(FileName);
  603. finally
  604. SetErrorMode(mode);
  605. end;
  606. end;
  607. {$else}
  608. begin
  609. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  610. Result:=System.SafeLoadLibrary(FileName);
  611. {$else}
  612. Result:=HModule(nil);
  613. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  614. end;
  615. {$endif}
  616. {$if defined(win32) or defined(win64) or defined(wince)}
  617. function GetModuleName(Module: HMODULE): string;
  618. var
  619. ResultLength, BufferLength: DWORD;
  620. Buffer: UnicodeString;
  621. begin
  622. BufferLength := MAX_PATH div 2;
  623. repeat
  624. Inc(BufferLength, BufferLength);
  625. SetLength(Buffer, BufferLength);
  626. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  627. if ResultLength = 0 then
  628. Exit('');
  629. until ResultLength < BufferLength;
  630. SetLength(Buffer, ResultLength);
  631. Result := Buffer;
  632. end;
  633. {$elseif defined(win16)}
  634. function GetModuleName(Module: HMODULE): string;
  635. var
  636. ResultLength, BufferLength: DWORD;
  637. Buffer: RawByteString;
  638. begin
  639. BufferLength := MAX_PATH div 2;
  640. repeat
  641. Inc(BufferLength, BufferLength);
  642. SetLength(Buffer, BufferLength);
  643. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  644. if ResultLength = 0 then
  645. Exit('');
  646. until ResultLength < BufferLength;
  647. SetLength(Buffer, ResultLength);
  648. Result := Buffer;
  649. end;
  650. {$else}
  651. function GetModuleName(Module: HMODULE): string;
  652. begin
  653. Result:='';
  654. end;
  655. {$endif}
  656. { Beep support }
  657. procedure Beep;
  658. begin
  659. If Assigned(OnBeep) then
  660. OnBeep;
  661. end;
  662. // OSes that only provide 1 byte versions can enable the following define
  663. {$ifdef executeprocuni}
  664. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  665. begin
  666. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  667. end;
  668. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  669. var
  670. ComLineA : array of RawByteString;
  671. I : Integer;
  672. begin
  673. SetLength(ComLineA,high(comline)-low(comline)+1);
  674. For I:=0 to length(ComLineA)-1 Do
  675. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  676. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  677. end;
  678. {$endif}
  679. // generic ifthen..
  680. {$IFNDEF VER3_0}
  681. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  682. begin
  683. if val then
  684. Result := ifTrue
  685. else
  686. Result:=ifFalse;
  687. end;
  688. {$ENDIF}