sysutils.inc 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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. procedure ListIndexError(aIndex,aMax: Integer; aObj: TObject);
  545. var
  546. aClassName : string;
  547. begin
  548. if Assigned(aObj) then
  549. aClassName:=aObj.ClassName
  550. else
  551. aClassName:='<nil>';
  552. Raise EListError.CreateFmt(SErrListIndexExt,[aIndex,aClassName,aMax])
  553. end;
  554. { ---------------------------------------------------------------------
  555. Initialization/Finalization/exit code
  556. ---------------------------------------------------------------------}
  557. Type
  558. PPRecord = ^TPRecord;
  559. TPRecord = Record
  560. Func : TTerminateProc;
  561. NextFunc : PPRecord;
  562. end;
  563. Const
  564. TPList : PPRecord = Nil;
  565. procedure AddTerminateProc(TermProc: TTerminateProc);
  566. Var
  567. TPR : PPRecord;
  568. begin
  569. New(TPR);
  570. With TPR^ do
  571. begin
  572. NextFunc:=TPList;
  573. Func:=TermProc;
  574. end;
  575. TPList:=TPR;
  576. end;
  577. function CallTerminateProcs: Boolean;
  578. Var
  579. TPR : PPRecord;
  580. begin
  581. Result:=True;
  582. TPR:=TPList;
  583. While Result and (TPR<>Nil) do
  584. begin
  585. Result:=TPR^.Func();
  586. TPR:=TPR^.NextFunc;
  587. end;
  588. end;
  589. procedure FreeTerminateProcs;
  590. var
  591. TPR1, TPR2: PPRecord;
  592. begin
  593. TPR1 := TPList;
  594. TPList := Nil;
  595. while Assigned(TPR1) do begin
  596. TPR2 := TPR1^.NextFunc;
  597. Dispose(TPR1);
  598. TPR1 := TPR2;
  599. end;
  600. end;
  601. { ---------------------------------------------------------------------
  602. Diskh functions, OS independent.
  603. ---------------------------------------------------------------------}
  604. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  605. begin
  606. GetDir(0,Result);
  607. end;
  608. { ---------------------------------------------------------------------
  609. Other functions, OS independent.
  610. ---------------------------------------------------------------------}
  611. Var
  612. GUIDCalledRandomize : Boolean = False;
  613. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  614. Var
  615. I : Integer;
  616. P : PByte;
  617. begin
  618. P:=@Buf;
  619. If Not GUIDCalledRandomize then
  620. begin
  621. Randomize;
  622. GUIDCalledRandomize:=True;
  623. end;
  624. For I:=0 to NBytes-1 do
  625. P[i]:=Random(256);
  626. end;
  627. {$IFDEF HASCREATEGUID}
  628. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  629. {$ENDIF}
  630. Function CreateGUID(out GUID : TGUID) : Integer;
  631. begin
  632. If Assigned(OnCreateGUID) then
  633. Result:=OnCreateGUID(GUID)
  634. else
  635. begin
  636. {$IFDEF HASCREATEGUID}
  637. Result:=SysCreateGUID(GUID);
  638. {$ELSE}
  639. GetRandomBytes(GUID,SizeOf(Guid));
  640. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  641. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  642. Result:=0;
  643. {$ENDIF}
  644. end;
  645. end;
  646. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  647. {$if defined(win64) or defined(win32)}
  648. var
  649. mode : DWord;
  650. begin
  651. mode:=SetErrorMode(ErrorMode);
  652. try
  653. Result:=System.SafeLoadLibrary(FileName);
  654. finally
  655. SetErrorMode(mode);
  656. end;
  657. end;
  658. {$else}
  659. begin
  660. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  661. Result:=System.SafeLoadLibrary(FileName);
  662. {$else}
  663. Result:=HModule(nil);
  664. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  665. end;
  666. {$endif}
  667. {$if defined(win32) or defined(win64) or defined(wince)}
  668. function GetModuleName(Module: HMODULE): string;
  669. var
  670. ResultLength, BufferLength: DWORD;
  671. Buffer: UnicodeString;
  672. begin
  673. BufferLength := MAX_PATH div 2;
  674. repeat
  675. Inc(BufferLength, BufferLength);
  676. SetLength(Buffer, BufferLength);
  677. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  678. if ResultLength = 0 then
  679. Exit('');
  680. until ResultLength < BufferLength;
  681. SetLength(Buffer, ResultLength);
  682. Result := Buffer;
  683. end;
  684. {$elseif defined(win16)}
  685. function GetModuleName(Module: HMODULE): string;
  686. var
  687. ResultLength, BufferLength: DWORD;
  688. Buffer: RawByteString;
  689. begin
  690. BufferLength := MAX_PATH div 2;
  691. repeat
  692. Inc(BufferLength, BufferLength);
  693. SetLength(Buffer, BufferLength);
  694. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  695. if ResultLength = 0 then
  696. Exit('');
  697. until ResultLength < BufferLength;
  698. SetLength(Buffer, ResultLength);
  699. Result := Buffer;
  700. end;
  701. {$else}
  702. function GetModuleName(Module: HMODULE): string;
  703. begin
  704. Result:='';
  705. end;
  706. {$endif}
  707. { Beep support }
  708. procedure Beep;
  709. begin
  710. If Assigned(OnBeep) then
  711. OnBeep;
  712. end;
  713. // OSes that only provide 1 byte versions can enable the following define
  714. {$ifdef executeprocuni}
  715. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  716. begin
  717. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  718. end;
  719. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  720. var
  721. ComLineA : array of RawByteString;
  722. I : Integer;
  723. begin
  724. SetLength(ComLineA,high(comline)-low(comline)+1);
  725. For I:=0 to length(ComLineA)-1 Do
  726. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  727. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  728. end;
  729. {$endif}
  730. // generic ifthen..
  731. {$IFNDEF VER3_0}
  732. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  733. begin
  734. if val then
  735. Result := ifTrue
  736. else
  737. Result:=ifFalse;
  738. end;
  739. generic function Exchange<T>(var target:T; const newvalue:T) :T;
  740. begin
  741. Result := target;
  742. target := newvalue;
  743. end;
  744. {$ENDIF}
  745. Function ArrayOfConstToStrArray(Args: array of const) : TUTF8StringDynArray;
  746. var
  747. i: Integer;
  748. O : TObject;
  749. C : TClass;
  750. S : String;
  751. begin
  752. SetLength(Result,Length(Args));
  753. for i:=Low(Args) to High(Args) do
  754. case Args[i].VType of
  755. vtInteger: Result[i]:=IntToStr(Args[i].VInteger);
  756. vtBoolean: Result[i]:=BoolToStr(Args[i].VBoolean);
  757. vtChar: Result[i] := Args[i].VChar;
  758. {$ifndef FPUNONE}
  759. vtExtended: Result[i]:= FloatToStr(Args[i].VExtended^);
  760. {$ENDIF}
  761. vtString: Result[i] := Args[i].VString^;
  762. vtPointer: Result[i] := '0x'+HexStr(PtrInt(Args[i].VPointer),SizeOF(PtrInt));
  763. vtPChar: Result[i] := Args[i].VPChar;
  764. vtObject:
  765. begin
  766. O:=Args[i].VObject;
  767. if Assigned(O) then
  768. begin
  769. try
  770. S:=O.ClassName;
  771. except
  772. S:='<Invalid instance>';
  773. end;
  774. end
  775. else
  776. S:='';
  777. Result[I] := '<Object '+S+' 0x'+HexStr(PtrInt(O),SizeOF(PtrInt))+'>';
  778. end;
  779. vtClass:
  780. begin
  781. C:=Args[i].VClass;
  782. if Assigned(C) then
  783. begin
  784. try
  785. S:=C.ClassName;
  786. except
  787. S:='<Invalid Class>';
  788. end;
  789. end
  790. else
  791. S:='';
  792. Result[I] := '<Class '+S+' 0x'+HexStr(PtrInt(C),SizeOF(PtrInt))+'>';
  793. end;
  794. vtWideChar: Result[i] := UTF8Encode(Args[i].VWideChar);
  795. vtPWideChar: Result[i] := UTF8Encode(Args[i].VPWideChar^);
  796. vtAnsiString: Result[i] := AnsiString(Args[i].VAnsiString);
  797. vtCurrency: Result[i] := FLoatToSTr(Args[i].VCurrency^);
  798. vtVariant: Result[i] := Args[i].VVariant^;
  799. vtInterface: Result[I] := '<Interface 0x'+HexStr(PtrInt(Args[i].VInterface),SizeOF(PtrInt))+'>';
  800. vtWidestring: Result[i] := UTF8ENcode(WideString(Args[i].VWideString));
  801. vtInt64: Result[i] := IntToStr(Args[i].VInt64^);
  802. vtQWord: Result[i] := IntToStr(Args[i].VQWord^);
  803. vtUnicodeString:Result[i] := UTF8Encode(UnicodeString(Args[i].VUnicodeString));
  804. end;
  805. end;
  806. Function ArrayOfConstToStr(Args: array of const ; aSeparator : Char = ','; aQuoteBegin : Char = '"'; aQuoteEnd : Char = '"') : UTF8String;
  807. Procedure Add(s: UTF8String);
  808. begin
  809. if aQuoteBegin<>#0 then
  810. S:=aQuoteBegin+S;
  811. if aQuoteEnd<>#0 then
  812. S:=S+aQuoteEnd;
  813. if Result<>'' then
  814. Result:=Result+aSeparator;
  815. Result:=Result+S;
  816. end;
  817. Var
  818. S : UTF8String;
  819. begin
  820. Result:='';
  821. For S in ArrayOfConstToStrArray(Args) do
  822. Add(S);
  823. end;
  824. Function GetCompiledArchitecture : TOSVersion.TArchitecture;
  825. begin
  826. Result:=arOther;
  827. {$ifdef i386}
  828. Result:=arIntelX86;
  829. {$endif i386}
  830. {$ifdef m68k}
  831. Result:=arM68k;
  832. {$endif m68k}
  833. {$ifdef powerpc}
  834. Result:=arPowerPC
  835. {$endif powerpc}
  836. {$ifdef powerpc64}
  837. Result:=arPower64
  838. {$endif powerpc64}
  839. {$ifdef arm}
  840. Result:=arARM32;
  841. {$endif arm}
  842. {$ifdef aarch64}
  843. Result:=arARM64
  844. {$endif aarch64}
  845. {$ifdef sparc}
  846. Result:=arSparc;
  847. {$endif sparc}
  848. {$ifdef sparc64}
  849. Result:=arSparc64;
  850. {$endif sparc64}
  851. {$ifdef CPUX86_64}
  852. Result:=arIntelX64;
  853. {$endif x86_64}
  854. {$ifdef mipsel}
  855. Result:=arMipsel
  856. {$else : not mipsel}
  857. {$ifdef mips}
  858. Result:=arMips;
  859. {$endif mips}
  860. {$endif not mipsel}
  861. {$ifdef riscv32}
  862. Result:=arRiscV32;
  863. {$endif riscv32}
  864. {$ifdef riscv64}
  865. Result:=arRiscV64;
  866. {$endif riscv64}
  867. {$ifdef xtensa}
  868. Result:=arXtensa;
  869. {$endif xtensa}
  870. {$ifdef wasm32}
  871. Result:=arWasm32;
  872. {$endif wasm32}
  873. {$ifdef loongarch64}
  874. Result:=arLoongArch64;
  875. {$endif loongarch64}
  876. end;
  877. Function GetCompiledPlatform : TOSVersion.TPlatform;
  878. begin
  879. Result:=pfOther;
  880. {$IFDEF WINDOWS}
  881. Result:=pfWindows;
  882. {$ENDIF}
  883. {$Ifdef darwin}
  884. Result:=pfMacOS;
  885. {$ENDIF}
  886. {$IFDEF IOS}
  887. Result:=pfiOS;
  888. {$ENDIF}
  889. {$IFDEF ANDROID}
  890. Result:=pfAndroid;
  891. {$ENDIF}
  892. {$IFDEF LINUX}
  893. Result:=pfLinux;
  894. {$ENDIF}
  895. {$IFDEF GO32V2}
  896. Result:=pfGo32v2;
  897. {$ENDIF}
  898. {$IFDEF OS2}
  899. Result:=pfOS2;
  900. {$ENDIF}
  901. {$IFDEF FREEBSD}
  902. Result:=pfFreeBSD;
  903. {$ENDIF}
  904. {$IFDEF BEOS}
  905. Result:=pfBeos;
  906. {$ENDIF}
  907. {$IFDEF NETBSD}
  908. Result:=pfNetBSD;
  909. {$ENDIF}
  910. {$IFDEF AMIGA}
  911. Result:=pfAmiga;
  912. {$ENDIF}
  913. {$IFDEF ATARI}
  914. Result:=pfAtari;
  915. {$ENDIF}
  916. {$IFDEF SUNOS}
  917. Result:=pfSolaris;
  918. {$ENDIF}
  919. {$IFDEF QNX}
  920. Result:=pfQNX;
  921. {$ENDIF}
  922. {$IFDEF Netware}
  923. Result:=pfNetware;
  924. {$ENDIF}
  925. {$IFDEF OpenBSD}
  926. Result:=pfOpenBSD;
  927. {$ENDIF}
  928. {$IFDEF WDosX}
  929. Result:=pfWDosX;
  930. {$ENDIF}
  931. {$IFDEF PALMOS}
  932. Result:=pfPalmos;
  933. {$ENDIF}
  934. {$IFDEF MacOSClassic}
  935. Result:=pfMacOSClassic;
  936. {$ENDIF}
  937. {$IFDEF DARWIN}
  938. Result:=pfDarwin;
  939. {$ENDIF}
  940. {$IFDEF EMX}
  941. Result:=pfEMX;
  942. {$ENDIF}
  943. {$IFDEF WATCOM}
  944. Result:=pfWatcom;
  945. {$ENDIF}
  946. {$IFDEF MORPHOS}
  947. Result:=pfMorphos;
  948. {$ENDIF}
  949. {$IFDEF NETWLIBC}
  950. Result:=pfNetwLibC;
  951. {$ENDIF}
  952. {$IFDEF WINCE}
  953. Result:=pfWinCE;
  954. {$ENDIF}
  955. {$IFDEF GBA}
  956. Result:=pfGBA;
  957. {$ENDIF}
  958. {$IFDEF NDS}
  959. Result:=pfNDS;
  960. {$ENDIF}
  961. {$IFDEF EMBEDDED}
  962. Result:=pfEmbedded;
  963. {$ENDIF}
  964. {$IFDEF SYMBIAN}
  965. Result:=pfSymbian;
  966. {$ENDIF}
  967. {$IFDEF HAIKU}
  968. Result:=pfHaiku;
  969. {$ENDIF}
  970. {$IFDEF IPHONESIM}
  971. Result:=pfIPhoneSim;
  972. {$ENDIF}
  973. {$IFDEF AIX}
  974. Result:=pfAIX;
  975. {$ENDIF}
  976. {$IFDEF JAVA}
  977. Result:=pfJava;
  978. {$ENDIF}
  979. {$IFDEF NATIVENT}
  980. Result:=pfNativeNT;
  981. {$ENDIF}
  982. {$IFDEF MSDOS}
  983. Result:=pfMSDos;
  984. {$ENDIF}
  985. {$IFDEF WII}
  986. Result:=pfWII;
  987. {$ENDIF}
  988. {$IFDEF AROS}
  989. Result:=pfAROS;
  990. {$ENDIF}
  991. {$IFDEF DRAGONFLY}
  992. Result:=pfDragonFly;
  993. {$ENDIF}
  994. {$IFDEF WIN16}
  995. Result:=pfWin16;
  996. {$ENDIF}
  997. {$IFDEF FREERTOS}
  998. Result:=pfFreeRTOS;
  999. {$ENDIF}
  1000. {$IFDEF ZXSPECTRUM}
  1001. Result:=pfZXSpectrum;
  1002. {$ENDIF}
  1003. {$IFDEF MSXDOS}
  1004. Result:=pfMSXDOS;
  1005. {$ENDIF}
  1006. {$IFDEF AMSTRADCPC}
  1007. Result:=pfAmstradCPC;
  1008. {$ENDIF}
  1009. {$IFDEF SINCLAIRQL}
  1010. Result:=pfSinclairQL;
  1011. {$ENDIF}
  1012. {$IFDEF WASI}
  1013. Result:=pfWasi;
  1014. {$ENDIF}
  1015. end;
  1016. class constructor TOSVersion.Create;
  1017. {$IFNDEF HAS_OSVERSION}
  1018. var
  1019. S : String;
  1020. {$ENDIF}
  1021. begin
  1022. FArchitecture:=GetCompiledArchitecture;
  1023. FPlatform:=GetCompiledPlatform;
  1024. FBuild:=0;
  1025. FMajor:=0;
  1026. FMinor:=0;
  1027. FServicePackMajor:=0;
  1028. FServicePackMinor:=0;
  1029. {$IFDEF HAS_OSVERSION}
  1030. InitOSVersion;
  1031. {$ELSE}
  1032. WriteStr(S,GetCompiledPlatform);
  1033. FName:=Copy(S,3);
  1034. WriteStr(S,GetCompiledArchitecture);
  1035. FFull:=Copy(S,3)+'-'+FName;
  1036. {$ENDIF}
  1037. end;
  1038. class function TOSVersion.Check(aMajor: Integer): Boolean; overload; static; inline;
  1039. begin
  1040. Result:=(Major>=aMajor);
  1041. end;
  1042. class function TOSVersion.Check(aMajor, aMinor: Integer): Boolean; overload; static; inline;
  1043. begin
  1044. Result:=(Major>aMajor)
  1045. or ((Major=aMajor) and (Minor>=aMinor))
  1046. end;
  1047. class function TOSVersion.Check(aMajor, aMinor, aServicePackMajor: Integer): Boolean; overload; static; inline;
  1048. begin
  1049. Result:=(Major>AMajor)
  1050. or ((Major=aMajor) and (Minor>aMinor))
  1051. or ((Major=aMajor) and (Minor=aMinor) and (ServicePackMajor>=aServicePackMajor));
  1052. end;
  1053. class function TOSVersion.ToString: string; static;
  1054. begin
  1055. Result:=FFull;
  1056. end;