system.inc 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. {
  2. $Id$
  3. This file is part of the Free Pascal Run time library.
  4. Copyright (c) 1999-2000 by 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. {****************************************************************************
  12. Local types
  13. ****************************************************************************}
  14. {
  15. TextRec and FileRec are put in a separate file to make it available to other
  16. units without putting it explicitly in systemh.
  17. This way we keep TP compatibility, and the TextRec definition is available
  18. for everyone who needs it.
  19. }
  20. {$i filerec.inc}
  21. {$i textrec.inc}
  22. Procedure HandleError (Errno : Longint); forward;
  23. Procedure HandleErrorFrame (Errno : longint;frame : Pointer); forward;
  24. type
  25. FileFunc = Procedure(var t : TextRec);
  26. const
  27. STACK_MARGIN = 16384; { Stack size margin for stack checking }
  28. { Random / Randomize constants }
  29. OldRandSeed : Cardinal = 0;
  30. { For Error Handling.}
  31. ErrorBase : Pointer = nil;
  32. { Used by the ansistrings and maybe also other things in the future }
  33. var
  34. emptychar : char;public name 'FPC_EMPTYCHAR';
  35. initialstklen : longint;external name '__stklen';
  36. {****************************************************************************
  37. Routines which have compiler magic
  38. ****************************************************************************}
  39. {$ifndef INTERNCONSTINTF}
  40. Function lo(i : Integer) : byte; [INTERNPROC: fpc_in_lo_Word];
  41. Function lo(w : Word) : byte; [INTERNPROC: fpc_in_lo_Word];
  42. Function lo(l : Longint) : Word; [INTERNPROC: fpc_in_lo_long];
  43. Function lo(l : DWord) : Word; [INTERNPROC: fpc_in_lo_long];
  44. Function hi(i : Integer) : byte; [INTERNPROC: fpc_in_hi_Word];
  45. Function hi(w : Word) : byte; [INTERNPROC: fpc_in_hi_Word];
  46. Function hi(l : Longint) : Word; [INTERNPROC: fpc_in_hi_long];
  47. Function hi(l : DWord) : Word; [INTERNPROC: fpc_in_hi_long];
  48. Function lo(q : QWord) : DWord; [INTERNPROC: fpc_in_lo_qword];
  49. Function lo(i : Int64) : DWord; [INTERNPROC: fpc_in_lo_qword];
  50. Function hi(q : QWord) : DWord; [INTERNPROC: fpc_in_hi_qword];
  51. Function hi(i : Int64) : DWord; [INTERNPROC: fpc_in_hi_qword];
  52. Function chr(b : byte) : Char; [INTERNPROC: fpc_in_chr_byte];
  53. {$ifndef INTERNLENGTH}
  54. Function Length(s : string) : byte; [INTERNPROC: fpc_in_Length_string];
  55. Function Length(c : char) : byte; [INTERNPROC: fpc_in_Length_string];
  56. {$endif INTERNLENGTH}
  57. Procedure Reset(var f : TypedFile); [INTERNPROC: fpc_in_Reset_TypedFile];
  58. Procedure Rewrite(var f : TypedFile); [INTERNPROC: fpc_in_Rewrite_TypedFile];
  59. {$endif INTERNCONSTINTF}
  60. {****************************************************************************
  61. Include processor specific routines
  62. ****************************************************************************}
  63. {$ifdef FPC_USE_LIBC}
  64. { prefer libc implementations over our own, as they're most likely faster }
  65. {$i cgeneric.inc}
  66. { is now declared as external reference to another routine in the interface }
  67. {$i cgenstr.inc}
  68. {$endif FPC_USE_LIBC}
  69. {$ifdef cpui386}
  70. {$ifdef SYSPROCDEFINED}
  71. {$Error Can't determine processor type !}
  72. {$endif}
  73. {$i i386.inc} { Case dependent, don't change }
  74. {$endif cpui386}
  75. {$ifdef cpum68k}
  76. {$ifdef SYSPROCDEFINED}
  77. {$Error Can't determine processor type !}
  78. {$endif}
  79. {$i m68k.inc} { Case dependent, don't change }
  80. {$define SYSPROCDEFINED}
  81. {$endif cpum68k}
  82. {$ifdef cpux86_64}
  83. {$ifdef SYSPROCDEFINED}
  84. {$Error Can't determine processor type !}
  85. {$endif}
  86. {$i x86_64.inc} { Case dependent, don't change }
  87. {$define SYSPROCDEFINED}
  88. {$endif cpux86_64}
  89. {$ifdef cpupowerpc}
  90. {$ifdef SYSPROCDEFINED}
  91. {$Error Can't determine processor type !}
  92. {$endif}
  93. {$i powerpc.inc} { Case dependent, don't change }
  94. {$define SYSPROCDEFINED}
  95. {$endif cpupowerpc}
  96. {$ifdef cpualpha}
  97. {$ifdef SYSPROCDEFINED}
  98. {$Error Can't determine processor type !}
  99. {$endif}
  100. {$i alpha.inc} { Case dependent, don't change }
  101. {$define SYSPROCDEFINED}
  102. {$endif cpualpha}
  103. {$ifdef cpuiA64}
  104. {$ifdef SYSPROCDEFINED}
  105. {$Error Can't determine processor type !}
  106. {$endif}
  107. {$i ia64.inc} { Case dependent, don't change }
  108. {$define SYSPROCDEFINED}
  109. {$endif cpuiA64}
  110. {$ifdef cpusparc}
  111. {$ifdef SYSPROCDEFINED}
  112. {$Error Can't determine processor type !}
  113. {$endif}
  114. {$i sparc.inc} { Case dependent, don't change }
  115. {$define SYSPROCDEFINED}
  116. {$endif cpusparc}
  117. {$ifdef cpuarm}
  118. {$ifdef SYSPROCDEFINED}
  119. {$Error Can't determine processor type !}
  120. {$endif}
  121. {$i arm.inc} { Case dependent, don't change }
  122. {$define SYSPROCDEFINED}
  123. {$endif cpuarm}
  124. procedure fillchar(var x;count : SizeInt;value : boolean);{$ifdef SYSTEMINLINE}inline;{$endif}
  125. begin
  126. fillchar(x,count,byte(value));
  127. end;
  128. procedure fillchar(var x;count : SizeInt;value : char);{$ifdef SYSTEMINLINE}inline;{$endif}
  129. begin
  130. fillchar(x,count,byte(value));
  131. end;
  132. { Include generic pascal only routines which are not defined in the processor
  133. specific include file }
  134. {$I generic.inc}
  135. {****************************************************************************
  136. Set Handling
  137. ****************************************************************************}
  138. { Include set support which is processor specific}
  139. {$i set.inc}
  140. { Include generic pascal routines for sets if the processor }
  141. { specific routines are not available. }
  142. {$i genset.inc}
  143. {****************************************************************************
  144. Math Routines
  145. ****************************************************************************}
  146. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  147. begin
  148. Hi := b shr 4
  149. end;
  150. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  151. begin
  152. Lo := b and $0f
  153. end;
  154. Function swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  155. Begin
  156. swap:=(X and $ff) shl 8 + (X shr 8)
  157. End;
  158. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  159. Begin
  160. swap:=(X and $ff) shl 8 + (X shr 8)
  161. End;
  162. Function swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  163. Begin
  164. Swap:=(X and $ffff) shl 16 + (X shr 16)
  165. End;
  166. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  167. Begin
  168. Swap:=(X and $ffff) shl 16 + (X shr 16)
  169. End;
  170. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  171. Begin
  172. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  173. End;
  174. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  175. Begin
  176. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  177. End;
  178. {$ifdef SUPPORT_DOUBLE}
  179. operator := (b:real48) d:double;
  180. begin
  181. D:=real2double(b);
  182. end;
  183. {$endif SUPPORT_DOUBLE}
  184. {$ifdef SUPPORT_EXTENDED}
  185. operator := (b:real48) e:extended;
  186. begin
  187. e:=real2double(b);
  188. end;
  189. {$endif SUPPORT_EXTENDED}
  190. {$ifdef FPC_USE_LIBC}
  191. { Include libc versions }
  192. {$i cgenmath.inc}
  193. {$endif FPC_USE_LIBC}
  194. { Include processor specific routines }
  195. {$I math.inc}
  196. { Include generic version }
  197. {$I genmath.inc}
  198. operator ** (bas,expo : real) e: real;
  199. begin
  200. e:=power(bas,expo);
  201. end;
  202. operator ** (bas,expo : int64) i: int64;
  203. begin
  204. i:=power(bas,expo);
  205. end;
  206. {****************************************************************************
  207. Subroutines for String handling
  208. ****************************************************************************}
  209. { Needs to be before RTTI handling }
  210. {$i sstrings.inc}
  211. { requires sstrings.inc for initval }
  212. {$I int64p.inc}
  213. {$I int64.inc}
  214. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  215. {$i astrings.inc}
  216. {$ifdef HASWIDESTRING}
  217. {$i wstrings.inc}
  218. {$endif HASWIDESTRING}
  219. {$i aliases.inc}
  220. {*****************************************************************************
  221. Dynamic Array support
  222. *****************************************************************************}
  223. {$i dynarr.inc}
  224. {*****************************************************************************
  225. Object Pascal support
  226. *****************************************************************************}
  227. {$i objpas.inc}
  228. {*****************************************************************************
  229. Variant support
  230. *****************************************************************************}
  231. {$ifdef HASVARIANT}
  232. {$i variant.inc}
  233. {$endif HASVARIANT}
  234. {****************************************************************************
  235. Run-Time Type Information (RTTI)
  236. ****************************************************************************}
  237. {$i rtti.inc}
  238. {----------------------------------------------------------------------
  239. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  240. Pseudo-Random Number Generator.
  241. What is Mersenne Twister?
  242. Mersenne Twister(MT) is a pseudorandom number generator developped by
  243. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  244. 1996-1997. MT has the following merits:
  245. It is designed with consideration on the flaws of various existing
  246. generators.
  247. Far longer period and far higher order of equidistribution than any
  248. other implemented generators. (It is proved that the period is 2^19937-1,
  249. and 623-dimensional equidistribution property is assured.)
  250. Fast generation. (Although it depends on the system, it is reported that
  251. MT is sometimes faster than the standard ANSI-C library in a system
  252. with pipeline and cache memory.)
  253. Efficient use of the memory. (The implemented C-code mt19937.c
  254. consumes only 624 words of working area.)
  255. home page
  256. http://www.math.keio.ac.jp/~matumoto/emt.html
  257. original c source
  258. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  259. Coded by Takuji Nishimura, considering the suggestions by
  260. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  261. This library is free software; you can redistribute it and/or
  262. modify it under the terms of the GNU Library General Public
  263. License as published by the Free Software Foundation; either
  264. version 2 of the License, or (at your option) any later
  265. version.
  266. This library is distributed in the hope that it will be useful,
  267. but WITHOUT ANY WARRANTY; without even the implied warranty of
  268. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  269. See the GNU Library General Public License for more details.
  270. You should have received a copy of the GNU Library General
  271. Public License along with this library; if not, write to the
  272. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  273. 02111-1307 USA
  274. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  275. When you use this, send an email to: [email protected]
  276. with an appropriate reference to your work.
  277. REFERENCE
  278. M. Matsumoto and T. Nishimura,
  279. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  280. Pseudo-Random Number Generator",
  281. ACM Transactions on Modeling and Computer Simulation,
  282. Vol. 8, No. 1, January 1998, pp 3--30.
  283. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  284. http://www.rksolution.cz/delphi/tips.htm
  285. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  286. 2003/10/26: adapted to use the improved intialisation mentioned at
  287. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  288. removed the assembler code
  289. ----------------------------------------------------------------------}
  290. {$R-} {range checking off}
  291. {$Q-} {overflow checking off}
  292. { Period parameter }
  293. Const
  294. MT19937N=624;
  295. Type
  296. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  297. { Period parameters }
  298. const
  299. MT19937M=397;
  300. MT19937MATRIX_A =$9908b0df; // constant vector a
  301. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  302. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  303. { Tempering parameters }
  304. TEMPERING_MASK_B=$9d2c5680;
  305. TEMPERING_MASK_C=$efc60000;
  306. VAR
  307. mt : tMT19937StateArray;
  308. const
  309. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  310. { Initializing the array with a seed }
  311. procedure sgenrand_MT19937(seed: longint);
  312. var
  313. i: longint;
  314. begin
  315. mt[0] := seed;
  316. for i := 1 to MT19937N-1 do
  317. begin
  318. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  319. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  320. { In the previous versions, MSBs of the seed affect }
  321. { only MSBs of the array mt[]. }
  322. { 2002/01/09 modified by Makoto Matsumoto }
  323. end;
  324. mti := MT19937N;
  325. end;
  326. function genrand_MT19937: longint;
  327. const
  328. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  329. var
  330. y: longint;
  331. kk: longint;
  332. begin
  333. if (mti >= MT19937N) or
  334. (randseed <> oldrandseed) { generate MT19937N longints at one time }
  335. then begin
  336. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  337. begin
  338. sgenrand_MT19937(randseed); // default initial seed is used
  339. { hack: randseed is not used more than once in this algorithm. Most }
  340. { user changes are re-initialising reandseed with the value it had }
  341. { at the start -> with the "not", we will detect this change. }
  342. { Detecting other changes is not useful, since the generated }
  343. { numbers will be different anyway. }
  344. randseed := not(randseed);
  345. oldrandseed := randseed;
  346. end;
  347. for kk:=0 to MT19937N-MT19937M-1 do begin
  348. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  349. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  350. end;
  351. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  352. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  353. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  354. end;
  355. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  356. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  357. mti := 0;
  358. end;
  359. y := mt[mti]; inc(mti);
  360. y := y xor (y shr 11);
  361. y := y xor (y shl 7) and TEMPERING_MASK_B;
  362. y := y xor (y shl 15) and TEMPERING_MASK_C;
  363. y := y xor (y shr 18);
  364. Result := y;
  365. end;
  366. function random(l:longint): longint;
  367. begin
  368. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  369. end;
  370. function random(l:int64): int64;
  371. begin
  372. {$ifndef VER1_0}
  373. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff) mod l;
  374. {$endif VER1_0}
  375. end;
  376. function random: extended;
  377. begin
  378. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  379. end;
  380. {****************************************************************************
  381. Memory Management
  382. ****************************************************************************}
  383. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_ptr];{$endif}
  384. Begin
  385. ptr:=farpointer((sel shl 4)+off);
  386. End;
  387. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  388. Begin
  389. Cseg:=0;
  390. End;
  391. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  392. Begin
  393. Dseg:=0;
  394. End;
  395. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  396. Begin
  397. Sseg:=0;
  398. End;
  399. {*****************************************************************************
  400. Directory support.
  401. *****************************************************************************}
  402. Procedure getdir(drivenr:byte;Var dir:ansistring);
  403. { this is needed to also allow ansistrings, the shortstring version is
  404. OS dependent }
  405. var
  406. s : shortstring;
  407. begin
  408. getdir(drivenr,s);
  409. dir:=s;
  410. end;
  411. {$ifopt R+}
  412. {$define RangeCheckWasOn}
  413. {$R-}
  414. {$endif opt R+}
  415. {$ifopt I+}
  416. {$define IOCheckWasOn}
  417. {$I-}
  418. {$endif opt I+}
  419. {$ifopt Q+}
  420. {$define OverflowCheckWasOn}
  421. {$Q-}
  422. {$endif opt Q+}
  423. {*****************************************************************************
  424. Miscellaneous
  425. *****************************************************************************}
  426. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; {$ifdef hascompilerproc} compilerproc; {$endif}
  427. begin
  428. HandleErrorFrame(201,get_frame);
  429. end;
  430. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; {$ifdef hascompilerproc} compilerproc; {$endif}
  431. begin
  432. HandleErrorFrame(200,get_frame);
  433. end;
  434. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; {$ifdef hascompilerproc} compilerproc; {$endif}
  435. begin
  436. HandleErrorFrame(215,get_frame);
  437. end;
  438. procedure fpc_iocheck;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_IOCHECK']; {$ifdef hascompilerproc} compilerproc; {$endif}
  439. var
  440. l : longint;
  441. begin
  442. if InOutRes<>0 then
  443. begin
  444. l:=InOutRes;
  445. InOutRes:=0;
  446. HandleErrorFrame(l,get_frame);
  447. end;
  448. end;
  449. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  450. Begin
  451. IOResult:=InOutRes;
  452. InOutRes:=0;
  453. End;
  454. {*****************************************************************************
  455. Stack check code
  456. *****************************************************************************}
  457. {$IFNDEF NO_GENERIC_STACK_CHECK}
  458. {$IFOPT S+}
  459. {$DEFINE STACKCHECK}
  460. {$ENDIF}
  461. {$S-}
  462. procedure fpc_stackcheck(stack_size:Cardinal);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_STACKCHECK'];
  463. var
  464. c : Pointer;
  465. begin
  466. { Avoid recursive calls when called from the exit routines }
  467. if StackError then
  468. exit;
  469. c := Sptr - (stack_size + STACK_MARGIN);
  470. if (c <= StackBottom) then
  471. begin
  472. StackError:=true;
  473. HandleError(202);
  474. end;
  475. end;
  476. {$IFDEF STACKCHECK}
  477. {$S+}
  478. {$ENDIF}
  479. {$UNDEF STACKCHECK}
  480. {$ENDIF NO_GENERIC_STACK_CHECK}
  481. {*****************************************************************************
  482. Initialization / Finalization
  483. *****************************************************************************}
  484. const
  485. maxunits=1024; { See also files.pas of the compiler source }
  486. type
  487. TInitFinalRec=record
  488. InitProc,
  489. FinalProc : TProcedure;
  490. end;
  491. TInitFinalTable=record
  492. TableCount,
  493. InitCount : longint;
  494. Procs : array[1..maxunits] of TInitFinalRec;
  495. end;
  496. var
  497. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  498. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; {$ifdef hascompilerproc} compilerproc; {$endif}
  499. var
  500. i : longint;
  501. begin
  502. { call cpu/fpu initialisation routine }
  503. fpc_cpuinit;
  504. with InitFinalTable do
  505. begin
  506. for i:=1 to TableCount do
  507. begin
  508. if assigned(Procs[i].InitProc) then
  509. Procs[i].InitProc();
  510. InitCount:=i;
  511. end;
  512. end;
  513. end;
  514. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  515. begin
  516. with InitFinalTable do
  517. begin
  518. while (InitCount>0) do
  519. begin
  520. // we've to decrement the cound before calling the final. code
  521. // else a halt in the final. code leads to a endless loop
  522. dec(InitCount);
  523. if assigned(Procs[InitCount+1].FinalProc) then
  524. Procs[InitCount+1].FinalProc();
  525. end;
  526. end;
  527. end;
  528. {*****************************************************************************
  529. Error / Exit / ExitProc
  530. *****************************************************************************}
  531. Procedure system_exit;forward;
  532. Procedure InternalExit;
  533. var
  534. current_exit : Procedure;
  535. Begin
  536. while exitProc<>nil Do
  537. Begin
  538. InOutRes:=0;
  539. current_exit:=tProcedure(exitProc);
  540. exitProc:=nil;
  541. current_exit();
  542. End;
  543. { Finalize units }
  544. FinalizeUnits;
  545. { Show runtime error and exit }
  546. If erroraddr<>nil Then
  547. Begin
  548. Writeln(stdout,'Runtime error ',Errorcode,' at $',hexstr(PtrInt(Erroraddr),sizeof(PtrInt)*2));
  549. { to get a nice symify }
  550. Writeln(stdout,BackTraceStrFunc(Erroraddr));
  551. dump_stack(stdout,ErrorBase);
  552. Writeln(stdout,'');
  553. End;
  554. End;
  555. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  556. begin
  557. InternalExit;
  558. System_exit;
  559. end;
  560. Procedure lib_exit;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[Public,Alias:'FPC_LIB_EXIT'];
  561. begin
  562. InternalExit;
  563. end;
  564. Procedure Halt(ErrNum: Byte);
  565. Begin
  566. ExitCode:=Errnum;
  567. Do_Exit;
  568. end;
  569. function SysBackTraceStr (Addr: Pointer): ShortString;
  570. begin
  571. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  572. end;
  573. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  574. begin
  575. If pointer(ErrorProc)<>Nil then
  576. ErrorProc(Errno,addr,frame);
  577. errorcode:=word(Errno);
  578. erroraddr:=addr;
  579. errorbase:=frame;
  580. if errorcode <= maxExitCode then
  581. halt(errorcode)
  582. else
  583. halt(255)
  584. end;
  585. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  586. {
  587. Procedure to handle internal errors, i.e. not user-invoked errors
  588. Internal function should ALWAYS call HandleError instead of RunError.
  589. Can be used for exception handlers to specify the frame
  590. }
  591. begin
  592. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  593. end;
  594. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  595. {
  596. Procedure to handle internal errors, i.e. not user-invoked errors
  597. Internal function should ALWAYS call HandleError instead of RunError.
  598. }
  599. begin
  600. HandleErrorFrame(Errno,get_frame);
  601. end;
  602. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  603. begin
  604. errorcode:=w;
  605. erroraddr:=get_caller_addr(get_frame);
  606. errorbase:=get_caller_frame(get_frame);
  607. if errorcode <= maxExitCode then
  608. halt(errorcode)
  609. else
  610. halt(255)
  611. end;
  612. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  613. Begin
  614. RunError (0);
  615. End;
  616. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  617. Begin
  618. Halt(0);
  619. End;
  620. function do_isdevice(handle:thandle):boolean;forward;
  621. Procedure dump_stack(var f : text;bp : Pointer);
  622. var
  623. i : Longint;
  624. prevbp : Pointer;
  625. is_dev : boolean;
  626. caller_frame,
  627. caller_addr : Pointer;
  628. Begin
  629. prevbp:=bp-1;
  630. i:=0;
  631. is_dev:=do_isdevice(textrec(f).Handle);
  632. while bp > prevbp Do
  633. Begin
  634. caller_addr := get_caller_addr(bp);
  635. caller_frame := get_caller_frame(bp);
  636. if (caller_addr=nil) or
  637. (caller_frame=nil) then
  638. break;
  639. Writeln(f,BackTraceStrFunc(caller_addr));
  640. Inc(i);
  641. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  642. break;
  643. prevbp:=bp;
  644. bp:=caller_frame;
  645. End;
  646. End;
  647. Type
  648. PExitProcInfo = ^TExitProcInfo;
  649. TExitProcInfo = Record
  650. Next : PExitProcInfo;
  651. SaveExit : Pointer;
  652. Proc : TProcedure;
  653. End;
  654. const
  655. ExitProcList: PExitProcInfo = nil;
  656. Procedure DoExitProc;
  657. var
  658. P : PExitProcInfo;
  659. Proc : TProcedure;
  660. Begin
  661. P:=ExitProcList;
  662. ExitProcList:=P^.Next;
  663. ExitProc:=P^.SaveExit;
  664. Proc:=P^.Proc;
  665. DisPose(P);
  666. Proc();
  667. End;
  668. Procedure AddExitProc(Proc: TProcedure);
  669. var
  670. P : PExitProcInfo;
  671. Begin
  672. New(P);
  673. P^.Next:=ExitProcList;
  674. P^.SaveExit:=ExitProc;
  675. P^.Proc:=Proc;
  676. ExitProcList:=P;
  677. ExitProc:=@DoExitProc;
  678. End;
  679. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  680. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  681. // Note: for internal use by skilled programmers only
  682. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  683. var p : ppchar;
  684. Res,
  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. InQuote : Boolean;
  716. begin
  717. buf:=s;
  718. nr:=1;
  719. InQuote:=false;
  720. while (buf^<>#0) do // count nr of args
  721. begin
  722. while (buf^ in [' ',#9,#10]) do // Kill separators.
  723. inc(buf);
  724. inc(nr);
  725. if buf^='"' Then // quotes argument?
  726. begin
  727. inc(buf);
  728. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  729. inc(buf);
  730. if buf^='"' then // skip closing quote.
  731. inc(buf);
  732. end
  733. else
  734. begin // else std
  735. while not (buf^ in [' ',#0,#9,#10]) do
  736. inc(buf);
  737. end;
  738. end;
  739. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  740. StringToPPChar:=p;
  741. if p=nil then
  742. begin
  743. {$ifdef xunix}
  744. fpseterrno(ESysEnomem);
  745. {$endif}
  746. exit;
  747. end;
  748. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  749. buf:=s;
  750. while (buf^<>#0) do
  751. begin
  752. while (buf^ in [' ',#9,#10]) do // Kill separators.
  753. begin
  754. buf^:=#0;
  755. inc(buf);
  756. end;
  757. if buf^='"' Then // quotes argument?
  758. begin
  759. inc(buf);
  760. p^:=buf;
  761. inc(p);
  762. p^:=nil;
  763. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  764. inc(buf);
  765. if buf^='"' then // skip closing quote.
  766. begin
  767. buf^:=#0;
  768. inc(buf);
  769. end;
  770. end
  771. else
  772. begin
  773. p^:=buf;
  774. inc(p);
  775. p^:=nil;
  776. while not (buf^ in [' ',#0,#9,#10]) do
  777. inc(buf);
  778. end;
  779. end;
  780. end;
  781. {*****************************************************************************
  782. Abstract/Assert support.
  783. *****************************************************************************}
  784. procedure fpc_AbstractErrorIntern;{$ifdef hascompilerproc}compilerproc;{$endif}[public,alias : 'FPC_ABSTRACTERROR'];
  785. begin
  786. If pointer(AbstractErrorProc)<>nil then
  787. AbstractErrorProc();
  788. HandleErrorFrame(211,get_frame);
  789. end;
  790. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif} [Public,Alias : 'FPC_ASSERT']; {$ifdef hascompilerproc} compilerproc; {$endif}
  791. begin
  792. if pointer(AssertErrorProc)<>nil then
  793. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  794. else
  795. HandleErrorFrame(227,get_frame);
  796. end;
  797. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  798. begin
  799. If msg='' then
  800. write(stderr,'Assertion failed')
  801. else
  802. write(stderr,msg);
  803. Writeln(stderr,' (',FName,', line ',LineNo,').');
  804. Writeln(stderr,'');
  805. Halt(227);
  806. end;
  807. {*****************************************************************************
  808. SetJmp/LongJmp support.
  809. *****************************************************************************}
  810. {$i setjump.inc}
  811. {$ifdef IOCheckWasOn}
  812. {$I+}
  813. {$endif}
  814. {$ifdef RangeCheckWasOn}
  815. {$R+}
  816. {$endif}
  817. {$ifdef OverflowCheckWasOn}
  818. {$Q+}
  819. {$endif}
  820. {
  821. $Log$
  822. Revision 1.70 2004-11-21 16:14:59 jonas
  823. * fixed remaining compilation problems
  824. Revision 1.69 2004/11/20 15:49:21 jonas
  825. * some compilation fixes for powerpc after all the internconst and
  826. internproc changes, still crashes with internalerror(88) for ppc1
  827. on real2str.inc(193,39)
  828. Revision 1.68 2004/11/17 22:19:04 peter
  829. internconst, internproc and some external declarations moved to interface
  830. Revision 1.67 2004/10/30 20:49:10 marco
  831. * arraytostring added
  832. Revision 1.66 2004/10/24 20:01:42 peter
  833. * saveregisters calling convention is obsolete
  834. Revision 1.65 2004/10/09 21:00:46 jonas
  835. + cgenmath with libc math functions. Faster than the routines in genmath
  836. and also have full double support (exp() only has support for values in
  837. the single range in genmath, for example). Used in FPC_USE_LIBC is
  838. defined
  839. * several fixes to allow compilation with -dHASINLINE, but internalerrors
  840. because of missing support for inlining assembler code
  841. Revision 1.64 2004/09/03 19:26:01 olle
  842. + added maxExitCode to all System.pp
  843. * constrained error code to be below maxExitCode in RunError et. al.
  844. Revision 1.63 2004/08/31 12:23:53 jonas
  845. * fixed compilation with 1.0.x
  846. Revision 1.62 2004/08/30 17:36:18 jonas
  847. * fixed random(int64)
  848. Revision 1.61 2004/08/29 10:23:12 peter
  849. no message
  850. Revision 1.60 2004/07/18 20:21:44 florian
  851. + several unicode (to/from utf-8 conversion) stuff added
  852. * some longint -> SizeInt changes
  853. Revision 1.59 2004/05/27 23:34:23 peter
  854. * stop backtrace also when caller frame is nil
  855. Revision 1.58 2004/05/16 18:51:20 peter
  856. * use thandle in do_*
  857. Revision 1.57 2004/05/01 15:26:33 jonas
  858. * use some more string routines from libc if FPC_USE_LIBC is used
  859. Revision 1.56 2004/04/22 19:43:43 peter
  860. * fix 64bit address printing
  861. Revision 1.55 2004/04/22 17:10:38 peter
  862. * random(int64) added
  863. Revision 1.54 2004/02/20 11:01:20 daniel
  864. * Applied
  865. Revision 1.53 2004/02/06 20:17:13 daniel
  866. * Use $ for hex numbers instead of alien 0x
  867. Revision 1.52 2004/01/22 20:12:37 florian
  868. * fixed syscall number
  869. Revision 1.51 2004/01/11 12:21:06 jonas
  870. * fixed wrong include filename
  871. Revision 1.50 2004/01/11 11:10:07 jonas
  872. + cgeneric.inc: implementations of rtl routines based on libc
  873. * system.inc: include cgeneric.inc before powerpc.inc/i386.inc/... if
  874. FPC_USE_LIBC is defined
  875. * powerpc.inc, i386.inc: check whether the routines they implement aren't
  876. implemented yet in another include file (cgeneric.inc)
  877. Revision 1.49 2004/01/02 17:21:50 jonas
  878. + fpc_cpuinit procedure to allow cpu/fpu initialisation before any unit
  879. initialises
  880. + fpu exceptions for invalid operations and division by zero enabled for
  881. ppc
  882. Revision 1.48 2004/01/01 17:58:16 jonas
  883. + integer division-by-zero detection support for ppc
  884. + compilerproc FPC_DIVBYZERO
  885. Revision 1.47 2003/11/03 09:42:28 marco
  886. * Peter's Cardinal<->Longint fixes patch
  887. Revision 1.46 2003/10/29 18:23:45 jonas
  888. * hack to allow repeatable random sequences using the new random number
  889. generator
  890. * fixed range warning/error
  891. Revision 1.45 2003/10/26 21:15:43 hajny
  892. * minor fix for new Random
  893. Revision 1.44 2003/10/26 18:46:02 jonas
  894. * replaced random generator with the Mersenne twister, which is about
  895. 3.5 times faster
  896. Revision 1.43 2003/09/14 11:34:13 peter
  897. * moved int64 asm code to int64p.inc
  898. * save ebx,esi
  899. Revision 1.42 2003/09/03 14:09:37 florian
  900. * arm fixes to the common rtl code
  901. * some generic math code fixed
  902. * ...
  903. Revision 1.41 2003/08/21 22:10:55 olle
  904. - removed parameter from fpc_iocheck
  905. * changed processor compiler directive * to cpu*
  906. Revision 1.40 2003/03/17 14:30:11 peter
  907. * changed address parameter/return values to pointer instead
  908. of longint
  909. Revision 1.39 2003/02/05 21:48:34 mazen
  910. * fixing run time errors related to unimplemented abstract methods in CG
  911. + giving empty emplementations for some RTL functions
  912. Revision 1.38 2002/12/07 14:36:33 carl
  913. - avoid warnings (add typecast)
  914. Revision 1.37 2002/11/18 18:33:51 peter
  915. * Swap(QWord) constant support
  916. Revision 1.36 2002/10/14 19:39:17 peter
  917. * threads unit added for thread support
  918. Revision 1.35 2002/09/18 18:32:01 carl
  919. * assert now halts with exitcode 227 (as Delphi does)
  920. Revision 1.34 2002/09/07 15:07:46 peter
  921. * old logs removed and tabs fixed
  922. Revision 1.33 2002/08/19 19:34:02 peter
  923. * SYSTEMINLINE define that will add inline directives for small
  924. functions and wrappers. This will be defined automaticly when
  925. the compiler defines the HASINLINE directive
  926. Revision 1.32 2002/07/28 20:43:48 florian
  927. * several fixes for linux/powerpc
  928. * several fixes to MT
  929. Revision 1.31 2002/07/26 22:46:06 florian
  930. * interface of system unit for Linux/PowerPC compiles
  931. Revision 1.30 2002/07/26 16:42:00 florian
  932. * endian directive for PowerPC fixed
  933. Revision 1.29 2002/07/04 20:40:09 florian
  934. + some x86-64 support added
  935. Revision 1.28 2002/04/21 15:51:50 carl
  936. * StackError is now a typed constant
  937. + $S can be used under unix
  938. Revision 1.27 2002/04/15 19:38:40 peter
  939. * stackcheck protected against infinite recursive after stack error
  940. * stackcheck requires saveregisters, because it can be called from
  941. iocheck and then will destroy the result of the original function
  942. Revision 1.26 2002/04/15 18:51:20 carl
  943. + generic stack checking can be overriden
  944. Revision 1.25 2002/04/12 17:37:36 carl
  945. + generic stack checking
  946. }