system.inc 32 KB

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