sysutils.inc 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  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. {$IFDEF FPC_HAS_FEATURE_UNICODESTRINGS}
  39. { strange Delphi thing }
  40. {$i sysmarshal.inc}
  41. {$ENDIF}
  42. {$ifndef OS_FILEISREADONLY}
  43. Function FileIsReadOnly(const FileName: RawByteString): Boolean;
  44. begin
  45. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  46. end;
  47. Function FileIsReadOnly(const FileName: UnicodeString): Boolean;
  48. begin
  49. Result := (FileGetAttr(FileName) and faReadOnly) <> 0;
  50. end;
  51. {$endif OS_FILEISREADONLY}
  52. {$ifndef OS_FILESETDATEBYNAME}
  53. Function FileSetDate (Const FileName : RawByteString;Age : Int64) : Longint;
  54. Var
  55. fd : THandle;
  56. begin
  57. { at least windows requires fmOpenWrite here }
  58. fd:=FileOpen(FileName,fmOpenWrite);
  59. If (Fd<>feInvalidHandle) then
  60. try
  61. Result:=FileSetDate(fd,Age);
  62. finally
  63. FileClose(fd);
  64. end
  65. else
  66. {$ifdef HAS_OSERROR}
  67. Result:=GetLastOSError;
  68. {$else}
  69. Result:=-1;
  70. {$endif}
  71. end;
  72. Function FileSetDate (Const FileName : UnicodeString;Age : Int64) : Longint;
  73. Var
  74. fd : THandle;
  75. begin
  76. { at least windows requires fmOpenWrite here }
  77. fd:=FileOpen(FileName,fmOpenWrite);
  78. If (Fd<>feInvalidHandle) then
  79. try
  80. Result:=FileSetDate(fd,Age);
  81. finally
  82. FileClose(fd);
  83. end
  84. else
  85. {$ifdef HAS_OSERROR}
  86. Result:=GetLastOSError;
  87. {$else}
  88. Result:=-1;
  89. {$endif}
  90. end;
  91. {$endif}
  92. { Read String Handling functions implementation }
  93. {$i sysstr.inc}
  94. { Read date & Time function implementations }
  95. {$ifndef FPUNONE}
  96. {$i dati.inc}
  97. {$endif}
  98. {$IFNDEF HAS_GETTICKCOUNT}
  99. function GetTickCount: LongWord;
  100. begin
  101. Result := LongWord(GetTickCount64);
  102. end;
  103. {$ENDIF}
  104. {$IFNDEF HAS_GETTICKCOUNT64}
  105. function GetTickCount64: QWord;
  106. begin
  107. {$IFDEF FPU_NONE}
  108. {$IFDEF HAS_SYSTIMERTICK}
  109. Result := SysTimerTick;
  110. {$ELSE}
  111. Result := 0;
  112. {$ENDIF}
  113. {$ELSE}
  114. Result := Trunc(Now * 24 * 60 * 60 * 1000);
  115. {$ENDIF}
  116. end;
  117. {$ENDIF}
  118. { Read PAnsiChar handling functions implementation }
  119. {$i syspch.inc}
  120. { generic internationalisation code }
  121. {$i sysint.inc}
  122. { wide string functions }
  123. {$i syswide.inc}
  124. {$ifdef FPC_HAS_UNICODESTRING}
  125. { unicode string functions }
  126. {$i sysuni.inc}
  127. {$i sysencoding.inc}
  128. {$endif FPC_HAS_UNICODESTRING}
  129. { threading stuff }
  130. {$i sysuthrd.inc}
  131. { OS utility code }
  132. {$i osutil.inc}
  133. procedure FreeAndNil(var obj);
  134. var
  135. temp: tobject;
  136. begin
  137. temp:=tobject(obj);
  138. pointer(obj):=nil;
  139. temp.free;
  140. end;
  141. procedure FreeMemAndNil(var p);
  142. var
  143. temp:Pointer;
  144. begin
  145. temp := Pointer(p);
  146. Pointer(P):=nil;
  147. FreeMem(temp);
  148. end;
  149. { Interfaces support }
  150. {$i sysuintf.inc}
  151. constructor Exception.Create(const msg : string);
  152. begin
  153. inherited create;
  154. fmessage:=msg;
  155. end;
  156. constructor Exception.CreateFmt(const msg : string; const args : array of const);
  157. begin
  158. inherited create;
  159. fmessage:=Format(msg,args);
  160. end;
  161. constructor Exception.CreateRes(ResString: PResStringRec);
  162. begin
  163. inherited create;
  164. fmessage:=ResString^;
  165. end;
  166. constructor Exception.CreateResFmt(ResString: PResStringRec; const Args: array of const);
  167. begin
  168. inherited create;
  169. fmessage:=Format(ResString^,args);
  170. end;
  171. constructor Exception.CreateHelp(const Msg: string; AHelpContext: Longint);
  172. begin
  173. inherited create;
  174. fmessage:=Msg;
  175. fhelpcontext:=AHelpContext;
  176. end;
  177. constructor Exception.CreateFmtHelp(const Msg: string; const Args: array of const;
  178. AHelpContext: Longint);
  179. begin
  180. inherited create;
  181. fmessage:=Format(Msg,args);
  182. fhelpcontext:=AHelpContext;
  183. end;
  184. constructor Exception.CreateResHelp(ResString: PResStringRec; AHelpContext: Longint);
  185. begin
  186. inherited create;
  187. fmessage:=ResString^;
  188. fhelpcontext:=AHelpContext;
  189. end;
  190. constructor Exception.CreateResFmtHelp(ResString: PResStringRec; const Args: array of const;
  191. AHelpContext: Longint);
  192. begin
  193. inherited create;
  194. fmessage:=Format(ResString^,args);
  195. fhelpcontext:=AHelpContext;
  196. end;
  197. Function Exception.ToString : RTLString;
  198. begin
  199. Result:=ClassName+': '+Message;
  200. end;
  201. procedure EHeapMemoryError.FreeInstance;
  202. begin
  203. if AllowFree then
  204. inherited FreeInstance;
  205. end;
  206. function Exception.GetBaseException : Exception;
  207. var
  208. _ExceptObjectStack : PExceptObject;
  209. begin
  210. _ExceptObjectStack:=RaiseList;
  211. While Assigned(_ExceptObjectStack) do
  212. begin
  213. result:=Exception(_ExceptObjectStack^.FObject);
  214. _ExceptObjectStack:=_ExceptObjectStack^.Next;
  215. end;
  216. end;
  217. Constructor EVariantError.CreateCode (Code : longint);
  218. begin
  219. case Code of
  220. VAR_OK:
  221. Create(SNoError);
  222. VAR_PARAMNOTFOUND:
  223. Create(SVarParamNotFound);
  224. VAR_TYPEMISMATCH:
  225. Create(SInvalidVarCast);
  226. VAR_BADVARTYPE:
  227. Create(SVarBadType);
  228. VAR_OVERFLOW:
  229. Create(SVarOverflow);
  230. VAR_BADINDEX:
  231. Create(SVarArrayBounds);
  232. VAR_ARRAYISLOCKED:
  233. Create(SVarArrayLocked);
  234. VAR_NOTIMPL:
  235. Create(SVarNotImplemented);
  236. VAR_OUTOFMEMORY:
  237. Create(SVarOutOfMemory);
  238. VAR_INVALIDARG:
  239. Create(SVarInvalid);
  240. VAR_UNEXPECTED,
  241. VAR_EXCEPTION:
  242. Create(SVarUnexpected);
  243. else
  244. CreateFmt(SUnknownErrorCode,[Code]);
  245. end;
  246. ErrCode:=Code;
  247. end;
  248. constructor EInOutArgumentException.Create(const aMsg, aPath: string); overload;
  249. begin
  250. Path:=aPath;
  251. Inherited Create(aMsg);
  252. end;
  253. constructor EInOutArgumentException.CreateRes(ResStringRec: PResStringRec; const aPath: string); overload;
  254. begin
  255. Path:=aPath;
  256. Inherited CreateRes(ResStringRec);
  257. end;
  258. constructor EInOutArgumentException.CreateFmt(const fmt: string; const args : array of const; const aPath : String);
  259. begin
  260. Path:=aPath;
  261. inherited CreateFmt(fmt,args);
  262. end;
  263. {$if defined(win32) or defined(win64) or defined (wince)}
  264. function EExternal.GetExceptionRecord: PExceptionRecord;
  265. begin
  266. result:=@FExceptionRecord;
  267. end;
  268. {$endif win32 or win64 or wince}
  269. {$push}
  270. {$S-}
  271. Procedure CatchUnhandledException (Obj : TObject; Addr: CodePointer; FrameCount: Longint; Frames: PCodePointer);[public,alias:'FPC_BREAK_UNHANDLED_EXCEPTION'];
  272. Var
  273. i : longint;
  274. hstdout : ^text;
  275. begin
  276. if WriteErrorsToStdErr then
  277. hstdout:=@stderr
  278. else
  279. hstdout:=@stdout;
  280. Writeln(hstdout^,'An unhandled exception occurred at $',HexStr(Addr),':');
  281. if Obj is exception then
  282. Writeln(hstdout^,Obj.ClassName,': ',Exception(Obj).Message)
  283. else if Obj is TObject then
  284. Writeln(hstdout^,'Exception object ',Obj.ClassName,' is not of class Exception.')
  285. else
  286. Writeln(hstdout^,'Exception object is not a valid class.');
  287. {$IFDEF HAS_OSERROR}
  288. {$IFDEF DEBUG_EXCEPTIONS_LASTOSERROR}
  289. WriteLn (HStdOut^, 'Last OS error detected in the RTL: ', GetLastOSError);
  290. {$ENDIF DEBUG_EXCEPTIONS_LASTOSERROR}
  291. {$ENDIF HAS_OSERROR}
  292. Writeln(hstdout^,BackTraceStrFunc(Addr));
  293. if (FrameCount>0) then
  294. begin
  295. for i:=0 to FrameCount-1 do
  296. Writeln(hstdout^,BackTraceStrFunc(Frames[i]));
  297. end;
  298. Writeln(hstdout^,'');
  299. end;
  300. type
  301. PExceptMapEntry=^TExceptMapEntry;
  302. TExceptMapEntry=record
  303. code: byte;
  304. cls: ExceptClass;
  305. {$IFDEF FPC_HAS_FEATURE_RESOURCES} // This is necessary for 2.4.4, which does not have reasources as a separate feature
  306. msg: PResStringRec;
  307. {$else FPC_HAS_FEATURE_RESOURCES}
  308. msg: PAnsiString;
  309. {$endif FPC_HAS_FEATURE_RESOURCES}
  310. end;
  311. const
  312. exceptmap: array[0..30] of TExceptMapEntry = (
  313. (code: 200; cls: EDivByZero; msg: @SDivByZero),
  314. (code: 201; cls: ERangeError; msg: @SRangeError),
  315. (code: 202; cls: EStackOverflow; msg: @SStackOverflow),
  316. (code: 205; cls: EOverflow; msg: @SOverflow),
  317. (code: 206; cls: EUnderflow; msg: @SUnderflow),
  318. (code: 207; cls: EInvalidOp; msg: @SInvalidOp),
  319. { Delphi distinguishes reDivByZero from reZeroDivide, but maps both to code 200. }
  320. (code: 208; cls: EZeroDivide; msg: @SZeroDivide),
  321. (code: 210; cls: EObjectCheck; msg: @SObjectCheckError),
  322. (code: 211; cls: EAbstractError; msg: @SAbstractError),
  323. (code: 212; cls: EExternalException; msg: @SExternalException),
  324. (code: 214; cls: EBusError; msg: @SBusError),
  325. (code: 215; cls: EIntOverflow; msg: @SIntOverflow),
  326. (code: 216; cls: EAccessViolation; msg: @SAccessViolation),
  327. (code: 217; cls: EControlC; msg: @SControlC),
  328. (code: 218; cls: EPrivilege; msg: @SPrivilege),
  329. (code: 219; cls: EInvalidCast; msg: @SInvalidCast),
  330. (code: 220; cls: EVariantError; msg: @SInvalidVarCast),
  331. (code: 221; cls: EVariantError; msg: @SInvalidVarOp),
  332. (code: 222; cls: EVariantError; msg: @SDispatchError),
  333. (code: 223; cls: EVariantError; msg: @SVarArrayCreate),
  334. (code: 224; cls: EVariantError; msg: @SVarNotArray),
  335. (code: 225; cls: EVariantError; msg: @SVarArrayBounds),
  336. (code: 227; cls: EAssertionFailed; msg: @SAssertionFailed),
  337. (code: 228; cls: EIntfCastError; msg: @SIntfCastError),
  338. (code: 229; cls: ESafecallException; msg: @SSafecallException),
  339. (code: 231; cls: EConvertError; msg: @SiconvError),
  340. (code: 232; cls: ENoThreadSupport; msg: @SNoThreadSupport),
  341. (code: 233; cls: ESigQuit; msg: @SSigQuit),
  342. (code: 234; cls: ENoWideStringSupport; msg: @SMissingWStringManager),
  343. (code: 235; cls: ENoDynLibsSupport; msg: @SNoDynLibsSupport),
  344. (code: 236; cls: EThreadError; msg: @SThreadError)
  345. );
  346. function FindExceptMapEntry(err: longint): PExceptMapEntry;
  347. var
  348. i: longint;
  349. begin
  350. for i:=low(exceptmap) to high(exceptmap) do
  351. if err=exceptmap[i].code then
  352. begin
  353. result:=@exceptmap[i];
  354. exit;
  355. end;
  356. result:=nil;
  357. end;
  358. Var OutOfMemory : EOutOfMemory;
  359. InValidPointer : EInvalidPointer;
  360. Procedure RunErrorToExcept (ErrNo : Longint; Address : CodePointer; Frame : Pointer);
  361. var
  362. E: Exception;
  363. HS: PResStringRec;
  364. Entry: PExceptMapEntry;
  365. begin
  366. Case Errno of
  367. 1,203 : E:=OutOfMemory;
  368. 204 : E:=InvalidPointer;
  369. else
  370. Entry:=FindExceptMapEntry(ErrNo);
  371. if Assigned(Entry) then
  372. E:=Entry^.cls.CreateRes(Entry^.msg)
  373. else
  374. begin
  375. HS:=nil;
  376. Case Errno of
  377. 2 : HS:=@SFileNotFound;
  378. 3 : HS:=@SInvalidFileName;
  379. 4 : HS:=@STooManyOpenFiles;
  380. 5 : HS:=@SAccessDenied;
  381. 6 : HS:=@SInvalidFileHandle;
  382. 15 : HS:=@SInvalidDrive;
  383. 100 : HS:=@SEndOfFile;
  384. 101 : HS:=@SDiskFull;
  385. 102 : HS:=@SFileNotAssigned;
  386. 103 : HS:=@SFileNotOpen;
  387. 104 : HS:=@SFileNotOpenForInput;
  388. 105 : HS:=@SFileNotOpenForOutput;
  389. 106 : HS:=@SInvalidInput;
  390. end;
  391. if Assigned(HS) then
  392. E:=EInOutError.CreateRes(HS)
  393. else
  394. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  395. // this routine can be called from FPC_IOCHECK,
  396. // which clears inoutres and then passes its
  397. // original value to HandleErrorFrame() (which calls
  398. // us). So use errno rather than IOResult, and clear
  399. // InOutRes explicitly in case we can also be called
  400. // from a place that does not clear InOutRes explicitly
  401. EInoutError(E).ErrorCode:=errno;
  402. inoutres:=0;
  403. end;
  404. end;
  405. Raise E at Address,Frame;
  406. end;
  407. {$IFDEF HAS_OSERROR}
  408. Procedure RaiseLastOSError;overload;
  409. begin
  410. RaiseLastOSError(GetLastOSError);
  411. end;
  412. Procedure RaiseLastOSError(LastError: Integer);overload;
  413. var
  414. E : EOSError;
  415. begin
  416. If (LastError<>0) then
  417. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  418. else
  419. E:=EOSError.Create(SUnkOSError);
  420. E.ErrorCode:=LastError;
  421. Raise E;
  422. end;
  423. {$else}
  424. Procedure RaiseLastOSError;overload;
  425. begin
  426. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  427. end;
  428. Procedure RaiseLastOSError(LastError: Integer);overload;
  429. begin
  430. RaiseLastOSError;
  431. end;
  432. {$endif}
  433. procedure CheckOSError(LastError: Integer);
  434. begin
  435. if LastError <> 0 then
  436. RaiseLastOSError(LastError);
  437. end;
  438. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  439. Var
  440. S : String;
  441. begin
  442. If Msg='' then
  443. S:=SAssertionFailed
  444. else
  445. S:=Msg;
  446. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  447. end;
  448. {$pop} //{$S-} for Error handling functions
  449. Procedure InitExceptions;
  450. {
  451. Must install uncaught exception handler (ExceptProc)
  452. and install exceptions for system exceptions or signals.
  453. (e.g: SIGSEGV -> ESegFault or so.)
  454. }
  455. begin
  456. ExceptionClass := Exception;
  457. ExceptProc:=@CatchUnhandledException;
  458. // Create objects that may have problems when there is no memory.
  459. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  460. OutOfMemory.AllowFree:=false;
  461. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  462. InvalidPointer.AllowFree:=false;
  463. AssertErrorProc:=@AssertErrorHandler;
  464. ErrorProc:=@RunErrorToExcept;
  465. OnShowException:=Nil;
  466. end;
  467. Procedure DoneExceptions;
  468. begin
  469. OutOfMemory.AllowFree:=true;
  470. OutOfMemory.Free;
  471. InValidPointer.AllowFree:=true;
  472. InValidPointer.Free;
  473. end;
  474. { Exception handling routines }
  475. function ExceptObject: TObject;
  476. begin
  477. If RaiseList=Nil then
  478. Result:=Nil
  479. else
  480. Result:=RaiseList^.FObject;
  481. end;
  482. function ExceptAddr: CodePointer;
  483. begin
  484. If RaiseList=Nil then
  485. Result:=Nil
  486. else
  487. Result:=RaiseList^.Addr;
  488. end;
  489. function ExceptFrameCount: Longint;
  490. begin
  491. If RaiseList=Nil then
  492. Result:=0
  493. else
  494. Result:=RaiseList^.Framecount;
  495. end;
  496. function ExceptFrames: PCodePointer;
  497. begin
  498. If RaiseList=Nil then
  499. Result:=Nil
  500. else
  501. Result:=RaiseList^.Frames;
  502. end;
  503. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  504. Buffer: PAnsiChar; Size: Integer): Integer;
  505. Var
  506. S : AnsiString;
  507. Len : Integer;
  508. begin
  509. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  510. If ExceptObject is Exception then
  511. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  512. Len:=Length(S);
  513. If S[Len]<>'.' then
  514. begin
  515. S:=S+'.';
  516. Inc(len);
  517. end;
  518. If Len>Size then
  519. Len:=Size;
  520. if Len > 0 then
  521. Move(S[1],Buffer^,Len);
  522. Result:=Len;
  523. end;
  524. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  525. // use shortstring. On exception, the heap may be corrupt.
  526. Var
  527. Buf : ShortString;
  528. begin
  529. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  530. If IsConsole Then
  531. writeln(Buf)
  532. else
  533. If Assigned(OnShowException) Then
  534. OnShowException (Buf);
  535. end;
  536. procedure Abort;
  537. begin
  538. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  539. end;
  540. procedure OutOfMemoryError;
  541. begin
  542. Raise OutOfMemory;
  543. end;
  544. function ListIndexErrorMsg(aIndex, aMaxIndex: SizeInt; const aListObjName: string): string; overload;
  545. begin
  546. if aMaxIndex<0 then
  547. Result:=Format(SListIndexErrorEmptyReason,[aListObjName])
  548. else
  549. Result:=Format(SListIndexErrorRangeReason,[aListObjName]);
  550. Result:=Format(SListIndexError, [aIndex])+Result;
  551. end;
  552. function ListIndexErrorMsg(AIndex, AMaxIndex: SizeInt; AListObj: TObject): string; overload;
  553. Var
  554. aName : string;
  555. begin
  556. if Assigned(aListObj) then
  557. Result:=aListObj.ClassName
  558. else
  559. Result:='<Nil>';
  560. Result:=ListIndexErrorMsg(aIndex, aMaxIndex, aName);
  561. end;
  562. procedure ListIndexError(aIndex,aMax: Integer; aObj: TObject);
  563. var
  564. aClassName : string;
  565. begin
  566. if Assigned(aObj) then
  567. aClassName:=aObj.ClassName
  568. else
  569. aClassName:='<nil>';
  570. Raise EListError.CreateFmt(SErrListIndexExt,[aIndex,aClassName,aMax])
  571. end;
  572. { ---------------------------------------------------------------------
  573. Initialization/Finalization/exit code
  574. ---------------------------------------------------------------------}
  575. Type
  576. PPRecord = ^TPRecord;
  577. TPRecord = Record
  578. Func : TTerminateProc;
  579. NextFunc : PPRecord;
  580. end;
  581. Const
  582. TPList : PPRecord = Nil;
  583. procedure AddTerminateProc(TermProc: TTerminateProc);
  584. Var
  585. TPR : PPRecord;
  586. begin
  587. New(TPR);
  588. With TPR^ do
  589. begin
  590. NextFunc:=TPList;
  591. Func:=TermProc;
  592. end;
  593. TPList:=TPR;
  594. end;
  595. function CallTerminateProcs: Boolean;
  596. Var
  597. TPR : PPRecord;
  598. begin
  599. Result:=True;
  600. TPR:=TPList;
  601. While Result and (TPR<>Nil) do
  602. begin
  603. Result:=TPR^.Func();
  604. TPR:=TPR^.NextFunc;
  605. end;
  606. end;
  607. procedure FreeTerminateProcs;
  608. var
  609. TPR1, TPR2: PPRecord;
  610. begin
  611. TPR1 := TPList;
  612. TPList := Nil;
  613. while Assigned(TPR1) do begin
  614. TPR2 := TPR1^.NextFunc;
  615. Dispose(TPR1);
  616. TPR1 := TPR2;
  617. end;
  618. end;
  619. { ---------------------------------------------------------------------
  620. Diskh functions, OS independent.
  621. ---------------------------------------------------------------------}
  622. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  623. begin
  624. GetDir(0,Result);
  625. end;
  626. { ---------------------------------------------------------------------
  627. Other functions, OS independent.
  628. ---------------------------------------------------------------------}
  629. Var
  630. GUIDCalledRandomize : Boolean = False;
  631. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  632. Var
  633. I : Integer;
  634. P : PByte;
  635. begin
  636. P:=@Buf;
  637. If Not GUIDCalledRandomize then
  638. begin
  639. Randomize;
  640. GUIDCalledRandomize:=True;
  641. end;
  642. For I:=0 to NBytes-1 do
  643. P[i]:=Random(256);
  644. end;
  645. {$IFDEF HASCREATEGUID}
  646. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  647. {$ENDIF}
  648. Function CreateGUID(out GUID : TGUID) : Integer;
  649. begin
  650. If Assigned(OnCreateGUID) then
  651. Result:=OnCreateGUID(GUID)
  652. else
  653. begin
  654. {$IFDEF HASCREATEGUID}
  655. Result:=SysCreateGUID(GUID);
  656. {$ELSE}
  657. GetRandomBytes(GUID,SizeOf(Guid));
  658. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  659. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  660. Result:=0;
  661. {$ENDIF}
  662. end;
  663. end;
  664. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  665. {$if defined(win64) or defined(win32)}
  666. var
  667. mode : DWord;
  668. begin
  669. mode:=SetErrorMode(ErrorMode);
  670. try
  671. Result:=System.SafeLoadLibrary(FileName);
  672. finally
  673. SetErrorMode(mode);
  674. end;
  675. end;
  676. {$else}
  677. begin
  678. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  679. Result:=System.SafeLoadLibrary(FileName);
  680. {$else}
  681. Result:=HModule(nil);
  682. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  683. end;
  684. {$endif}
  685. {$if defined(win32) or defined(win64) or defined(wince)}
  686. function GetModuleName(Module: HMODULE): string;
  687. var
  688. ResultLength, BufferLength: DWORD;
  689. Buffer: UnicodeString;
  690. begin
  691. BufferLength := MAX_PATH div 2;
  692. repeat
  693. Inc(BufferLength, BufferLength);
  694. SetLength(Buffer, BufferLength);
  695. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  696. if ResultLength = 0 then
  697. Exit('');
  698. until ResultLength < BufferLength;
  699. SetLength(Buffer, ResultLength);
  700. Result := Buffer;
  701. end;
  702. {$elseif defined(win16)}
  703. function GetModuleName(Module: HMODULE): string;
  704. var
  705. ResultLength, BufferLength: DWORD;
  706. Buffer: RawByteString;
  707. begin
  708. BufferLength := MAX_PATH div 2;
  709. repeat
  710. Inc(BufferLength, BufferLength);
  711. SetLength(Buffer, BufferLength);
  712. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  713. if ResultLength = 0 then
  714. Exit('');
  715. until ResultLength < BufferLength;
  716. SetLength(Buffer, ResultLength);
  717. Result := Buffer;
  718. end;
  719. {$else}
  720. function GetModuleName(Module: HMODULE): string;
  721. begin
  722. Result:='';
  723. end;
  724. {$endif}
  725. { Beep support }
  726. procedure Beep;
  727. begin
  728. If Assigned(OnBeep) then
  729. OnBeep;
  730. end;
  731. // OSes that only provide 1 byte versions can enable the following define
  732. {$ifdef executeprocuni}
  733. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  734. begin
  735. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  736. end;
  737. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  738. var
  739. ComLineA : array of RawByteString;
  740. I : Integer;
  741. begin
  742. SetLength(ComLineA,high(comline)-low(comline)+1);
  743. For I:=0 to length(ComLineA)-1 Do
  744. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  745. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  746. end;
  747. {$endif}
  748. // generic ifthen..
  749. {$IFNDEF VER3_0}
  750. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  751. begin
  752. if val then
  753. Result := ifTrue
  754. else
  755. Result:=ifFalse;
  756. end;
  757. generic function Exchange<T>(var target:T; const newvalue:T) :T;
  758. begin
  759. Result := target;
  760. target := newvalue;
  761. end;
  762. {$ENDIF}
  763. Function ArrayOfConstToStrArray(const Args: array of const) : TUTF8StringDynArray;
  764. var
  765. i: Integer;
  766. O : TObject;
  767. C : TClass;
  768. S : String;
  769. begin
  770. SetLength(Result,Length(Args));
  771. for i:=Low(Args) to High(Args) do
  772. case Args[i].VType of
  773. vtInteger: Result[i]:=IntToStr(Args[i].VInteger);
  774. vtBoolean: Result[i]:=BoolToStr(Args[i].VBoolean);
  775. vtChar: Result[i] := Args[i].VChar;
  776. {$ifndef FPUNONE}
  777. vtExtended: Result[i]:= FloatToStr(Args[i].VExtended^);
  778. {$ENDIF}
  779. vtString: Result[i] := Args[i].VString^;
  780. vtPointer: Result[i] := '0x'+HexStr(PtrInt(Args[i].VPointer),SizeOF(PtrInt));
  781. vtPChar: Result[i] := Args[i].VPChar;
  782. vtObject:
  783. begin
  784. O:=Args[i].VObject;
  785. if Assigned(O) then
  786. begin
  787. try
  788. S:=O.ClassName;
  789. except
  790. S:='<Invalid instance>';
  791. end;
  792. end
  793. else
  794. S:='';
  795. Result[I] := '<Object '+S+' 0x'+HexStr(PtrInt(O),SizeOF(PtrInt))+'>';
  796. end;
  797. vtClass:
  798. begin
  799. C:=Args[i].VClass;
  800. if Assigned(C) then
  801. begin
  802. try
  803. S:=C.ClassName;
  804. except
  805. S:='<Invalid Class>';
  806. end;
  807. end
  808. else
  809. S:='';
  810. Result[I] := '<Class '+S+' 0x'+HexStr(PtrInt(C),SizeOF(PtrInt))+'>';
  811. end;
  812. vtWideChar: Result[i] := UTF8Encode(Args[i].VWideChar);
  813. vtPWideChar: Result[i] := UTF8Encode(Args[i].VPWideChar^);
  814. vtAnsiString: Result[i] := AnsiString(Args[i].VAnsiString);
  815. vtCurrency: Result[i] := FLoatToSTr(Args[i].VCurrency^);
  816. vtVariant: Result[i] := Args[i].VVariant^;
  817. vtInterface: Result[I] := '<Interface 0x'+HexStr(PtrInt(Args[i].VInterface),SizeOF(PtrInt))+'>';
  818. vtWidestring: Result[i] := UTF8ENcode(WideString(Args[i].VWideString));
  819. vtInt64: Result[i] := IntToStr(Args[i].VInt64^);
  820. vtQWord: Result[i] := IntToStr(Args[i].VQWord^);
  821. vtUnicodeString:Result[i] := UTF8Encode(UnicodeString(Args[i].VUnicodeString));
  822. end;
  823. end;
  824. Function ArrayOfConstToStr(const Args: array of const ; aSeparator : Char = ','; aQuoteBegin : Char = '"'; aQuoteEnd : Char = '"') : UTF8String;
  825. Procedure Add(s: UTF8String);
  826. begin
  827. if aQuoteBegin<>#0 then
  828. S:=aQuoteBegin+S;
  829. if aQuoteEnd<>#0 then
  830. S:=S+aQuoteEnd;
  831. if Result<>'' then
  832. Result:=Result+aSeparator;
  833. Result:=Result+S;
  834. end;
  835. Var
  836. S : UTF8String;
  837. begin
  838. Result:='';
  839. For S in ArrayOfConstToStrArray(Args) do
  840. Add(S);
  841. end;
  842. Function GetCompiledArchitecture : TOSVersion.TArchitecture;
  843. begin
  844. Result:=arOther;
  845. {$ifdef i386}
  846. Result:=arIntelX86;
  847. {$endif i386}
  848. {$ifdef m68k}
  849. Result:=arM68k;
  850. {$endif m68k}
  851. {$ifdef powerpc}
  852. Result:=arPowerPC
  853. {$endif powerpc}
  854. {$ifdef powerpc64}
  855. Result:=arPower64
  856. {$endif powerpc64}
  857. {$ifdef arm}
  858. Result:=arARM32;
  859. {$endif arm}
  860. {$ifdef aarch64}
  861. Result:=arARM64
  862. {$endif aarch64}
  863. {$ifdef sparc}
  864. Result:=arSparc;
  865. {$endif sparc}
  866. {$ifdef sparc64}
  867. Result:=arSparc64;
  868. {$endif sparc64}
  869. {$ifdef CPUX86_64}
  870. Result:=arIntelX64;
  871. {$endif x86_64}
  872. {$ifdef mipsel}
  873. Result:=arMipsel
  874. {$else : not mipsel}
  875. {$ifdef mips}
  876. Result:=arMips;
  877. {$endif mips}
  878. {$endif not mipsel}
  879. {$ifdef riscv32}
  880. Result:=arRiscV32;
  881. {$endif riscv32}
  882. {$ifdef riscv64}
  883. Result:=arRiscV64;
  884. {$endif riscv64}
  885. {$ifdef xtensa}
  886. Result:=arXtensa;
  887. {$endif xtensa}
  888. {$ifdef wasm32}
  889. Result:=arWasm32;
  890. {$endif wasm32}
  891. {$ifdef loongarch64}
  892. Result:=arLoongArch64;
  893. {$endif loongarch64}
  894. end;
  895. Function GetCompiledPlatform : TOSVersion.TPlatform;
  896. begin
  897. Result:=pfOther;
  898. {$IFDEF WINDOWS}
  899. Result:=pfWindows;
  900. {$ENDIF}
  901. {$Ifdef darwin}
  902. Result:=pfMacOS;
  903. {$ENDIF}
  904. {$IFDEF IOS}
  905. Result:=pfiOS;
  906. {$ENDIF}
  907. {$IFDEF ANDROID}
  908. Result:=pfAndroid;
  909. {$ENDIF}
  910. {$IFDEF LINUX}
  911. Result:=pfLinux;
  912. {$ENDIF}
  913. {$IFDEF GO32V2}
  914. Result:=pfGo32v2;
  915. {$ENDIF}
  916. {$IFDEF OS2}
  917. Result:=pfOS2;
  918. {$ENDIF}
  919. {$IFDEF FREEBSD}
  920. Result:=pfFreeBSD;
  921. {$ENDIF}
  922. {$IFDEF BEOS}
  923. Result:=pfBeos;
  924. {$ENDIF}
  925. {$IFDEF NETBSD}
  926. Result:=pfNetBSD;
  927. {$ENDIF}
  928. {$IFDEF AMIGA}
  929. Result:=pfAmiga;
  930. {$ENDIF}
  931. {$IFDEF ATARI}
  932. Result:=pfAtari;
  933. {$ENDIF}
  934. {$IFDEF SUNOS}
  935. Result:=pfSolaris;
  936. {$ENDIF}
  937. {$IFDEF QNX}
  938. Result:=pfQNX;
  939. {$ENDIF}
  940. {$IFDEF Netware}
  941. Result:=pfNetware;
  942. {$ENDIF}
  943. {$IFDEF OpenBSD}
  944. Result:=pfOpenBSD;
  945. {$ENDIF}
  946. {$IFDEF WDosX}
  947. Result:=pfWDosX;
  948. {$ENDIF}
  949. {$IFDEF PALMOS}
  950. Result:=pfPalmos;
  951. {$ENDIF}
  952. {$IFDEF MacOSClassic}
  953. Result:=pfMacOSClassic;
  954. {$ENDIF}
  955. {$IFDEF DARWIN}
  956. Result:=pfDarwin;
  957. {$ENDIF}
  958. {$IFDEF EMX}
  959. Result:=pfEMX;
  960. {$ENDIF}
  961. {$IFDEF WATCOM}
  962. Result:=pfWatcom;
  963. {$ENDIF}
  964. {$IFDEF MORPHOS}
  965. Result:=pfMorphos;
  966. {$ENDIF}
  967. {$IFDEF NETWLIBC}
  968. Result:=pfNetwLibC;
  969. {$ENDIF}
  970. {$IFDEF WINCE}
  971. Result:=pfWinCE;
  972. {$ENDIF}
  973. {$IFDEF GBA}
  974. Result:=pfGBA;
  975. {$ENDIF}
  976. {$IFDEF NDS}
  977. Result:=pfNDS;
  978. {$ENDIF}
  979. {$IFDEF EMBEDDED}
  980. Result:=pfEmbedded;
  981. {$ENDIF}
  982. {$IFDEF SYMBIAN}
  983. Result:=pfSymbian;
  984. {$ENDIF}
  985. {$IFDEF HAIKU}
  986. Result:=pfHaiku;
  987. {$ENDIF}
  988. {$IFDEF IPHONESIM}
  989. Result:=pfIPhoneSim;
  990. {$ENDIF}
  991. {$IFDEF AIX}
  992. Result:=pfAIX;
  993. {$ENDIF}
  994. {$IFDEF JAVA}
  995. Result:=pfJava;
  996. {$ENDIF}
  997. {$IFDEF NATIVENT}
  998. Result:=pfNativeNT;
  999. {$ENDIF}
  1000. {$IFDEF MSDOS}
  1001. Result:=pfMSDos;
  1002. {$ENDIF}
  1003. {$IFDEF WII}
  1004. Result:=pfWII;
  1005. {$ENDIF}
  1006. {$IFDEF AROS}
  1007. Result:=pfAROS;
  1008. {$ENDIF}
  1009. {$IFDEF DRAGONFLY}
  1010. Result:=pfDragonFly;
  1011. {$ENDIF}
  1012. {$IFDEF WIN16}
  1013. Result:=pfWin16;
  1014. {$ENDIF}
  1015. {$IFDEF FREERTOS}
  1016. Result:=pfFreeRTOS;
  1017. {$ENDIF}
  1018. {$IFDEF ZXSPECTRUM}
  1019. Result:=pfZXSpectrum;
  1020. {$ENDIF}
  1021. {$IFDEF MSXDOS}
  1022. Result:=pfMSXDOS;
  1023. {$ENDIF}
  1024. {$IFDEF AMSTRADCPC}
  1025. Result:=pfAmstradCPC;
  1026. {$ENDIF}
  1027. {$IFDEF SINCLAIRQL}
  1028. Result:=pfSinclairQL;
  1029. {$ENDIF}
  1030. {$IFDEF WASI}
  1031. Result:=pfWasi;
  1032. {$ENDIF}
  1033. end;
  1034. class constructor TOSVersion.Create;
  1035. {$IFNDEF HAS_OSVERSION}
  1036. var
  1037. S : String;
  1038. {$ENDIF}
  1039. begin
  1040. FArchitecture:=GetCompiledArchitecture;
  1041. FPlatform:=GetCompiledPlatform;
  1042. FBuild:=0;
  1043. FMajor:=0;
  1044. FMinor:=0;
  1045. FServicePackMajor:=0;
  1046. FServicePackMinor:=0;
  1047. {$IFDEF HAS_OSVERSION}
  1048. InitOSVersion;
  1049. {$ELSE}
  1050. WriteStr(S,GetCompiledPlatform);
  1051. FName:=Copy(S,3);
  1052. WriteStr(S,GetCompiledArchitecture);
  1053. FFull:=Copy(S,3)+'-'+FName;
  1054. {$ENDIF}
  1055. end;
  1056. class function TOSVersion.Check(aMajor: Integer): Boolean; overload; static; inline;
  1057. begin
  1058. Result:=(Major>=aMajor);
  1059. end;
  1060. class function TOSVersion.Check(aMajor, aMinor: Integer): Boolean; overload; static; inline;
  1061. begin
  1062. Result:=(Major>aMajor)
  1063. or ((Major=aMajor) and (Minor>=aMinor))
  1064. end;
  1065. class function TOSVersion.Check(aMajor, aMinor, aServicePackMajor: Integer): Boolean; overload; static; inline;
  1066. begin
  1067. Result:=(Major>AMajor)
  1068. or ((Major=aMajor) and (Minor>aMinor))
  1069. or ((Major=aMajor) and (Minor=aMinor) and (ServicePackMajor>=aServicePackMajor));
  1070. end;
  1071. class function TOSVersion.ToString: string; static;
  1072. begin
  1073. Result:=FFull;
  1074. end;