2
0

sysutils.inc 30 KB

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