sysutils.inc 28 KB

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