system.inc 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. {
  2. This file is part of the Free Pascal Run time library.
  3. Copyright (c) 1999-2000 by the Free Pascal development team
  4. See the file COPYING.FPC, included in this distribution,
  5. For details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************}
  10. {****************************************************************************
  11. Local types
  12. ****************************************************************************}
  13. {
  14. TextRec and FileRec are put in a separate file to make it available to other
  15. units without putting it explicitly in systemh.
  16. This way we keep TP compatibility, and the TextRec definition is available
  17. for everyone who needs it.
  18. }
  19. {$i filerec.inc}
  20. {$i textrec.inc}
  21. Procedure HandleError (Errno : Longint); forward;
  22. Procedure HandleErrorFrame (Errno : longint;frame : Pointer); forward;
  23. type
  24. FileFunc = Procedure(var t : TextRec);
  25. const
  26. STACK_MARGIN = 16384; { Stack size margin for stack checking }
  27. { Random / Randomize constants }
  28. OldRandSeed : Cardinal = 0;
  29. { For Error Handling.}
  30. ErrorBase : Pointer = nil;
  31. { Used by the ansistrings and maybe also other things in the future }
  32. var
  33. emptychar : char;public name 'FPC_EMPTYCHAR';
  34. initialstklen : SizeUint;external name '__stklen';
  35. { checks whether the given suggested size for the stack of the current
  36. thread is acceptable. If this is the case, returns it unaltered.
  37. Otherwise it should return an acceptable value.
  38. Operating systems that automatically expand their stack on demand, should
  39. simply return a very large value.
  40. Operating systems which do not have a possibility to retrieve stack size
  41. information, should simply return the given stklen value (This is the default
  42. implementation).
  43. }
  44. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt; forward;
  45. {****************************************************************************
  46. Include processor specific routines
  47. ****************************************************************************}
  48. {$ifdef FPC_USE_LIBC}
  49. { prefer libc implementations over our own, as they're most likely faster }
  50. {$i cgeneric.inc}
  51. { is now declared as external reference to another routine in the interface }
  52. {$i cgenstr.inc}
  53. {$endif FPC_USE_LIBC}
  54. {$ifdef cpui386}
  55. {$ifdef SYSPROCDEFINED}
  56. {$Error Can't determine processor type !}
  57. {$endif}
  58. {$i i386.inc} { Case dependent, don't change }
  59. {$endif cpui386}
  60. {$ifdef cpum68k}
  61. {$ifdef SYSPROCDEFINED}
  62. {$Error Can't determine processor type !}
  63. {$endif}
  64. {$i m68k.inc} { Case dependent, don't change }
  65. {$define SYSPROCDEFINED}
  66. {$endif cpum68k}
  67. {$ifdef cpux86_64}
  68. {$ifdef SYSPROCDEFINED}
  69. {$Error Can't determine processor type !}
  70. {$endif}
  71. {$i x86_64.inc} { Case dependent, don't change }
  72. {$define SYSPROCDEFINED}
  73. {$endif cpux86_64}
  74. {$ifdef cpupowerpc32}
  75. {$ifdef SYSPROCDEFINED}
  76. {$Error Can't determine processor type !}
  77. {$endif}
  78. {$i powerpc.inc} { Case dependent, don't change }
  79. {$define SYSPROCDEFINED}
  80. {$endif cpupowerpc32}
  81. {$ifdef cpupowerpc64}
  82. {$ifdef SYSPROCDEFINED}
  83. {$Error Can't determine processor type !}
  84. {$endif}
  85. {$i powerpc64.inc} { Case dependent, don't change }
  86. {$define SYSPROCDEFINED}
  87. {$endif cpupowerpc64}
  88. {$ifdef cpualpha}
  89. {$ifdef SYSPROCDEFINED}
  90. {$Error Can't determine processor type !}
  91. {$endif}
  92. {$i alpha.inc} { Case dependent, don't change }
  93. {$define SYSPROCDEFINED}
  94. {$endif cpualpha}
  95. {$ifdef cpuiA64}
  96. {$ifdef SYSPROCDEFINED}
  97. {$Error Can't determine processor type !}
  98. {$endif}
  99. {$i ia64.inc} { Case dependent, don't change }
  100. {$define SYSPROCDEFINED}
  101. {$endif cpuiA64}
  102. {$ifdef cpusparc}
  103. {$ifdef SYSPROCDEFINED}
  104. {$Error Can't determine processor type !}
  105. {$endif}
  106. {$i sparc.inc} { Case dependent, don't change }
  107. {$define SYSPROCDEFINED}
  108. {$endif cpusparc}
  109. {$ifdef cpuarm}
  110. {$ifdef SYSPROCDEFINED}
  111. {$Error Can't determine processor type !}
  112. {$endif}
  113. {$i arm.inc} { Case dependent, don't change }
  114. {$define SYSPROCDEFINED}
  115. {$endif cpuarm}
  116. procedure fillchar(var x;count : SizeInt;value : boolean);{$ifdef SYSTEMINLINE}inline;{$endif}
  117. begin
  118. fillchar(x,count,byte(value));
  119. end;
  120. procedure fillchar(var x;count : SizeInt;value : char);{$ifdef SYSTEMINLINE}inline;{$endif}
  121. begin
  122. fillchar(x,count,byte(value));
  123. end;
  124. { Include generic pascal only routines which are not defined in the processor
  125. specific include file }
  126. {$I generic.inc}
  127. {****************************************************************************
  128. Set Handling
  129. ****************************************************************************}
  130. { Include set support which is processor specific}
  131. {$i set.inc}
  132. { Include generic pascal routines for sets if the processor }
  133. { specific routines are not available. }
  134. {$i genset.inc}
  135. {****************************************************************************
  136. Math Routines
  137. ****************************************************************************}
  138. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  139. begin
  140. Hi := b shr 4
  141. end;
  142. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  143. begin
  144. Lo := b and $0f
  145. end;
  146. Function swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  147. Begin
  148. swap:=(X and $ff) shl 8 + (X shr 8)
  149. End;
  150. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}
  151. Begin
  152. swap:=(X and $ff) shl 8 + (X shr 8)
  153. End;
  154. Function swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}
  155. Begin
  156. Swap:=(X and $ffff) shl 16 + (X shr 16)
  157. End;
  158. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}
  159. Begin
  160. Swap:=(X and $ffff) shl 16 + (X shr 16)
  161. End;
  162. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}
  163. Begin
  164. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  165. End;
  166. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}
  167. Begin
  168. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  169. End;
  170. {$ifdef SUPPORT_DOUBLE}
  171. operator := (b:real48) d:double;
  172. begin
  173. D:=real2double(b);
  174. end;
  175. {$endif SUPPORT_DOUBLE}
  176. {$ifdef SUPPORT_EXTENDED}
  177. operator := (b:real48) e:extended;
  178. begin
  179. e:=real2double(b);
  180. end;
  181. {$endif SUPPORT_EXTENDED}
  182. {$ifdef FPC_USE_LIBC}
  183. { Include libc versions }
  184. {$i cgenmath.inc}
  185. {$endif FPC_USE_LIBC}
  186. { Include processor specific routines }
  187. {$I math.inc}
  188. { Include generic version }
  189. {$I genmath.inc}
  190. {****************************************************************************
  191. Subroutines for String handling
  192. ****************************************************************************}
  193. { Needs to be before RTTI handling }
  194. {$i sstrings.inc}
  195. { requires sstrings.inc for initval }
  196. {$I int64p.inc}
  197. {$I int64.inc}
  198. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  199. {$i astrings.inc}
  200. {$i wstrings.inc}
  201. {$i aliases.inc}
  202. {*****************************************************************************
  203. Dynamic Array support
  204. *****************************************************************************}
  205. {$i dynarr.inc}
  206. {*****************************************************************************
  207. Object Pascal support
  208. *****************************************************************************}
  209. {$i objpas.inc}
  210. {*****************************************************************************
  211. Variant support
  212. *****************************************************************************}
  213. {$i variant.inc}
  214. {****************************************************************************
  215. Run-Time Type Information (RTTI)
  216. ****************************************************************************}
  217. {$i rtti.inc}
  218. {----------------------------------------------------------------------
  219. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  220. Pseudo-Random Number Generator.
  221. What is Mersenne Twister?
  222. Mersenne Twister(MT) is a pseudorandom number generator developped by
  223. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  224. 1996-1997. MT has the following merits:
  225. It is designed with consideration on the flaws of various existing
  226. generators.
  227. Far longer period and far higher order of equidistribution than any
  228. other implemented generators. (It is proved that the period is 2^19937-1,
  229. and 623-dimensional equidistribution property is assured.)
  230. Fast generation. (Although it depends on the system, it is reported that
  231. MT is sometimes faster than the standard ANSI-C library in a system
  232. with pipeline and cache memory.)
  233. Efficient use of the memory. (The implemented C-code mt19937.c
  234. consumes only 624 words of working area.)
  235. home page
  236. http://www.math.keio.ac.jp/~matumoto/emt.html
  237. original c source
  238. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  239. Coded by Takuji Nishimura, considering the suggestions by
  240. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  241. This library is free software; you can redistribute it and/or
  242. modify it under the terms of the GNU Library General Public
  243. License as published by the Free Software Foundation; either
  244. version 2 of the License, or (at your option) any later
  245. version.
  246. This library is distributed in the hope that it will be useful,
  247. but WITHOUT ANY WARRANTY; without even the implied warranty of
  248. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  249. See the GNU Library General Public License for more details.
  250. You should have received a copy of the GNU Library General
  251. Public License along with this library; if not, write to the
  252. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  253. 02111-1307 USA
  254. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  255. When you use this, send an email to: [email protected]
  256. with an appropriate reference to your work.
  257. REFERENCE
  258. M. Matsumoto and T. Nishimura,
  259. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  260. Pseudo-Random Number Generator",
  261. ACM Transactions on Modeling and Computer Simulation,
  262. Vol. 8, No. 1, January 1998, pp 3--30.
  263. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  264. http://www.rksolution.cz/delphi/tips.htm
  265. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  266. 2003/10/26: adapted to use the improved intialisation mentioned at
  267. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  268. removed the assembler code
  269. ----------------------------------------------------------------------}
  270. {$R-} {range checking off}
  271. {$Q-} {overflow checking off}
  272. { Period parameter }
  273. Const
  274. MT19937N=624;
  275. Type
  276. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  277. { Period parameters }
  278. const
  279. MT19937M=397;
  280. MT19937MATRIX_A =$9908b0df; // constant vector a
  281. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  282. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  283. { Tempering parameters }
  284. TEMPERING_MASK_B=$9d2c5680;
  285. TEMPERING_MASK_C=$efc60000;
  286. VAR
  287. mt : tMT19937StateArray;
  288. const
  289. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  290. { Initializing the array with a seed }
  291. procedure sgenrand_MT19937(seed: longint);
  292. var
  293. i: longint;
  294. begin
  295. mt[0] := seed;
  296. for i := 1 to MT19937N-1 do
  297. begin
  298. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  299. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  300. { In the previous versions, MSBs of the seed affect }
  301. { only MSBs of the array mt[]. }
  302. { 2002/01/09 modified by Makoto Matsumoto }
  303. end;
  304. mti := MT19937N;
  305. end;
  306. function genrand_MT19937: longint;
  307. const
  308. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  309. var
  310. y: longint;
  311. kk: longint;
  312. begin
  313. if RandSeed<>OldRandSeed then
  314. mti:=MT19937N+1;
  315. if (mti >= MT19937N) { generate MT19937N longints at one time }
  316. then begin
  317. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  318. begin
  319. sgenrand_MT19937(randseed); // default initial seed is used
  320. { hack: randseed is not used more than once in this algorithm. Most }
  321. { user changes are re-initialising reandseed with the value it had }
  322. { at the start -> with the "not", we will detect this change. }
  323. { Detecting other changes is not useful, since the generated }
  324. { numbers will be different anyway. }
  325. randseed := not(randseed);
  326. oldrandseed := randseed;
  327. end;
  328. for kk:=0 to MT19937N-MT19937M-1 do begin
  329. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  330. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  331. end;
  332. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  333. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  334. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  335. end;
  336. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  337. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  338. mti := 0;
  339. end;
  340. y := mt[mti]; inc(mti);
  341. y := y xor (y shr 11);
  342. y := y xor (y shl 7) and TEMPERING_MASK_B;
  343. y := y xor (y shl 15) and TEMPERING_MASK_C;
  344. y := y xor (y shr 18);
  345. Result := y;
  346. end;
  347. function random(l:longint): longint;
  348. begin
  349. { otherwise we can return values = l (JM) }
  350. if (l < 0) then
  351. inc(l);
  352. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  353. end;
  354. function random(l:int64): int64;
  355. begin
  356. { always call random, so the random generator cycles (TP-compatible) (JM) }
  357. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff);
  358. if (l<>0) then
  359. random := random mod l
  360. else
  361. random := 0;
  362. end;
  363. function random: extended;
  364. begin
  365. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  366. end;
  367. {****************************************************************************
  368. Memory Management
  369. ****************************************************************************}
  370. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}
  371. Begin
  372. ptr:=farpointer((sel shl 4)+off);
  373. End;
  374. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  375. Begin
  376. Cseg:=0;
  377. End;
  378. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  379. Begin
  380. Dseg:=0;
  381. End;
  382. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  383. Begin
  384. Sseg:=0;
  385. End;
  386. {*****************************************************************************
  387. Directory support.
  388. *****************************************************************************}
  389. Procedure getdir(drivenr:byte;Var dir:ansistring);
  390. { this is needed to also allow ansistrings, the shortstring version is
  391. OS dependent }
  392. var
  393. s : shortstring;
  394. begin
  395. getdir(drivenr,s);
  396. dir:=s;
  397. end;
  398. {$ifopt R+}
  399. {$define RangeCheckWasOn}
  400. {$R-}
  401. {$endif opt R+}
  402. {$ifopt I+}
  403. {$define IOCheckWasOn}
  404. {$I-}
  405. {$endif opt I+}
  406. {$ifopt Q+}
  407. {$define OverflowCheckWasOn}
  408. {$Q-}
  409. {$endif opt Q+}
  410. {*****************************************************************************
  411. Miscellaneous
  412. *****************************************************************************}
  413. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; compilerproc;
  414. begin
  415. HandleErrorFrame(201,get_frame);
  416. end;
  417. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; compilerproc;
  418. begin
  419. HandleErrorFrame(200,get_frame);
  420. end;
  421. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; compilerproc;
  422. begin
  423. HandleErrorFrame(215,get_frame);
  424. end;
  425. procedure fpc_iocheck;[public,alias:'FPC_IOCHECK']; compilerproc;
  426. var
  427. l : longint;
  428. begin
  429. if InOutRes<>0 then
  430. begin
  431. l:=InOutRes;
  432. InOutRes:=0;
  433. HandleErrorFrame(l,get_frame);
  434. end;
  435. end;
  436. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  437. Begin
  438. IOResult:=InOutRes;
  439. InOutRes:=0;
  440. End;
  441. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  442. begin
  443. (* ThreadID is stored in a threadvar and made available in interface *)
  444. (* to allow setup of this value during thread initialization. *)
  445. GetThreadID := ThreadID;
  446. end;
  447. {*****************************************************************************
  448. Stack check code
  449. *****************************************************************************}
  450. {$IFNDEF NO_GENERIC_STACK_CHECK}
  451. {$IFOPT S+}
  452. {$DEFINE STACKCHECK}
  453. {$ENDIF}
  454. {$S-}
  455. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK'];
  456. var
  457. c : Pointer;
  458. begin
  459. { Avoid recursive calls when called from the exit routines }
  460. if StackError then
  461. exit;
  462. c := Sptr - (stack_size + STACK_MARGIN);
  463. if (c <= StackBottom) then
  464. begin
  465. StackError:=true;
  466. HandleError(202);
  467. end;
  468. end;
  469. {$IFDEF STACKCHECK}
  470. {$S+}
  471. {$ENDIF}
  472. {$UNDEF STACKCHECK}
  473. {$ENDIF NO_GENERIC_STACK_CHECK}
  474. {*****************************************************************************
  475. Initialization / Finalization
  476. *****************************************************************************}
  477. const
  478. maxunits=1024; { See also files.pas of the compiler source }
  479. type
  480. TInitFinalRec=record
  481. InitProc,
  482. FinalProc : TProcedure;
  483. end;
  484. TInitFinalTable=record
  485. TableCount,
  486. InitCount : longint;
  487. Procs : array[1..maxunits] of TInitFinalRec;
  488. end;
  489. var
  490. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  491. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  492. var
  493. i : longint;
  494. begin
  495. { call cpu/fpu initialisation routine }
  496. fpc_cpuinit;
  497. with InitFinalTable do
  498. begin
  499. for i:=1 to TableCount do
  500. begin
  501. if assigned(Procs[i].InitProc) then
  502. Procs[i].InitProc();
  503. InitCount:=i;
  504. end;
  505. end;
  506. if assigned(InitProc) then
  507. TProcedure(InitProc)();
  508. end;
  509. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  510. begin
  511. with InitFinalTable do
  512. begin
  513. while (InitCount>0) do
  514. begin
  515. // we've to decrement the cound before calling the final. code
  516. // else a halt in the final. code leads to a endless loop
  517. dec(InitCount);
  518. if assigned(Procs[InitCount+1].FinalProc) then
  519. Procs[InitCount+1].FinalProc();
  520. end;
  521. end;
  522. end;
  523. {*****************************************************************************
  524. Error / Exit / ExitProc
  525. *****************************************************************************}
  526. Procedure system_exit;forward;
  527. Procedure InternalExit;
  528. var
  529. current_exit : Procedure;
  530. Begin
  531. while exitProc<>nil Do
  532. Begin
  533. InOutRes:=0;
  534. current_exit:=tProcedure(exitProc);
  535. exitProc:=nil;
  536. current_exit();
  537. End;
  538. { Finalize units }
  539. FinalizeUnits;
  540. { Show runtime error and exit }
  541. If erroraddr<>nil Then
  542. Begin
  543. Writeln(stdout,'Runtime error ',Errorcode,' at $',hexstr(PtrInt(Erroraddr),sizeof(PtrInt)*2));
  544. { to get a nice symify }
  545. Writeln(stdout,BackTraceStrFunc(Erroraddr));
  546. dump_stack(stdout,ErrorBase);
  547. Writeln(stdout,'');
  548. End;
  549. End;
  550. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  551. begin
  552. InternalExit;
  553. System_exit;
  554. end;
  555. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  556. begin
  557. InternalExit;
  558. end;
  559. Procedure Halt(ErrNum: Byte);
  560. Begin
  561. ExitCode:=Errnum;
  562. Do_Exit;
  563. end;
  564. function SysBackTraceStr (Addr: Pointer): ShortString;
  565. begin
  566. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  567. end;
  568. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  569. begin
  570. If pointer(ErrorProc)<>Nil then
  571. ErrorProc(Errno,addr,frame);
  572. errorcode:=word(Errno);
  573. erroraddr:=addr;
  574. errorbase:=frame;
  575. if ExceptAddrStack <> nil then
  576. raise TObject(nil) at addr,frame;
  577. if errorcode <= maxExitCode then
  578. halt(errorcode)
  579. else
  580. halt(255)
  581. end;
  582. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  583. {
  584. Procedure to handle internal errors, i.e. not user-invoked errors
  585. Internal function should ALWAYS call HandleError instead of RunError.
  586. Can be used for exception handlers to specify the frame
  587. }
  588. begin
  589. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  590. end;
  591. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  592. {
  593. Procedure to handle internal errors, i.e. not user-invoked errors
  594. Internal function should ALWAYS call HandleError instead of RunError.
  595. }
  596. begin
  597. HandleErrorFrame(Errno,get_frame);
  598. end;
  599. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  600. begin
  601. errorcode:=w;
  602. erroraddr:=get_caller_addr(get_frame);
  603. errorbase:=get_caller_frame(get_frame);
  604. if errorcode <= maxExitCode then
  605. halt(errorcode)
  606. else
  607. halt(255)
  608. end;
  609. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  610. Begin
  611. RunError (0);
  612. End;
  613. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  614. Begin
  615. Halt(0);
  616. End;
  617. function do_isdevice(handle:thandle):boolean;forward;
  618. Procedure dump_stack(var f : text;bp : Pointer);
  619. var
  620. i : Longint;
  621. prevbp : Pointer;
  622. is_dev : boolean;
  623. caller_frame,
  624. caller_addr : Pointer;
  625. Begin
  626. try
  627. prevbp:=bp-1;
  628. i:=0;
  629. is_dev:=do_isdevice(textrec(f).Handle);
  630. while bp > prevbp Do
  631. Begin
  632. caller_addr := get_caller_addr(bp);
  633. caller_frame := get_caller_frame(bp);
  634. if (caller_addr=nil) or
  635. (caller_frame=nil) then
  636. break;
  637. Writeln(f,BackTraceStrFunc(caller_addr));
  638. Inc(i);
  639. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  640. break;
  641. prevbp:=bp;
  642. bp:=caller_frame;
  643. End;
  644. except
  645. { prevent endless dump if an exception occured }
  646. end;
  647. End;
  648. Type
  649. PExitProcInfo = ^TExitProcInfo;
  650. TExitProcInfo = Record
  651. Next : PExitProcInfo;
  652. SaveExit : Pointer;
  653. Proc : TProcedure;
  654. End;
  655. const
  656. ExitProcList: PExitProcInfo = nil;
  657. Procedure DoExitProc;
  658. var
  659. P : PExitProcInfo;
  660. Proc : TProcedure;
  661. Begin
  662. P:=ExitProcList;
  663. ExitProcList:=P^.Next;
  664. ExitProc:=P^.SaveExit;
  665. Proc:=P^.Proc;
  666. DisPose(P);
  667. Proc();
  668. End;
  669. Procedure AddExitProc(Proc: TProcedure);
  670. var
  671. P : PExitProcInfo;
  672. Begin
  673. New(P);
  674. P^.Next:=ExitProcList;
  675. P^.SaveExit:=ExitProc;
  676. P^.Proc:=Proc;
  677. ExitProcList:=P;
  678. ExitProc:=@DoExitProc;
  679. End;
  680. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  681. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  682. // Note: for internal use by skilled programmers only
  683. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  684. var p : ppchar;
  685. i : LongInt;
  686. begin
  687. if High(s)<Low(s) Then Exit(NIL);
  688. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  689. // for cmd
  690. if p=nil then
  691. begin
  692. {$ifdef xunix}
  693. fpseterrno(ESysEnomem);
  694. {$endif}
  695. exit(NIL);
  696. end;
  697. for i:=low(s) to high(s) do
  698. p[i+Reserveentries]:=pchar(s[i]);
  699. p[high(s)+1+Reserveentries]:=nil;
  700. ArrayStringToPPchar:=p;
  701. end;
  702. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  703. {
  704. Create a PPChar to structure of pchars which are the arguments specified
  705. in the string S. Especially usefull for creating an ArgV for Exec-calls
  706. }
  707. begin
  708. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  709. end;
  710. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  711. var
  712. i,nr : longint;
  713. Buf : ^char;
  714. p : ppchar;
  715. begin
  716. buf:=s;
  717. nr:=1;
  718. while (buf^<>#0) do // count nr of args
  719. begin
  720. while (buf^ in [' ',#9,#10]) do // Kill separators.
  721. inc(buf);
  722. inc(nr);
  723. if buf^='"' Then // quotes argument?
  724. begin
  725. inc(buf);
  726. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  727. inc(buf);
  728. if buf^='"' then // skip closing quote.
  729. inc(buf);
  730. end
  731. else
  732. begin // else std
  733. while not (buf^ in [' ',#0,#9,#10]) do
  734. inc(buf);
  735. end;
  736. end;
  737. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  738. StringToPPChar:=p;
  739. if p=nil then
  740. begin
  741. {$ifdef xunix}
  742. fpseterrno(ESysEnomem);
  743. {$endif}
  744. exit;
  745. end;
  746. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  747. buf:=s;
  748. while (buf^<>#0) do
  749. begin
  750. while (buf^ in [' ',#9,#10]) do // Kill separators.
  751. begin
  752. buf^:=#0;
  753. inc(buf);
  754. end;
  755. if buf^='"' Then // quotes argument?
  756. begin
  757. inc(buf);
  758. p^:=buf;
  759. inc(p);
  760. p^:=nil;
  761. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  762. inc(buf);
  763. if buf^='"' then // skip closing quote.
  764. begin
  765. buf^:=#0;
  766. inc(buf);
  767. end;
  768. end
  769. else
  770. begin
  771. p^:=buf;
  772. inc(p);
  773. p^:=nil;
  774. while not (buf^ in [' ',#0,#9,#10]) do
  775. inc(buf);
  776. end;
  777. end;
  778. end;
  779. {*****************************************************************************
  780. Abstract/Assert support.
  781. *****************************************************************************}
  782. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  783. begin
  784. If pointer(AbstractErrorProc)<>nil then
  785. AbstractErrorProc();
  786. HandleErrorFrame(211,get_frame);
  787. end;
  788. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  789. begin
  790. if pointer(AssertErrorProc)<>nil then
  791. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  792. else
  793. HandleErrorFrame(227,get_frame);
  794. end;
  795. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  796. begin
  797. If msg='' then
  798. write(stderr,'Assertion failed')
  799. else
  800. write(stderr,msg);
  801. Writeln(stderr,' (',FName,', line ',LineNo,').');
  802. Writeln(stderr,'');
  803. Halt(227);
  804. end;
  805. {*****************************************************************************
  806. SetJmp/LongJmp support.
  807. *****************************************************************************}
  808. {$i setjump.inc}
  809. {$ifdef IOCheckWasOn}
  810. {$I+}
  811. {$endif}
  812. {$ifdef RangeCheckWasOn}
  813. {$R+}
  814. {$endif}
  815. {$ifdef OverflowCheckWasOn}
  816. {$Q+}
  817. {$endif}
  818. {*****************************************************************************
  819. OS dependent Helpers/Syscalls
  820. *****************************************************************************}
  821. {$i sysos.inc}
  822. {*****************************************************************************
  823. Heap
  824. *****************************************************************************}
  825. {$i sysheap.inc}
  826. {$i heap.inc}
  827. {*****************************************************************************
  828. Thread support
  829. *****************************************************************************}
  830. { Generic threadmanager }
  831. {$i thread.inc}
  832. { Generic threadvar support }
  833. {$i threadvr.inc}
  834. { OS Dependent implementation }
  835. {$i systhrd.inc}
  836. {*****************************************************************************
  837. File Handling
  838. *****************************************************************************}
  839. { OS dependent low level file functions }
  840. {$i sysfile.inc}
  841. { Text file }
  842. {$i text.inc}
  843. { Untyped file }
  844. {$i file.inc}
  845. { Typed file }
  846. {$i typefile.inc}
  847. {*****************************************************************************
  848. Directory Handling
  849. *****************************************************************************}
  850. { OS dependent dir functions }
  851. {$i sysdir.inc}
  852. {*****************************************************************************
  853. Resources support
  854. *****************************************************************************}
  855. {$ifndef HAS_RESOURCES}
  856. {$i sysres.inc}
  857. {$endif}
  858. Function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: AnsiString): TResourceHandle;
  859. begin
  860. Result:=FindResource(ModuleHandle,PChar(ResourceName),PChar(ResourceType));
  861. end;