sysutils.inc 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  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. begin
  382. Case Errno of
  383. 1,203 : E:=OutOfMemory;
  384. 204 : E:=InvalidPointer;
  385. else
  386. Entry:=FindExceptMapEntry(ErrNo);
  387. if Assigned(Entry) then
  388. E:=Entry^.cls.CreateRes(Entry^.msg)
  389. else
  390. begin
  391. HS:=nil;
  392. Case Errno of
  393. 2 : HS:=@SFileNotFound;
  394. 3 : HS:=@SInvalidFileName;
  395. 4 : HS:=@STooManyOpenFiles;
  396. 5 : HS:=@SAccessDenied;
  397. 6 : HS:=@SInvalidFileHandle;
  398. 15 : HS:=@SInvalidDrive;
  399. 100 : HS:=@SEndOfFile;
  400. 101 : HS:=@SDiskFull;
  401. 102 : HS:=@SFileNotAssigned;
  402. 103 : HS:=@SFileNotOpen;
  403. 104 : HS:=@SFileNotOpenForInput;
  404. 105 : HS:=@SFileNotOpenForOutput;
  405. 106 : HS:=@SInvalidInput;
  406. end;
  407. if Assigned(HS) then
  408. E:=EInOutError.CreateRes(HS)
  409. else
  410. E:=EInOutError.CreateResFmt(@SUnknownRunTimeError,[errno]);
  411. // this routine can be called from FPC_IOCHECK,
  412. // which clears inoutres and then passes its
  413. // original value to HandleErrorFrame() (which calls
  414. // us). So use errno rather than IOResult, and clear
  415. // InOutRes explicitly in case we can also be called
  416. // from a place that does not clear InOutRes explicitly
  417. EInoutError(E).ErrorCode:=errno;
  418. inoutres:=0;
  419. end;
  420. end;
  421. Raise E at Address,Frame;
  422. end;
  423. {$IFDEF HAS_OSERROR}
  424. Procedure RaiseLastOSError;overload;
  425. begin
  426. RaiseLastOSError(GetLastOSError);
  427. end;
  428. Procedure RaiseLastOSError(LastError: Integer);overload;
  429. var
  430. E : EOSError;
  431. begin
  432. If (LastError<>0) then
  433. E:=EOSError.CreateFmt(SOSError, [LastError, SysErrorMessage(LastError)])
  434. else
  435. E:=EOSError.Create(SUnkOSError);
  436. E.ErrorCode:=LastError;
  437. Raise E;
  438. end;
  439. {$else}
  440. Procedure RaiseLastOSError;overload;
  441. begin
  442. Raise Exception.Create('RaiseLastOSError not implemented on this platform.');
  443. end;
  444. Procedure RaiseLastOSError(LastError: Integer);overload;
  445. begin
  446. RaiseLastOSError;
  447. end;
  448. {$endif}
  449. procedure CheckOSError(LastError: Integer);
  450. begin
  451. if LastError <> 0 then
  452. RaiseLastOSError(LastError);
  453. end;
  454. Procedure AssertErrorHandler (Const Msg,FN : ShortString;LineNo:longint; TheAddr : pointer);
  455. Var
  456. S : String;
  457. begin
  458. If Msg='' then
  459. S:=SAssertionFailed
  460. else
  461. S:=Msg;
  462. Raise EAssertionFailed.Createfmt(SAssertError,[S,Fn,LineNo]) at get_caller_addr(theAddr), get_caller_frame(theAddr);
  463. end;
  464. {$pop} //{$S-} for Error handling functions
  465. procedure RangeIndexError(aIndex, aMaxIndex: SizeInt; aListObj: TObject);
  466. begin
  467. raise ERangeError.Create(ListIndexErrorMsg(aIndex,aMaxIndex,aListObj));
  468. end;
  469. Procedure InitExceptions;
  470. {
  471. Must install uncaught exception handler (ExceptProc)
  472. and install exceptions for system exceptions or signals.
  473. (e.g: SIGSEGV -> ESegFault or so.)
  474. }
  475. begin
  476. ExceptionClass := Exception;
  477. ExceptProc:=@CatchUnhandledException;
  478. // Create objects that may have problems when there is no memory.
  479. OutOfMemory:=EOutOfMemory.Create(SOutOfMemory);
  480. InvalidPointer:=EInvalidPointer.Create(SInvalidPointer);
  481. AssertErrorProc:=@AssertErrorHandler;
  482. ErrorProc:=@RunErrorToExcept;
  483. OnShowException:=Nil;
  484. end;
  485. Procedure DoneExceptions;
  486. begin
  487. FreeAndNil(OutOfMemory); { These will automatically work as they first set pointer to nil, then free the object. See EHeapMemoryError.FreeInstance. }
  488. FreeAndNil(InValidPointer);
  489. end;
  490. { Exception handling routines }
  491. function ExceptObject: TObject;
  492. begin
  493. If RaiseList=Nil then
  494. Result:=Nil
  495. else
  496. Result:=RaiseList^.FObject;
  497. end;
  498. function ExceptAddr: CodePointer;
  499. begin
  500. If RaiseList=Nil then
  501. Result:=Nil
  502. else
  503. Result:=RaiseList^.Addr;
  504. end;
  505. function ExceptFrameCount: Longint;
  506. begin
  507. If RaiseList=Nil then
  508. Result:=0
  509. else
  510. Result:=RaiseList^.Framecount;
  511. end;
  512. function ExceptFrames: PCodePointer;
  513. begin
  514. If RaiseList=Nil then
  515. Result:=Nil
  516. else
  517. Result:=RaiseList^.Frames;
  518. end;
  519. function ExceptionErrorMessage(ExceptObject: TObject; ExceptAddr: Pointer;
  520. Buffer: PAnsiChar; Size: Integer): Integer;
  521. Var
  522. S : AnsiString;
  523. Len : Integer;
  524. begin
  525. S:=Format(SExceptionErrorMessage,[ExceptAddr,ExceptObject.ClassName]);
  526. If ExceptObject is Exception then
  527. S:=Format('%s:'#10'%s',[S,Exception(ExceptObject).Message]);
  528. Len:=Length(S);
  529. If S[Len]<>'.' then
  530. begin
  531. S:=S+'.';
  532. Inc(len);
  533. end;
  534. If Len>Size then
  535. Len:=Size;
  536. if Len > 0 then
  537. Move(S[1],Buffer^,Len);
  538. Result:=Len;
  539. end;
  540. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  541. // use shortstring. On exception, the heap may be corrupt.
  542. Var
  543. Buf : ShortString;
  544. begin
  545. SetLength(Buf,ExceptionErrorMessage(ExceptObject,ExceptAddr,@Buf[1],255));
  546. If IsConsole Then
  547. writeln(Buf)
  548. else
  549. If Assigned(OnShowException) Then
  550. OnShowException (Buf);
  551. end;
  552. procedure Abort;
  553. begin
  554. Raise EAbort.Create(SAbortError) at CodePointer(Get_Caller_addr(Get_Frame));
  555. end;
  556. procedure OutOfMemoryError;
  557. begin
  558. Raise OutOfMemory;
  559. end;
  560. function ListIndexErrorMsg(aIndex, aMaxIndex: SizeInt; const aListObjName: string): string; overload;
  561. begin
  562. if aMaxIndex<0 then
  563. Result:=Format(SListIndexErrorEmptyReason,[aListObjName])
  564. else
  565. Result:=Format(SListIndexErrorRangeReason,[aListObjName]);
  566. Result:=Format(SListIndexError, [aIndex])+Result;
  567. end;
  568. function ListIndexErrorMsg(AIndex, AMaxIndex: SizeInt; AListObj: TObject): string; overload;
  569. Var
  570. aName : string;
  571. begin
  572. if Assigned(aListObj) then
  573. Result:=aListObj.ClassName
  574. else
  575. Result:='<Nil>';
  576. Result:=ListIndexErrorMsg(aIndex, aMaxIndex, aName);
  577. end;
  578. procedure ListIndexError(aIndex,aMax: Integer; aObj: TObject);
  579. var
  580. aClassName : string;
  581. begin
  582. if Assigned(aObj) then
  583. aClassName:=aObj.ClassName
  584. else
  585. aClassName:='<nil>';
  586. Raise EListError.CreateFmt(SErrListIndexExt,[aIndex,aClassName,aMax])
  587. end;
  588. { ---------------------------------------------------------------------
  589. Initialization/Finalization/exit code
  590. ---------------------------------------------------------------------}
  591. Type
  592. PPRecord = ^TPRecord;
  593. TPRecord = Record
  594. Func : TTerminateProc;
  595. NextFunc : PPRecord;
  596. end;
  597. Const
  598. TPList : PPRecord = Nil;
  599. procedure AddTerminateProc(TermProc: TTerminateProc);
  600. Var
  601. TPR : PPRecord;
  602. begin
  603. New(TPR);
  604. With TPR^ do
  605. begin
  606. NextFunc:=TPList;
  607. Func:=TermProc;
  608. end;
  609. TPList:=TPR;
  610. end;
  611. function CallTerminateProcs: Boolean;
  612. Var
  613. TPR : PPRecord;
  614. begin
  615. Result:=True;
  616. TPR:=TPList;
  617. While Result and (TPR<>Nil) do
  618. begin
  619. Result:=TPR^.Func();
  620. TPR:=TPR^.NextFunc;
  621. end;
  622. end;
  623. procedure FreeTerminateProcs;
  624. var
  625. TPR1, TPR2: PPRecord;
  626. begin
  627. TPR1 := TPList;
  628. TPList := Nil;
  629. while Assigned(TPR1) do begin
  630. TPR2 := TPR1^.NextFunc;
  631. Dispose(TPR1);
  632. TPR1 := TPR2;
  633. end;
  634. end;
  635. { ---------------------------------------------------------------------
  636. Diskh functions, OS independent.
  637. ---------------------------------------------------------------------}
  638. Function GetCurrentDir: {$ifdef FPC_UNICODE_RTL}UnicodeString{$else}AnsiString{$endif};
  639. begin
  640. GetDir(0,Result);
  641. end;
  642. { ---------------------------------------------------------------------
  643. Other functions, OS independent.
  644. ---------------------------------------------------------------------}
  645. Var
  646. GUIDCalledRandomize : Boolean = False;
  647. Procedure GetRandomBytes(Var Buf; NBytes : Integer);
  648. Var
  649. I : Integer;
  650. P : PByte;
  651. begin
  652. P:=@Buf;
  653. If Not GUIDCalledRandomize then
  654. begin
  655. Randomize;
  656. GUIDCalledRandomize:=True;
  657. end;
  658. For I:=0 to NBytes-1 do
  659. P[i]:=Random(256);
  660. end;
  661. {$IFDEF HASCREATEGUID}
  662. Function SysCreateGUID(out GUID : TGUID) : Integer; forward;
  663. {$ENDIF}
  664. Function CreateGUID(out GUID : TGUID) : Integer;
  665. begin
  666. If Assigned(OnCreateGUID) then
  667. Result:=OnCreateGUID(GUID)
  668. else
  669. begin
  670. {$IFDEF HASCREATEGUID}
  671. Result:=SysCreateGUID(GUID);
  672. {$ELSE}
  673. GetRandomBytes(GUID,SizeOf(Guid));
  674. guid.clock_seq_hi_and_reserved:=(guid.clock_seq_hi_and_reserved and $3F) + 64;
  675. guid.time_hi_and_version :=(guid.time_hi_and_version and $0FFF)+ $4000;
  676. Result:=0;
  677. {$ENDIF}
  678. end;
  679. end;
  680. function SafeLoadLibrary(const FileName: AnsiString; ErrorMode: DWord = {$ifdef windows}SEM_NOOPENFILEERRORBOX{$else windows}0{$endif windows}): HMODULE;
  681. {$if defined(win64) or defined(win32)}
  682. var
  683. mode : DWord;
  684. begin
  685. mode:=SetErrorMode(ErrorMode);
  686. try
  687. Result:=System.SafeLoadLibrary(FileName);
  688. finally
  689. SetErrorMode(mode);
  690. end;
  691. end;
  692. {$else}
  693. begin
  694. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  695. Result:=System.SafeLoadLibrary(FileName);
  696. {$else}
  697. Result:=HModule(nil);
  698. {$endif not FPC_HAS_FEATURE_DYNLIBS}
  699. end;
  700. {$endif}
  701. {$if defined(win32) or defined(win64) or defined(wince)}
  702. function GetModuleName(Module: HMODULE): string;
  703. var
  704. ResultLength, BufferLength: DWORD;
  705. Buffer: UnicodeString;
  706. begin
  707. BufferLength := MAX_PATH div 2;
  708. repeat
  709. Inc(BufferLength, BufferLength);
  710. SetLength(Buffer, BufferLength);
  711. ResultLength := GetModuleFileNameW(Module, Pointer(Buffer), BufferLength);
  712. if ResultLength = 0 then
  713. Exit('');
  714. until ResultLength < BufferLength;
  715. SetLength(Buffer, ResultLength);
  716. Result := Buffer;
  717. end;
  718. {$elseif defined(win16)}
  719. function GetModuleName(Module: HMODULE): string;
  720. var
  721. ResultLength, BufferLength: DWORD;
  722. Buffer: RawByteString;
  723. begin
  724. BufferLength := MAX_PATH div 2;
  725. repeat
  726. Inc(BufferLength, BufferLength);
  727. SetLength(Buffer, BufferLength);
  728. ResultLength := GetModuleFileName(Module, FarAddr(Buffer[1]), BufferLength);
  729. if ResultLength = 0 then
  730. Exit('');
  731. until ResultLength < BufferLength;
  732. SetLength(Buffer, ResultLength);
  733. Result := Buffer;
  734. end;
  735. {$else}
  736. function GetModuleName(Module: HMODULE): string;
  737. begin
  738. Result:='';
  739. end;
  740. {$endif}
  741. { Beep support }
  742. procedure Beep;
  743. begin
  744. If Assigned(OnBeep) then
  745. OnBeep;
  746. end;
  747. // OSes that only provide 1 byte versions can enable the following define
  748. {$ifdef executeprocuni}
  749. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: UnicodeString;Flags:TExecuteFlags=[]):integer;
  750. begin
  751. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ToSingleByteFileSystemEncodedFileName(ComLine));
  752. end;
  753. function ExecuteProcess(Const Path: UnicodeString; Const ComLine: Array of UnicodeString;Flags:TExecuteFlags=[]):integer;
  754. var
  755. ComLineA : array of RawByteString;
  756. I : Integer;
  757. begin
  758. SetLength(ComLineA,high(comline)-low(comline)+1);
  759. For I:=0 to length(ComLineA)-1 Do
  760. ComLineA[i]:=ToSingleByteFileSystemEncodedFileName(ComLine[I]);
  761. result:=ExecuteProcess(ToSingleByteFileSystemEncodedFileName(Path),ComLineA);
  762. end;
  763. {$endif}
  764. // generic ifthen..
  765. generic function IfThen<T>(val:boolean;const iftrue:T; const iffalse:T) :T; inline; overload;
  766. begin
  767. if val then
  768. Result := ifTrue
  769. else
  770. Result:=ifFalse;
  771. end;
  772. generic function Exchange<T>(var target:T; const newvalue:T) :T;
  773. begin
  774. Result := target;
  775. target := newvalue;
  776. end;
  777. generic function Extract<T>(var from: T) :T;
  778. type
  779. RawT = array[0 .. sizeof(T) - 1] of byte;
  780. begin
  781. Finalize(Result);
  782. RawT(Result):=RawT(from);
  783. Initialize(from);
  784. end;
  785. generic procedure Swap<T>(var lhs,rhs: T);
  786. type
  787. RawT = array[0 .. sizeof(T) - 1] of byte;
  788. var
  789. tmp:RawT;
  790. begin
  791. tmp:=RawT(lhs);
  792. RawT(lhs):=RawT(rhs);
  793. RawT(rhs):=tmp;
  794. end;
  795. Function ArrayOfConstToStrArray(const Args: array of const) : TUTF8StringDynArray;
  796. var
  797. i: Integer;
  798. O : TObject;
  799. C : TClass;
  800. S : String;
  801. begin
  802. SetLength(Result,Length(Args));
  803. for i:=Low(Args) to High(Args) do
  804. case Args[i].VType of
  805. vtInteger: Result[i]:=IntToStr(Args[i].VInteger);
  806. vtBoolean: Result[i]:=BoolToStr(Args[i].VBoolean);
  807. vtChar: Result[i] := Args[i].VChar;
  808. {$ifndef FPUNONE}
  809. vtExtended: Result[i]:= FloatToStr(Args[i].VExtended^);
  810. {$ENDIF}
  811. vtString: Result[i] := Args[i].VString^;
  812. vtPointer: Result[i] := '0x'+HexStr(PtrInt(Args[i].VPointer),SizeOF(PtrInt));
  813. vtPChar: Result[i] := Args[i].VPChar;
  814. vtObject:
  815. begin
  816. O:=Args[i].VObject;
  817. if Assigned(O) then
  818. begin
  819. try
  820. S:=O.ClassName;
  821. except
  822. S:='<Invalid instance>';
  823. end;
  824. end
  825. else
  826. S:='';
  827. Result[I] := '<Object '+S+' 0x'+HexStr(PtrInt(O),SizeOF(PtrInt))+'>';
  828. end;
  829. vtClass:
  830. begin
  831. C:=Args[i].VClass;
  832. if Assigned(C) then
  833. begin
  834. try
  835. S:=C.ClassName;
  836. except
  837. S:='<Invalid Class>';
  838. end;
  839. end
  840. else
  841. S:='';
  842. Result[I] := '<Class '+S+' 0x'+HexStr(PtrInt(C),SizeOF(PtrInt))+'>';
  843. end;
  844. vtWideChar: Result[i] := UTF8Encode(Args[i].VWideChar);
  845. vtPWideChar: Result[i] := UTF8Encode(Args[i].VPWideChar^);
  846. vtAnsiString: Result[i] := AnsiString(Args[i].VAnsiString);
  847. vtCurrency: Result[i] := FLoatToSTr(Args[i].VCurrency^);
  848. vtVariant: Result[i] := Args[i].VVariant^;
  849. vtInterface: Result[I] := '<Interface 0x'+HexStr(PtrInt(Args[i].VInterface),SizeOF(PtrInt))+'>';
  850. vtWidestring: Result[i] := UTF8ENcode(WideString(Args[i].VWideString));
  851. vtInt64: Result[i] := IntToStr(Args[i].VInt64^);
  852. vtQWord: Result[i] := IntToStr(Args[i].VQWord^);
  853. vtUnicodeString:Result[i] := UTF8Encode(UnicodeString(Args[i].VUnicodeString));
  854. end;
  855. end;
  856. Function ArrayOfConstToStr(const Args: array of const ; aSeparator : Char = ','; aQuoteBegin : Char = '"'; aQuoteEnd : Char = '"') : UTF8String;
  857. Procedure Add(s: UTF8String);
  858. begin
  859. if aQuoteBegin<>#0 then
  860. S:=aQuoteBegin+S;
  861. if aQuoteEnd<>#0 then
  862. S:=S+aQuoteEnd;
  863. if Result<>'' then
  864. Result:=Result+aSeparator;
  865. Result:=Result+S;
  866. end;
  867. Var
  868. S : UTF8String;
  869. begin
  870. Result:='';
  871. For S in ArrayOfConstToStrArray(Args) do
  872. Add(S);
  873. end;
  874. Function GetCompiledArchitecture : TOSVersion.TArchitecture;
  875. begin
  876. Result:=arOther;
  877. {$ifdef i386}
  878. Result:=arIntelX86;
  879. {$endif i386}
  880. {$ifdef m68k}
  881. Result:=arM68k;
  882. {$endif m68k}
  883. {$ifdef powerpc}
  884. Result:=arPowerPC
  885. {$endif powerpc}
  886. {$ifdef powerpc64}
  887. Result:=arPower64
  888. {$endif powerpc64}
  889. {$ifdef arm}
  890. Result:=arARM32;
  891. {$endif arm}
  892. {$ifdef aarch64}
  893. Result:=arARM64
  894. {$endif aarch64}
  895. {$ifdef sparc}
  896. Result:=arSparc;
  897. {$endif sparc}
  898. {$ifdef sparc64}
  899. Result:=arSparc64;
  900. {$endif sparc64}
  901. {$ifdef CPUX86_64}
  902. Result:=arIntelX64;
  903. {$endif x86_64}
  904. {$ifdef mipsel}
  905. Result:=arMipsel
  906. {$else : not mipsel}
  907. {$ifdef mips}
  908. Result:=arMips;
  909. {$endif mips}
  910. {$endif not mipsel}
  911. {$ifdef riscv32}
  912. Result:=arRiscV32;
  913. {$endif riscv32}
  914. {$ifdef riscv64}
  915. Result:=arRiscV64;
  916. {$endif riscv64}
  917. {$ifdef xtensa}
  918. Result:=arXtensa;
  919. {$endif xtensa}
  920. {$ifdef wasm32}
  921. Result:=arWasm32;
  922. {$endif wasm32}
  923. {$ifdef loongarch64}
  924. Result:=arLoongArch64;
  925. {$endif loongarch64}
  926. end;
  927. Function GetCompiledPlatform : TOSVersion.TPlatform;
  928. begin
  929. Result:=pfOther;
  930. {$IFDEF WINDOWS}
  931. Result:=pfWindows;
  932. {$ENDIF}
  933. {$Ifdef darwin}
  934. Result:=pfMacOS;
  935. {$ENDIF}
  936. {$IFDEF IOS}
  937. Result:=pfiOS;
  938. {$ENDIF}
  939. {$IFDEF ANDROID}
  940. Result:=pfAndroid;
  941. {$ENDIF}
  942. {$IFDEF LINUX}
  943. Result:=pfLinux;
  944. {$ENDIF}
  945. {$IFDEF GO32V2}
  946. Result:=pfGo32v2;
  947. {$ENDIF}
  948. {$IFDEF OS2}
  949. Result:=pfOS2;
  950. {$ENDIF}
  951. {$IFDEF FREEBSD}
  952. Result:=pfFreeBSD;
  953. {$ENDIF}
  954. {$IFDEF BEOS}
  955. Result:=pfBeos;
  956. {$ENDIF}
  957. {$IFDEF NETBSD}
  958. Result:=pfNetBSD;
  959. {$ENDIF}
  960. {$IFDEF AMIGA}
  961. Result:=pfAmiga;
  962. {$ENDIF}
  963. {$IFDEF ATARI}
  964. Result:=pfAtari;
  965. {$ENDIF}
  966. {$IFDEF SUNOS}
  967. Result:=pfSolaris;
  968. {$ENDIF}
  969. {$IFDEF QNX}
  970. Result:=pfQNX;
  971. {$ENDIF}
  972. {$IFDEF Netware}
  973. Result:=pfNetware;
  974. {$ENDIF}
  975. {$IFDEF OpenBSD}
  976. Result:=pfOpenBSD;
  977. {$ENDIF}
  978. {$IFDEF WDosX}
  979. Result:=pfWDosX;
  980. {$ENDIF}
  981. {$IFDEF PALMOS}
  982. Result:=pfPalmos;
  983. {$ENDIF}
  984. {$IFDEF MacOSClassic}
  985. Result:=pfMacOSClassic;
  986. {$ENDIF}
  987. {$IFDEF DARWIN}
  988. Result:=pfDarwin;
  989. {$ENDIF}
  990. {$IFDEF EMX}
  991. Result:=pfEMX;
  992. {$ENDIF}
  993. {$IFDEF WATCOM}
  994. Result:=pfWatcom;
  995. {$ENDIF}
  996. {$IFDEF MORPHOS}
  997. Result:=pfMorphos;
  998. {$ENDIF}
  999. {$IFDEF NETWLIBC}
  1000. Result:=pfNetwLibC;
  1001. {$ENDIF}
  1002. {$IFDEF WINCE}
  1003. Result:=pfWinCE;
  1004. {$ENDIF}
  1005. {$IFDEF GBA}
  1006. Result:=pfGBA;
  1007. {$ENDIF}
  1008. {$IFDEF NDS}
  1009. Result:=pfNDS;
  1010. {$ENDIF}
  1011. {$IFDEF EMBEDDED}
  1012. Result:=pfEmbedded;
  1013. {$ENDIF}
  1014. {$IFDEF SYMBIAN}
  1015. Result:=pfSymbian;
  1016. {$ENDIF}
  1017. {$IFDEF HAIKU}
  1018. Result:=pfHaiku;
  1019. {$ENDIF}
  1020. {$IFDEF IPHONESIM}
  1021. Result:=pfIPhoneSim;
  1022. {$ENDIF}
  1023. {$IFDEF AIX}
  1024. Result:=pfAIX;
  1025. {$ENDIF}
  1026. {$IFDEF JAVA}
  1027. Result:=pfJava;
  1028. {$ENDIF}
  1029. {$IFDEF NATIVENT}
  1030. Result:=pfNativeNT;
  1031. {$ENDIF}
  1032. {$IFDEF MSDOS}
  1033. Result:=pfMSDos;
  1034. {$ENDIF}
  1035. {$IFDEF WII}
  1036. Result:=pfWII;
  1037. {$ENDIF}
  1038. {$IFDEF AROS}
  1039. Result:=pfAROS;
  1040. {$ENDIF}
  1041. {$IFDEF DRAGONFLY}
  1042. Result:=pfDragonFly;
  1043. {$ENDIF}
  1044. {$IFDEF WIN16}
  1045. Result:=pfWin16;
  1046. {$ENDIF}
  1047. {$IFDEF FREERTOS}
  1048. Result:=pfFreeRTOS;
  1049. {$ENDIF}
  1050. {$IFDEF ZXSPECTRUM}
  1051. Result:=pfZXSpectrum;
  1052. {$ENDIF}
  1053. {$IFDEF MSXDOS}
  1054. Result:=pfMSXDOS;
  1055. {$ENDIF}
  1056. {$IFDEF AMSTRADCPC}
  1057. Result:=pfAmstradCPC;
  1058. {$ENDIF}
  1059. {$IFDEF SINCLAIRQL}
  1060. Result:=pfSinclairQL;
  1061. {$ENDIF}
  1062. {$IFDEF WASI}
  1063. Result:=pfWasi;
  1064. {$ENDIF}
  1065. end;
  1066. class constructor TOSVersion.Create;
  1067. {$IFNDEF HAS_OSVERSION}
  1068. var
  1069. S : String;
  1070. {$ENDIF}
  1071. begin
  1072. FArchitecture:=GetCompiledArchitecture;
  1073. FPlatform:=GetCompiledPlatform;
  1074. FBuild:=0;
  1075. FMajor:=0;
  1076. FMinor:=0;
  1077. FServicePackMajor:=0;
  1078. FServicePackMinor:=0;
  1079. {$IFDEF HAS_OSVERSION}
  1080. InitOSVersion;
  1081. {$ELSE}
  1082. WriteStr(S,GetCompiledPlatform);
  1083. FName:=Copy(S,3);
  1084. WriteStr(S,GetCompiledArchitecture);
  1085. FFull:=Copy(S,3)+'-'+FName;
  1086. {$ENDIF}
  1087. end;
  1088. class function TOSVersion.Check(aMajor: Integer): Boolean; overload; static; inline;
  1089. begin
  1090. Result:=(Major>=aMajor);
  1091. end;
  1092. class function TOSVersion.Check(aMajor, aMinor: Integer): Boolean; overload; static; inline;
  1093. begin
  1094. Result:=(Major>aMajor)
  1095. or ((Major=aMajor) and (Minor>=aMinor))
  1096. end;
  1097. class function TOSVersion.Check(aMajor, aMinor, aServicePackMajor: Integer): Boolean; overload; static; inline;
  1098. begin
  1099. Result:=(Major>AMajor)
  1100. or ((Major=aMajor) and (Minor>aMinor))
  1101. or ((Major=aMajor) and (Minor=aMinor) and (ServicePackMajor>=aServicePackMajor));
  1102. end;
  1103. class function TOSVersion.ToString: string; static;
  1104. begin
  1105. Result:=FFull;
  1106. end;