sysutils.inc 29 KB

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