sysutils.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. {%MainUnit sysutils.pp}
  2. {
  3. This file is part of the Free Pascal run time library.
  4. Copyright (c) 1999-2000 by Florian Klaempfl
  5. member of the Free Pascal development team
  6. See the file COPYING.FPC, included in this distribution,
  7. for details about the copyright.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  11. **********************************************************************}
  12. { MCBS functions }
  13. {$i sysansi.inc}
  14. {$i syscodepages.inc}
  15. {$macro on}
  16. {$define PathStr:=UnicodeString}
  17. {$define PathPChar:=PUnicodeChar}
  18. {$define SYSUTILSUNICODE}
  19. { Read filename handling functions implementation }
  20. {$i fina.inc}
  21. { Read disk function implementations }
  22. {$i disk.inc}
  23. {$undef SYSUTILSUNICODE}
  24. {$define PathStr:=RawByteString}
  25. {$define PathPChar:=PAnsiChar}
  26. { Read filename handling functions implementation }
  27. {$i fina.inc}
  28. { Read disk function implementations }
  29. {$i disk.inc}
  30. {$undef PathStr}
  31. {$undef PathPChar}
  32. { Read file utility functions implementation }
  33. {$i filutil.inc}
  34. { variant error codes }
  35. {$i varerror.inc}
  36. { Type helpers}
  37. {$i syshelp.inc}
  38. { strange Delphi thing }
  39. {$i sysmarshal.inc}
  40. {$ifndef OS_FILEISREADONLY}
  41. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  42. begin
  43. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  44. end;
  45. Function FileIsReadOnly(const FileName: UnicodeString): Boolean;
  46. begin
  47. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  48. end;
  49. {$endif OS_FILEISREADONLY}
  50. {$ifndef OS_FILESETDATEBYNAME}
  51. Function FileSetDate (Const FileName : RawByteString;Age : Int64) : Longint;
  52. Var
  53. fd : THandle;
  54. begin
  55. { at least windows requires fmOpenWrite here }
  56. fd:=FileOpen(FileName,fmOpenWrite);
  57. If (Fd<>feInvalidHandle) then
  58. try
  59. Result:=FileSetDate(fd,Age);
  60. finally
  61. FileClose(fd);
  62. end
  63. else
  64. {$ifdef HAS_OSERROR}
  65. Result:=GetLastOSError;
  66. {$else}
  67. Result:=-1;
  68. {$endif}
  69. end;
  70. Function FileSetDate (Const FileName : UnicodeString;Age : Int64) : Longint;
  71. Var
  72. fd : THandle;
  73. begin
  74. { at least windows requires fmOpenWrite here }
  75. fd:=FileOpen(FileName,fmOpenWrite);
  76. If (Fd<>feInvalidHandle) then
  77. try
  78. Result:=FileSetDate(fd,Age);
  79. finally
  80. FileClose(fd);
  81. end
  82. else
  83. {$ifdef HAS_OSERROR}
  84. Result:=GetLastOSError;
  85. {$else}
  86. Result:=-1;
  87. {$endif}
  88. end;
  89. {$endif}
  90. { Read String Handling functions implementation }
  91. {$i sysstr.inc}
  92. { Read date & Time function implementations }
  93. {$ifndef FPUNONE}
  94. {$i dati.inc}
  95. {$endif}
  96. {$IFNDEF HAS_GETTICKCOUNT}
  97. function GetTickCount: LongWord;
  98. begin
  99. Result := LongWord(GetTickCount64);
  100. end;
  101. {$ENDIF}
  102. {$IFNDEF HAS_GETTICKCOUNT64}
  103. function GetTickCount64: QWord;
  104. begin
  105. {$IFDEF FPU_NONE}
  106. {$IFDEF HAS_SYSTIMERTICK}
  107. Result := SysTimerTick;
  108. {$ELSE}
  109. Result := 0;
  110. {$ENDIF}
  111. {$ELSE}
  112. Result := Trunc(Now * 24 * 60 * 60 * 1000);
  113. {$ENDIF}
  114. end;
  115. {$ENDIF}
  116. { Read PAnsiChar handling functions implementation }
  117. {$i syspch.inc}
  118. { generic internationalisation code }
  119. {$i sysint.inc}
  120. { wide string functions }
  121. {$i syswide.inc}
  122. {$ifdef FPC_HAS_UNICODESTRING}
  123. { unicode string functions }
  124. {$i sysuni.inc}
  125. {$i sysencoding.inc}
  126. {$endif FPC_HAS_UNICODESTRING}
  127. { threading stuff }
  128. {$i sysuthrd.inc}
  129. { OS utility code }
  130. {$i osutil.inc}
  131. procedure FreeAndNil(var obj);
  132. var
  133. temp: tobject;
  134. begin
  135. temp:=tobject(obj);
  136. pointer(obj):=nil;
  137. temp.free;
  138. end;
  139. procedure FreeMemAndNil(var p);
  140. var
  141. temp:Pointer;
  142. begin
  143. temp := Pointer(p);
  144. Pointer(P):=nil;
  145. FreeMem(temp);
  146. end;
  147. { Interfaces support }
  148. {$i sysuintf.inc}
  149. constructor Exception.Create(const msg : string);
  150. begin
  151. inherited create;
  152. fmessage:=msg;
  153. end;
  154. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  155. begin
  156. inherited create;
  157. fmessage:=Format(msg,args);
  158. end;
  159. constructor Exception.CreateRes(ResString: PAnsiString);
  160. begin
  161. inherited create;
  162. fmessage:=ResString^;
  163. end;
  164. constructor Exception.CreateResFmt(ResString: PAnsiString; const Args: array of const);
  165. begin
  166. inherited create;
  167. fmessage:=Format(ResString^,args);
  168. end;
  169. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Longint);
  170. begin
  171. inherited create;
  172. fmessage:=Msg;
  173. fhelpcontext:=AHelpContext;
  174. end;
  175. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  176. AHelpContext: Longint);
  177. begin
  178. inherited create;
  179. fmessage:=Format(Msg,args);
  180. fhelpcontext:=AHelpContext;
  181. end;
  182. constructor Exception.CreateResHelp(ResString: PAnsiString; AHelpContext: Longint);
  183. begin
  184. inherited create;
  185. fmessage:=ResString^;
  186. fhelpcontext:=AHelpContext;
  187. end;
  188. constructor Exception.CreateResFmtHelp(ResString: PAnsiString; const Args: array of const;
  189. AHelpContext: Longint);
  190. begin
  191. inherited create;
  192. fmessage:=Format(ResString^,args);
  193. fhelpcontext:=AHelpContext;
  194. end;
  195. Function Exception.ToString : RTLString;
  196. begin
  197. Result:=ClassName+': '+Message;
  198. end;
  199. procedure EHeapMemoryError.FreeInstance;
  200. begin
  201. if AllowFree then
  202. inherited FreeInstance;
  203. end;
  204. function Exception.GetBaseException : Exception;
  205. var
  206. _ExceptObjectStack : PExceptObject;
  207. begin
  208. _ExceptObjectStack:=RaiseList;
  209. While Assigned(_ExceptObjectStack) do
  210. begin
  211. result:=Exception(_ExceptObjectStack^.FObject);
  212. _ExceptObjectStack:=_ExceptObjectStack^.Next;
  213. end;
  214. end;
  215. Constructor EVariantError.CreateCode (Code : longint);
  216. begin
  217. case Code of
  218. VAR_OK:
  219. Create(SNoError);
  220. VAR_PARAMNOTFOUND:
  221. Create(SVarParamNotFound);
  222. VAR_TYPEMISMATCH:
  223. Create(SInvalidVarCast);
  224. VAR_BADVARTYPE:
  225. Create(SVarBadType);
  226. VAR_OVERFLOW:
  227. Create(SVarOverflow);
  228. VAR_BADINDEX:
  229. Create(SVarArrayBounds);
  230. VAR_ARRAYISLOCKED:
  231. Create(SVarArrayLocked);
  232. VAR_NOTIMPL:
  233. Create(SVarNotImplemented);
  234. VAR_OUTOFMEMORY:
  235. Create(SVarOutOfMemory);
  236. VAR_INVALIDARG:
  237. Create(SVarInvalid);
  238. VAR_UNEXPECTED,
  239. VAR_EXCEPTION:
  240. Create(SVarUnexpected);
  241. else
  242. CreateFmt(SUnknownErrorCode,[Code]);
  243. end;
  244. ErrCode:=Code;
  245. end;
  246. {$if defined(win32) or defined(win64) or defined (wince)}
  247. function EExternal.GetExceptionRecord: PExceptionRecord;
  248. begin
  249. result:=@FExceptionRecord;
  250. end;
  251. {$endif win32 or win64 or wince}
  252. {$push}
  253. {$S-}
  254. Procedure CatchUnhandledException (Obj : TObject; Addr: CodePointer; FrameCount: Longint; Frames: PCodePointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  255. Var
  256. i : longint;
  257. hstdout : ^text;
  258. begin
  259. if WriteErrorsToStdErr then
  260. hstdout:=@stderr
  261. else
  262. hstdout:=@stdout;
  263. Writeln(hstdout^,'An unhandled exception occurred at $',HexStr(Addr),':');
  264. if Obj is exception then
  265. Writeln(hstdout^,Obj.ClassName,': ',Exception(Obj).Message)
  266. else if Obj is TObject then
  267. Writeln(hstdout^,'Exception object ',Obj.ClassName,' is not of class Exception.')
  268. else
  269. Writeln(hstdout^,'Exception object is not a valid class.');
  270. {$IFDEF HAS_OSERROR}
  271. {$IFDEF DEBUG_EXCEPTIONS_LASTOSERROR}
  272. WriteLn (HStdOut^, 'Last OS error detected in the RTL: ', GetLastOSError);
  273. {$ENDIF DEBUG_EXCEPTIONS_LASTOSERROR}
  274. {$ENDIF HAS_OSERROR}
  275. Writeln(hstdout^,BackTraceStrFunc(Addr));
  276. if (FrameCount>0) then
  277. begin
  278. for i:=0 to FrameCount-1 do
  279. Writeln(hstdout^,BackTraceStrFunc(Frames[i]));
  280. end;
  281. Writeln(hstdout^,'');
  282. end;
  283. type
  284. PExceptMapEntry=^TExceptMapEntry;
  285. TExceptMapEntry=record
  286. code: byte;
  287. cls: ExceptClass;
  288. {$IFDEF FPC_HAS_FEATURE_RESOURCES} // This is necessary for 2.4.4, which does not have reasources as a separate feature
  289. msg: PResStringRec;
  290. {$else FPC_HAS_FEATURE_RESOURCES}
  291. msg: PAnsiString;
  292. {$endif FPC_HAS_FEATURE_RESOURCES}
  293. end;
  294. const
  295. exceptmap: array[0..30] of TExceptMapEntry = (
  296. (code: 200; cls: EDivByZero; msg: @SDivByZero),
  297. (code: 201; cls: ERangeError; msg: @SRangeError),
  298. (code: 202; cls: EStackOverflow; msg: @SStackOverflow),
  299. (code: 205; cls: EOverflow; msg: @SOverflow),
  300. (code: 206; cls: EUnderflow; msg: @SUnderflow),
  301. (code: 207; cls: EInvalidOp; msg: @SInvalidOp),
  302. { Delphi distinguishes reDivByZero from reZeroDivide, but maps both to code 200. }
  303. (code: 208; cls: EZeroDivide; msg: @SZeroDivide),
  304. (code: 210; cls: EObjectCheck; msg: @SObjectCheckError),
  305. (code: 211; cls: EAbstractError; msg: @SAbstractError),
  306. (code: 212; cls: EExternalException; msg: @SExternalException),
  307. (code: 214; cls: EBusError; msg: @SBusError),
  308. (code: 215; cls: EIntOverflow; msg: @SIntOverflow),
  309. (code: 216; cls: EAccessViolation; msg: @SAccessViolation),
  310. (code: 217; cls: EControlC; msg: @SControlC),
  311. (code: 218; cls: EPrivilege; msg: @SPrivilege),
  312. (code: 219; cls: EInvalidCast; msg: @SInvalidCast),
  313. (code: 220; cls: EVariantError; msg: @SInvalidVarCast),
  314. (code: 221; cls: EVariantError; msg: @SInvalidVarOp),
  315. (code: 222; cls: EVariantError; msg: @SDispatchError),
  316. (code: 223; cls: EVariantError; msg: @SVarArrayCreate),
  317. (code: 224; cls: EVariantError; msg: @SVarNotArray),
  318. (code: 225; cls: EVariantError; msg: @SVarArrayBounds),
  319. (code: 227; cls: EAssertionFailed; msg: @SAssertionFailed),
  320. (code: 228; cls: EIntfCastError; msg: @SIntfCastError),
  321. (code: 229; cls: ESafecallException; msg: @SSafecallException),
  322. (code: 231; cls: EConvertError; msg: @SiconvError),
  323. (code: 232; cls: ENoThreadSupport; msg: @SNoThreadSupport),
  324. (code: 233; cls: ESigQuit; msg: @SSigQuit),
  325. (code: 234; cls: ENoWideStringSupport; msg: @SMissingWStringManager),
  326. (code: 235; cls: ENoDynLibsSupport; msg: @SNoDynLibsSupport),
  327. (code: 236; cls: EThreadError; msg: @SThreadError)
  328. );
  329. function FindExceptMapEntry(err: longint): PExceptMapEntry;
  330. var
  331. i: longint;
  332. begin
  333. for i:=low(exceptmap) to high(exceptmap) do
  334. if err=exceptmap[i].code then
  335. begin
  336. result:=@exceptmap[i];
  337. exit;
  338. end;
  339. result:=nil;
  340. end;
  341. Var OutOfMemory : EOutOfMemory;
  342. InValidPointer : EInvalidPointer;
  343. Procedure RunErrorToExcept (ErrNo : Longint; Address : CodePointer; Frame : Pointer);
  344. var
  345. E: Exception;
  346. HS: PAnsiString;
  347. Entry: PExceptMapEntry;
  348. begin
  349. Case Errno of
  350. 1,203 : E:=OutOfMemory;
  351. 204 : E:=InvalidPointer;
  352. else
  353. Entry:=FindExceptMapEntry(ErrNo);
  354. if Assigned(Entry) then
  355. E:=Entry^.cls.CreateRes(Entry^.msg)
  356. else
  357. begin
  358. HS:=nil;
  359. Case Errno of
  360. 2 : HS:=@SFileNotFound;
  361. 3 : HS:=@SInvalidFileName;
  362. 4 : HS:=@STooManyOpenFiles;
  363. 5 : HS:=@SAccessDenied;
  364. 6 : HS:=@SInvalidFileHandle;
  365. 15 : HS:=@SInvalidDrive;
  366. 100 : HS:=@SEndOfFile;
  367. 101 : HS:=@SDiskFull;
  368. 102 : HS:=@SFileNotAssigned;
  369. 103 : HS:=@SFileNotOpen;
  370. 104 : HS:=@SFileNotOpenForInput;
  371. 105 : HS:=@SFileNotOpenForOutput;
  372. 106 : HS:=@SInvalidInput;
  373. end;
  374. if Assigned(HS) then
  375. E:=EInOutError.CreateRes(HS)
  376. else
  377. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  378. // this routine can be called from FPC_IOCHECK,
  379. // which clears inoutres and then passes its
  380. // original value to HandleErrorFrame() (which calls
  381. // us). So use errno rather than IOResult, and clear
  382. // InOutRes explicitly in case we can also be called
  383. // from a place that does not clear InOutRes explicitly
  384. EInoutError(E).ErrorCode:=errno;
  385. inoutres:=0;
  386. end;
  387. end;
  388. Raise E at Address,Frame;
  389. end;
  390. {$IFDEF HAS_OSERROR}
  391. Procedure RaiseLastOSError;overload;
  392. begin
  393. RaiseLastOSError(GetLastOSError);
  394. end;
  395. Procedure RaiseLastOSError(LastError: Integer);overload;
  396. var
  397. E : EOSError;
  398. begin
  399. If (LastError<>0) then
  400. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  401. else
  402. E:=EOSError.Create(SUnkOSError);
  403. E.ErrorCode:=LastError;
  404. Raise E;
  405. end;
  406. {$else}
  407. Procedure RaiseLastOSError;overload;
  408. begin
  409. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  410. end;
  411. Procedure RaiseLastOSError(LastError: Integer);overload;
  412. begin
  413. RaiseLastOSError;
  414. end;
  415. {$endif}
  416. procedure CheckOSError(LastError: Integer);
  417. begin
  418. if LastError <> 0 then
  419. RaiseLastOSError(LastError);
  420. end;
  421. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  422. Var
  423. S : String;
  424. begin
  425. If Msg='' then
  426. S:=SAssertionFailed
  427. else
  428. S:=Msg;
  429. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  430. end;
  431. {$pop} //{$S-} for Error handling functions
  432. Procedure InitExceptions;
  433. {
  434. Must install uncaught exception handler (ExceptProc)
  435. and install exceptions for system exceptions or signals.
  436. (e.g: SIGSEGV -> ESegFault or so.)
  437. }
  438. begin
  439. ExceptionClass := Exception;
  440. ExceptProc:=@CatchUnhandledException;
  441. // Create objects that may have problems when there is no memory.
  442. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  443. OutOfMemory.AllowFree:=false;
  444. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  445. InvalidPointer.AllowFree:=false;
  446. AssertErrorProc:=@AssertErrorHandler;
  447. ErrorProc:=@RunErrorToExcept;
  448. OnShowException:=Nil;
  449. end;
  450. Procedure DoneExceptions;
  451. begin
  452. OutOfMemory.AllowFree:=true;
  453. OutOfMemory.Free;
  454. InValidPointer.AllowFree:=true;
  455. InValidPointer.Free;
  456. end;
  457. { Exception handling routines }
  458. function ExceptObject: TObject;
  459. begin
  460. If RaiseList=Nil then
  461. Result:=Nil
  462. else
  463. Result:=RaiseList^.FObject;
  464. end;
  465. function ExceptAddr: CodePointer;
  466. begin
  467. If RaiseList=Nil then
  468. Result:=Nil
  469. else
  470. Result:=RaiseList^.Addr;
  471. end;
  472. function ExceptFrameCount: Longint;
  473. begin
  474. If RaiseList=Nil then
  475. Result:=0
  476. else
  477. Result:=RaiseList^.Framecount;
  478. end;
  479. function ExceptFrames: PCodePointer;
  480. begin
  481. If RaiseList=Nil then
  482. Result:=Nil
  483. else
  484. Result:=RaiseList^.Frames;
  485. end;
  486. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  487. Buffer: PAnsiChar; Size: Integer): Integer;
  488. Var
  489. S : AnsiString;
  490. Len : Integer;
  491. begin
  492. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  493. If ExceptObject is Exception then
  494. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  495. Len:=Length(S);
  496. If S[Len]<>'.' then
  497. begin
  498. S:=S+'.';
  499. Inc(len);
  500. end;
  501. If Len>Size then
  502. Len:=Size;
  503. if Len > 0 then
  504. Move(S[1],Buffer^,Len);
  505. Result:=Len;
  506. end;
  507. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  508. // use shortstring. On exception, the heap may be corrupt.
  509. Var
  510. Buf : ShortString;
  511. begin
  512. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  513. If IsConsole Then
  514. writeln(Buf)
  515. else
  516. If Assigned(OnShowException) Then
  517. OnShowException (Buf);
  518. end;
  519. procedure Abort;
  520. begin
  521. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  522. end;
  523. procedure OutOfMemoryError;
  524. begin
  525. Raise OutOfMemory;
  526. end;
  527. { ---------------------------------------------------------------------
  528. Initialization/Finalization/exit code
  529. ---------------------------------------------------------------------}
  530. Type
  531. PPRecord = ^TPRecord;
  532. TPRecord = Record
  533. Func : TTerminateProc;
  534. NextFunc : PPRecord;
  535. end;
  536. Const
  537. TPList : PPRecord = Nil;
  538. procedure AddTerminateProc(TermProc: TTerminateProc);
  539. Var
  540. TPR : PPRecord;
  541. begin
  542. New(TPR);
  543. With TPR^ do
  544. begin
  545. NextFunc:=TPList;
  546. Func:=TermProc;
  547. end;
  548. TPList:=TPR;
  549. end;
  550. function CallTerminateProcs: Boolean;
  551. Var
  552. TPR : PPRecord;
  553. begin
  554. Result:=True;
  555. TPR:=TPList;
  556. While Result and (TPR<>Nil) do
  557. begin
  558. Result:=TPR^.Func();
  559. TPR:=TPR^.NextFunc;
  560. end;
  561. end;
  562. procedure FreeTerminateProcs;
  563. var
  564. TPR1, TPR2: PPRecord;
  565. begin
  566. TPR1 := TPList;
  567. TPList := Nil;
  568. while Assigned(TPR1) do begin
  569. TPR2 := TPR1^.NextFunc;
  570. Dispose(TPR1);
  571. TPR1 := TPR2;
  572. end;
  573. end;
  574. { ---------------------------------------------------------------------
  575. Diskh functions, OS independent.
  576. ---------------------------------------------------------------------}
  577. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  578. begin
  579. GetDir(0,Result);
  580. end;
  581. { ---------------------------------------------------------------------
  582. Other functions, OS independent.
  583. ---------------------------------------------------------------------}
  584. Var
  585. GUIDCalledRandomize : Boolean = False;
  586. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  587. Var
  588. I : Integer;
  589. P : PByte;
  590. begin
  591. P:=@Buf;
  592. If Not GUIDCalledRandomize then
  593. begin
  594. Randomize;
  595. GUIDCalledRandomize:=True;
  596. end;
  597. For I:=0 to NBytes-1 do
  598. P[i]:=Random(256);
  599. end;
  600. {$IFDEF HASCREATEGUID}
  601. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  602. {$ENDIF}
  603. Function CreateGUID(out GUID : TGUID) : Integer;
  604. begin
  605. If Assigned(OnCreateGUID) then
  606. Result:=OnCreateGUID(GUID)
  607. else
  608. begin
  609. {$IFDEF HASCREATEGUID}
  610. Result:=SysCreateGUID(GUID);
  611. {$ELSE}
  612. GetRandomBytes(GUID,SizeOf(Guid));
  613. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  614. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  615. Result:=0;
  616. {$ENDIF}
  617. end;
  618. end;
  619. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  620. {$if defined(win64) or defined(win32)}
  621. var
  622. mode : DWord;
  623. begin
  624. mode:=SetErrorMode(ErrorMode);
  625. try
  626. Result:=System.SafeLoadLibrary(FileName);
  627. finally
  628. SetErrorMode(mode);
  629. end;
  630. end;
  631. {$else}
  632. begin
  633. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  634. Result:=System.SafeLoadLibrary(FileName);
  635. {$else}
  636. Result:=HModule(nil);
  637. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  638. end;
  639. {$endif}
  640. {$if defined(win32) or defined(win64) or defined(wince)}
  641. function GetModuleName(Module: HMODULE): string;
  642. var
  643. ResultLength, BufferLength: DWORD;
  644. Buffer: UnicodeString;
  645. begin
  646. BufferLength := MAX_PATH div 2;
  647. repeat
  648. Inc(BufferLength, BufferLength);
  649. SetLength(Buffer, BufferLength);
  650. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  651. if ResultLength = 0 then
  652. Exit('');
  653. until ResultLength < BufferLength;
  654. SetLength(Buffer, ResultLength);
  655. Result := Buffer;
  656. end;
  657. {$elseif defined(win16)}
  658. function GetModuleName(Module: HMODULE): string;
  659. var
  660. ResultLength, BufferLength: DWORD;
  661. Buffer: RawByteString;
  662. begin
  663. BufferLength := MAX_PATH div 2;
  664. repeat
  665. Inc(BufferLength, BufferLength);
  666. SetLength(Buffer, BufferLength);
  667. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  668. if ResultLength = 0 then
  669. Exit('');
  670. until ResultLength < BufferLength;
  671. SetLength(Buffer, ResultLength);
  672. Result := Buffer;
  673. end;
  674. {$else}
  675. function GetModuleName(Module: HMODULE): string;
  676. begin
  677. Result:='';
  678. end;
  679. {$endif}
  680. { Beep support }
  681. procedure Beep;
  682. begin
  683. If Assigned(OnBeep) then
  684. OnBeep;
  685. end;
  686. // OSes that only provide 1 byte versions can enable the following define
  687. {$ifdef executeprocuni}
  688. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  689. begin
  690. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  691. end;
  692. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  693. var
  694. ComLineA : array of RawByteString;
  695. I : Integer;
  696. begin
  697. SetLength(ComLineA,high(comline)-low(comline)+1);
  698. For I:=0 to length(ComLineA)-1 Do
  699. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  700. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  701. end;
  702. {$endif}
  703. // generic ifthen..
  704. {$IFNDEF VER3_0}
  705. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  706. begin
  707. if val then
  708. Result := ifTrue
  709. else
  710. Result:=ifFalse;
  711. end;
  712. {$ENDIF}
  713. Function ArrayOfConstToStrArray(Args: array of const) : TUTF8StringDynArray;
  714. var
  715. i: Integer;
  716. O : TObject;
  717. C : TClass;
  718. S : String;
  719. begin
  720. SetLength(Result,Length(Args));
  721. for i:=Low(Args) to High(Args) do
  722. case Args[i].VType of
  723. vtInteger: Result[i]:=IntToStr(Args[i].VInteger);
  724. vtBoolean: Result[i]:=BoolToStr(Args[i].VBoolean);
  725. vtChar: Result[i] := Args[i].VChar;
  726. {$ifndef FPUNONE}
  727. vtExtended: Result[i]:= FloatToStr(Args[i].VExtended^);
  728. {$ENDIF}
  729. vtString: Result[i] := Args[i].VString^;
  730. vtPointer: Result[i] := '0x'+HexStr(PtrInt(Args[i].VPointer),SizeOF(PtrInt));
  731. vtPChar: Result[i] := Args[i].VPChar;
  732. vtObject:
  733. begin
  734. O:=Args[i].VObject;
  735. if Assigned(O) then
  736. begin
  737. try
  738. S:=O.ClassName;
  739. except
  740. S:='<Invalid instance>';
  741. end;
  742. end
  743. else
  744. S:='';
  745. Result[I] := '<Object '+S+' 0x'+HexStr(PtrInt(O),SizeOF(PtrInt))+'>';
  746. end;
  747. vtClass:
  748. begin
  749. C:=Args[i].VClass;
  750. if Assigned(C) then
  751. begin
  752. try
  753. S:=C.ClassName;
  754. except
  755. S:='<Invalid Class>';
  756. end;
  757. end
  758. else
  759. S:='';
  760. Result[I] := '<Class '+S+' 0x'+HexStr(PtrInt(C),SizeOF(PtrInt))+'>';
  761. end;
  762. vtWideChar: Result[i] := UTF8Encode(Args[i].VWideChar);
  763. vtPWideChar: Result[i] := UTF8Encode(Args[i].VPWideChar^);
  764. vtAnsiString: Result[i] := AnsiString(Args[i].VAnsiString);
  765. vtCurrency: Result[i] := FLoatToSTr(Args[i].VCurrency^);
  766. vtVariant: Result[i] := Args[i].VVariant^;
  767. vtInterface: Result[I] := '<Interface 0x'+HexStr(PtrInt(Args[i].VInterface),SizeOF(PtrInt))+'>';
  768. vtWidestring: Result[i] := UTF8ENcode(WideString(Args[i].VWideString));
  769. vtInt64: Result[i] := IntToStr(Args[i].VInt64^);
  770. vtQWord: Result[i] := IntToStr(Args[i].VQWord^);
  771. vtUnicodeString:Result[i] := UTF8Encode(UnicodeString(Args[i].VUnicodeString));
  772. end;
  773. end;
  774. Function ArrayOfConstToStr(Args: array of const ; aSeparator : Char = ','; aQuoteBegin : Char = '"'; aQuoteEnd : Char = '"') : UTF8String;
  775. Procedure Add(s: UTF8String);
  776. begin
  777. if aQuoteBegin<>#0 then
  778. S:=aQuoteBegin+S;
  779. if aQuoteEnd<>#0 then
  780. S:=S+aQuoteEnd;
  781. if Result<>'' then
  782. Result:=Result+aSeparator;
  783. Result:=Result+S;
  784. end;
  785. Var
  786. S : UTF8String;
  787. begin
  788. Result:='';
  789. For S in ArrayOfConstToStrArray(Args) do
  790. Add(S);
  791. end;