sysutils.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  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:=PUnicodeChar}
  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. {$i syshelp.inc}
  37. { strange Delphi thing }
  38. {$i sysmarshal.inc}
  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 : Int64) : 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 : Int64) : 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 PAnsiChar 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. function Exception.GetBaseException : Exception;
  204. var
  205. _ExceptObjectStack : PExceptObject;
  206. begin
  207. _ExceptObjectStack:=RaiseList;
  208. While Assigned(_ExceptObjectStack) do
  209. begin
  210. result:=Exception(_ExceptObjectStack^.FObject);
  211. _ExceptObjectStack:=_ExceptObjectStack^.Next;
  212. end;
  213. end;
  214. Constructor EVariantError.CreateCode (Code : longint);
  215. begin
  216. case Code of
  217. VAR_OK:
  218. Create(SNoError);
  219. VAR_PARAMNOTFOUND:
  220. Create(SVarParamNotFound);
  221. VAR_TYPEMISMATCH:
  222. Create(SInvalidVarCast);
  223. VAR_BADVARTYPE:
  224. Create(SVarBadType);
  225. VAR_OVERFLOW:
  226. Create(SVarOverflow);
  227. VAR_BADINDEX:
  228. Create(SVarArrayBounds);
  229. VAR_ARRAYISLOCKED:
  230. Create(SVarArrayLocked);
  231. VAR_NOTIMPL:
  232. Create(SVarNotImplemented);
  233. VAR_OUTOFMEMORY:
  234. Create(SVarOutOfMemory);
  235. VAR_INVALIDARG:
  236. Create(SVarInvalid);
  237. VAR_UNEXPECTED,
  238. VAR_EXCEPTION:
  239. Create(SVarUnexpected);
  240. else
  241. CreateFmt(SUnknownErrorCode,[Code]);
  242. end;
  243. ErrCode:=Code;
  244. end;
  245. {$if defined(win32) or defined(win64) or defined (wince)}
  246. function EExternal.GetExceptionRecord: PExceptionRecord;
  247. begin
  248. result:=@FExceptionRecord;
  249. end;
  250. {$endif win32 or win64 or wince}
  251. {$push}
  252. {$S-}
  253. Procedure CatchUnhandledException (Obj : TObject; Addr: CodePointer; FrameCount: Longint; Frames: PCodePointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  254. Var
  255. i : longint;
  256. hstdout : ^text;
  257. begin
  258. if WriteErrorsToStdErr then
  259. hstdout:=@stderr
  260. else
  261. hstdout:=@stdout;
  262. Writeln(hstdout^,'An unhandled exception occurred at $',HexStr(Addr),':');
  263. if Obj is exception then
  264. Writeln(hstdout^,Obj.ClassName,': ',Exception(Obj).Message)
  265. else if Obj is TObject then
  266. Writeln(hstdout^,'Exception object ',Obj.ClassName,' is not of class Exception.')
  267. else
  268. Writeln(hstdout^,'Exception object is not a valid class.');
  269. {$IFDEF HAS_OSERROR}
  270. {$IFDEF DEBUG_EXCEPTIONS_LASTOSERROR}
  271. WriteLn (HStdOut^, 'Last OS error detected in the RTL: ', GetLastOSError);
  272. {$ENDIF DEBUG_EXCEPTIONS_LASTOSERROR}
  273. {$ENDIF HAS_OSERROR}
  274. Writeln(hstdout^,BackTraceStrFunc(Addr));
  275. if (FrameCount>0) then
  276. begin
  277. for i:=0 to FrameCount-1 do
  278. Writeln(hstdout^,BackTraceStrFunc(Frames[i]));
  279. end;
  280. Writeln(hstdout^,'');
  281. end;
  282. type
  283. PExceptMapEntry=^TExceptMapEntry;
  284. TExceptMapEntry=record
  285. code: byte;
  286. cls: ExceptClass;
  287. {$IFDEF FPC_HAS_FEATURE_RESOURCES} // This is necessary for 2.4.4, which does not have reasources as a separate feature
  288. msg: PResStringRec;
  289. {$else FPC_HAS_FEATURE_RESOURCES}
  290. msg: PString;
  291. {$endif FPC_HAS_FEATURE_RESOURCES}
  292. end;
  293. const
  294. exceptmap: array[0..30] of TExceptMapEntry = (
  295. (code: 200; cls: EDivByZero; msg: @SDivByZero),
  296. (code: 201; cls: ERangeError; msg: @SRangeError),
  297. (code: 202; cls: EStackOverflow; msg: @SStackOverflow),
  298. (code: 205; cls: EOverflow; msg: @SOverflow),
  299. (code: 206; cls: EUnderflow; msg: @SUnderflow),
  300. (code: 207; cls: EInvalidOp; msg: @SInvalidOp),
  301. { Delphi distinguishes reDivByZero from reZeroDivide, but maps both to code 200. }
  302. (code: 208; cls: EZeroDivide; msg: @SZeroDivide),
  303. (code: 210; cls: EObjectCheck; msg: @SObjectCheckError),
  304. (code: 211; cls: EAbstractError; msg: @SAbstractError),
  305. (code: 212; cls: EExternalException; msg: @SExternalException),
  306. (code: 214; cls: EBusError; msg: @SBusError),
  307. (code: 215; cls: EIntOverflow; msg: @SIntOverflow),
  308. (code: 216; cls: EAccessViolation; msg: @SAccessViolation),
  309. (code: 217; cls: EControlC; msg: @SControlC),
  310. (code: 218; cls: EPrivilege; msg: @SPrivilege),
  311. (code: 219; cls: EInvalidCast; msg: @SInvalidCast),
  312. (code: 220; cls: EVariantError; msg: @SInvalidVarCast),
  313. (code: 221; cls: EVariantError; msg: @SInvalidVarOp),
  314. (code: 222; cls: EVariantError; msg: @SDispatchError),
  315. (code: 223; cls: EVariantError; msg: @SVarArrayCreate),
  316. (code: 224; cls: EVariantError; msg: @SVarNotArray),
  317. (code: 225; cls: EVariantError; msg: @SVarArrayBounds),
  318. (code: 227; cls: EAssertionFailed; msg: @SAssertionFailed),
  319. (code: 228; cls: EIntfCastError; msg: @SIntfCastError),
  320. (code: 229; cls: ESafecallException; msg: @SSafecallException),
  321. (code: 231; cls: EConvertError; msg: @SiconvError),
  322. (code: 232; cls: ENoThreadSupport; msg: @SNoThreadSupport),
  323. (code: 233; cls: ESigQuit; msg: @SSigQuit),
  324. (code: 234; cls: ENoWideStringSupport; msg: @SMissingWStringManager),
  325. (code: 235; cls: ENoDynLibsSupport; msg: @SNoDynLibsSupport),
  326. (code: 236; cls: EThreadError; msg: @SThreadError)
  327. );
  328. function FindExceptMapEntry(err: longint): PExceptMapEntry;
  329. var
  330. i: longint;
  331. begin
  332. for i:=low(exceptmap) to high(exceptmap) do
  333. if err=exceptmap[i].code then
  334. begin
  335. result:=@exceptmap[i];
  336. exit;
  337. end;
  338. result:=nil;
  339. end;
  340. Var OutOfMemory : EOutOfMemory;
  341. InValidPointer : EInvalidPointer;
  342. Procedure RunErrorToExcept (ErrNo : Longint; Address : CodePointer; Frame : Pointer);
  343. var
  344. E: Exception;
  345. HS: PString;
  346. Entry: PExceptMapEntry;
  347. begin
  348. Case Errno of
  349. 1,203 : E:=OutOfMemory;
  350. 204 : E:=InvalidPointer;
  351. else
  352. Entry:=FindExceptMapEntry(ErrNo);
  353. if Assigned(Entry) then
  354. E:=Entry^.cls.CreateRes(Entry^.msg)
  355. else
  356. begin
  357. HS:=nil;
  358. Case Errno of
  359. 2 : HS:=@SFileNotFound;
  360. 3 : HS:=@SInvalidFileName;
  361. 4 : HS:=@STooManyOpenFiles;
  362. 5 : HS:=@SAccessDenied;
  363. 6 : HS:=@SInvalidFileHandle;
  364. 15 : HS:=@SInvalidDrive;
  365. 100 : HS:=@SEndOfFile;
  366. 101 : HS:=@SDiskFull;
  367. 102 : HS:=@SFileNotAssigned;
  368. 103 : HS:=@SFileNotOpen;
  369. 104 : HS:=@SFileNotOpenForInput;
  370. 105 : HS:=@SFileNotOpenForOutput;
  371. 106 : HS:=@SInvalidInput;
  372. end;
  373. if Assigned(HS) then
  374. E:=EInOutError.CreateRes(HS)
  375. else
  376. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  377. // this routine can be called from FPC_IOCHECK,
  378. // which clears inoutres and then passes its
  379. // original value to HandleErrorFrame() (which calls
  380. // us). So use errno rather than IOResult, and clear
  381. // InOutRes explicitly in case we can also be called
  382. // from a place that does not clear InOutRes explicitly
  383. EInoutError(E).ErrorCode:=errno;
  384. inoutres:=0;
  385. end;
  386. end;
  387. Raise E at Address,Frame;
  388. end;
  389. {$IFDEF HAS_OSERROR}
  390. Procedure RaiseLastOSError;overload;
  391. begin
  392. RaiseLastOSError(GetLastOSError);
  393. end;
  394. Procedure RaiseLastOSError(LastError: Integer);overload;
  395. var
  396. E : EOSError;
  397. begin
  398. If (LastError<>0) then
  399. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  400. else
  401. E:=EOSError.Create(SUnkOSError);
  402. E.ErrorCode:=LastError;
  403. Raise E;
  404. end;
  405. {$else}
  406. Procedure RaiseLastOSError;overload;
  407. begin
  408. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  409. end;
  410. Procedure RaiseLastOSError(LastError: Integer);overload;
  411. begin
  412. RaiseLastOSError;
  413. end;
  414. {$endif}
  415. procedure CheckOSError(LastError: Integer);
  416. begin
  417. if LastError <> 0 then
  418. RaiseLastOSError(LastError);
  419. end;
  420. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  421. Var
  422. S : String;
  423. begin
  424. If Msg='' then
  425. S:=SAssertionFailed
  426. else
  427. S:=Msg;
  428. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  429. end;
  430. {$pop} //{$S-} for Error handling functions
  431. Procedure InitExceptions;
  432. {
  433. Must install uncaught exception handler (ExceptProc)
  434. and install exceptions for system exceptions or signals.
  435. (e.g: SIGSEGV -> ESegFault or so.)
  436. }
  437. begin
  438. ExceptionClass := Exception;
  439. ExceptProc:=@CatchUnhandledException;
  440. // Create objects that may have problems when there is no memory.
  441. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  442. OutOfMemory.AllowFree:=false;
  443. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  444. InvalidPointer.AllowFree:=false;
  445. AssertErrorProc:=@AssertErrorHandler;
  446. ErrorProc:=@RunErrorToExcept;
  447. OnShowException:=Nil;
  448. end;
  449. Procedure DoneExceptions;
  450. begin
  451. OutOfMemory.AllowFree:=true;
  452. OutOfMemory.Free;
  453. InValidPointer.AllowFree:=true;
  454. InValidPointer.Free;
  455. end;
  456. { Exception handling routines }
  457. function ExceptObject: TObject;
  458. begin
  459. If RaiseList=Nil then
  460. Result:=Nil
  461. else
  462. Result:=RaiseList^.FObject;
  463. end;
  464. function ExceptAddr: CodePointer;
  465. begin
  466. If RaiseList=Nil then
  467. Result:=Nil
  468. else
  469. Result:=RaiseList^.Addr;
  470. end;
  471. function ExceptFrameCount: Longint;
  472. begin
  473. If RaiseList=Nil then
  474. Result:=0
  475. else
  476. Result:=RaiseList^.Framecount;
  477. end;
  478. function ExceptFrames: PCodePointer;
  479. begin
  480. If RaiseList=Nil then
  481. Result:=Nil
  482. else
  483. Result:=RaiseList^.Frames;
  484. end;
  485. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  486. Buffer: PAnsiChar; Size: Integer): Integer;
  487. Var
  488. S : AnsiString;
  489. Len : Integer;
  490. begin
  491. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  492. If ExceptObject is Exception then
  493. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  494. Len:=Length(S);
  495. If S[Len]<>'.' then
  496. begin
  497. S:=S+'.';
  498. Inc(len);
  499. end;
  500. If Len>Size then
  501. Len:=Size;
  502. if Len > 0 then
  503. Move(S[1],Buffer^,Len);
  504. Result:=Len;
  505. end;
  506. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  507. // use shortstring. On exception, the heap may be corrupt.
  508. Var
  509. Buf : ShortString;
  510. begin
  511. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  512. If IsConsole Then
  513. writeln(Buf)
  514. else
  515. If Assigned(OnShowException) Then
  516. OnShowException (Buf);
  517. end;
  518. procedure Abort;
  519. begin
  520. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  521. end;
  522. procedure OutOfMemoryError;
  523. begin
  524. Raise OutOfMemory;
  525. end;
  526. { ---------------------------------------------------------------------
  527. Initialization/Finalization/exit code
  528. ---------------------------------------------------------------------}
  529. Type
  530. PPRecord = ^TPRecord;
  531. TPRecord = Record
  532. Func : TTerminateProc;
  533. NextFunc : PPRecord;
  534. end;
  535. Const
  536. TPList : PPRecord = Nil;
  537. procedure AddTerminateProc(TermProc: TTerminateProc);
  538. Var
  539. TPR : PPRecord;
  540. begin
  541. New(TPR);
  542. With TPR^ do
  543. begin
  544. NextFunc:=TPList;
  545. Func:=TermProc;
  546. end;
  547. TPList:=TPR;
  548. end;
  549. function CallTerminateProcs: Boolean;
  550. Var
  551. TPR : PPRecord;
  552. begin
  553. Result:=True;
  554. TPR:=TPList;
  555. While Result and (TPR<>Nil) do
  556. begin
  557. Result:=TPR^.Func();
  558. TPR:=TPR^.NextFunc;
  559. end;
  560. end;
  561. procedure FreeTerminateProcs;
  562. var
  563. TPR1, TPR2: PPRecord;
  564. begin
  565. TPR1 := TPList;
  566. TPList := Nil;
  567. while Assigned(TPR1) do begin
  568. TPR2 := TPR1^.NextFunc;
  569. Dispose(TPR1);
  570. TPR1 := TPR2;
  571. end;
  572. end;
  573. { ---------------------------------------------------------------------
  574. Diskh functions, OS independent.
  575. ---------------------------------------------------------------------}
  576. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  577. begin
  578. GetDir(0,Result);
  579. end;
  580. { ---------------------------------------------------------------------
  581. Other functions, OS independent.
  582. ---------------------------------------------------------------------}
  583. Var
  584. GUIDCalledRandomize : Boolean = False;
  585. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  586. Var
  587. I : Integer;
  588. P : PByte;
  589. begin
  590. P:=@Buf;
  591. If Not GUIDCalledRandomize then
  592. begin
  593. Randomize;
  594. GUIDCalledRandomize:=True;
  595. end;
  596. For I:=0 to NBytes-1 do
  597. P[i]:=Random(256);
  598. end;
  599. {$IFDEF HASCREATEGUID}
  600. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  601. {$ENDIF}
  602. Function CreateGUID(out GUID : TGUID) : Integer;
  603. begin
  604. If Assigned(OnCreateGUID) then
  605. Result:=OnCreateGUID(GUID)
  606. else
  607. begin
  608. {$IFDEF HASCREATEGUID}
  609. Result:=SysCreateGUID(GUID);
  610. {$ELSE}
  611. GetRandomBytes(GUID,SizeOf(Guid));
  612. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  613. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  614. Result:=0;
  615. {$ENDIF}
  616. end;
  617. end;
  618. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  619. {$if defined(win64) or defined(win32)}
  620. var
  621. mode : DWord;
  622. begin
  623. mode:=SetErrorMode(ErrorMode);
  624. try
  625. Result:=System.SafeLoadLibrary(FileName);
  626. finally
  627. SetErrorMode(mode);
  628. end;
  629. end;
  630. {$else}
  631. begin
  632. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  633. Result:=System.SafeLoadLibrary(FileName);
  634. {$else}
  635. Result:=HModule(nil);
  636. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  637. end;
  638. {$endif}
  639. {$if defined(win32) or defined(win64) or defined(wince)}
  640. function GetModuleName(Module: HMODULE): string;
  641. var
  642. ResultLength, BufferLength: DWORD;
  643. Buffer: UnicodeString;
  644. begin
  645. BufferLength := MAX_PATH div 2;
  646. repeat
  647. Inc(BufferLength, BufferLength);
  648. SetLength(Buffer, BufferLength);
  649. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  650. if ResultLength = 0 then
  651. Exit('');
  652. until ResultLength < BufferLength;
  653. SetLength(Buffer, ResultLength);
  654. Result := Buffer;
  655. end;
  656. {$elseif defined(win16)}
  657. function GetModuleName(Module: HMODULE): string;
  658. var
  659. ResultLength, BufferLength: DWORD;
  660. Buffer: RawByteString;
  661. begin
  662. BufferLength := MAX_PATH div 2;
  663. repeat
  664. Inc(BufferLength, BufferLength);
  665. SetLength(Buffer, BufferLength);
  666. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  667. if ResultLength = 0 then
  668. Exit('');
  669. until ResultLength < BufferLength;
  670. SetLength(Buffer, ResultLength);
  671. Result := Buffer;
  672. end;
  673. {$else}
  674. function GetModuleName(Module: HMODULE): string;
  675. begin
  676. Result:='';
  677. end;
  678. {$endif}
  679. { Beep support }
  680. procedure Beep;
  681. begin
  682. If Assigned(OnBeep) then
  683. OnBeep;
  684. end;
  685. // OSes that only provide 1 byte versions can enable the following define
  686. {$ifdef executeprocuni}
  687. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  688. begin
  689. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  690. end;
  691. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  692. var
  693. ComLineA : array of RawByteString;
  694. I : Integer;
  695. begin
  696. SetLength(ComLineA,high(comline)-low(comline)+1);
  697. For I:=0 to length(ComLineA)-1 Do
  698. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  699. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  700. end;
  701. {$endif}
  702. // generic ifthen..
  703. {$IFNDEF VER3_0}
  704. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  705. begin
  706. if val then
  707. Result := ifTrue
  708. else
  709. Result:=ifFalse;
  710. end;
  711. {$ENDIF}
  712. Function ArrayOfConstToStrArray(Args: array of const) : TUTF8StringDynArray;
  713. var
  714. i: Integer;
  715. O : TObject;
  716. C : TClass;
  717. S : String;
  718. begin
  719. SetLength(Result,Length(Args));
  720. for i:=Low(Args) to High(Args) do
  721. case Args[i].VType of
  722. vtInteger: Result[i]:=IntToStr(Args[i].VInteger);
  723. vtBoolean: Result[i]:=BoolToStr(Args[i].VBoolean);
  724. vtChar: Result[i] := Args[i].VChar;
  725. {$ifndef FPUNONE}
  726. vtExtended: Result[i]:= FloatToStr(Args[i].VExtended^);
  727. {$ENDIF}
  728. vtString: Result[i] := Args[i].VString^;
  729. vtPointer: Result[i] := '0x'+HexStr(PtrInt(Args[i].VPointer),SizeOF(PtrInt));
  730. vtPChar: Result[i] := Args[i].VPChar;
  731. vtObject:
  732. begin
  733. O:=Args[i].VObject;
  734. if Assigned(O) then
  735. begin
  736. try
  737. S:=O.ClassName;
  738. except
  739. S:='<Invalid instance>';
  740. end;
  741. end
  742. else
  743. S:='';
  744. Result[I] := '<Object '+S+' 0x'+HexStr(PtrInt(O),SizeOF(PtrInt))+'>';
  745. end;
  746. vtClass:
  747. begin
  748. C:=Args[i].VClass;
  749. if Assigned(C) then
  750. begin
  751. try
  752. S:=C.ClassName;
  753. except
  754. S:='<Invalid Class>';
  755. end;
  756. end
  757. else
  758. S:='';
  759. Result[I] := '<Class '+S+' 0x'+HexStr(PtrInt(C),SizeOF(PtrInt))+'>';
  760. end;
  761. vtWideChar: Result[i] := UTF8Encode(Args[i].VWideChar);
  762. vtPWideChar: Result[i] := UTF8Encode(Args[i].VPWideChar^);
  763. vtAnsiString: Result[i] := AnsiString(Args[i].VAnsiString);
  764. vtCurrency: Result[i] := FLoatToSTr(Args[i].VCurrency^);
  765. vtVariant: Result[i] := Args[i].VVariant^;
  766. vtInterface: Result[I] := '<Interface 0x'+HexStr(PtrInt(Args[i].VInterface),SizeOF(PtrInt))+'>';
  767. vtWidestring: Result[i] := UTF8ENcode(WideString(Args[i].VWideString));
  768. vtInt64: Result[i] := IntToStr(Args[i].VInt64^);
  769. vtQWord: Result[i] := IntToStr(Args[i].VQWord^);
  770. vtUnicodeString:Result[i] := UTF8Encode(UnicodeString(Args[i].VUnicodeString));
  771. end;
  772. end;
  773. Function ArrayOfConstToStr(Args: array of const ; aSeparator : Char = ','; aQuoteBegin : Char = '"'; aQuoteEnd : Char = '"') : UTF8String;
  774. Procedure Add(s: UTF8String);
  775. begin
  776. if aQuoteBegin<>#0 then
  777. S:=aQuoteBegin+S;
  778. if aQuoteEnd<>#0 then
  779. S:=S+aQuoteEnd;
  780. if Result<>'' then
  781. Result:=Result+aSeparator;
  782. Result:=Result+S;
  783. end;
  784. Var
  785. S : UTF8String;
  786. begin
  787. Result:='';
  788. For S in ArrayOfConstToStrArray(Args) do
  789. Add(S);
  790. end;