system.inc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  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 : longint;external name '__stklen';
  35. {****************************************************************************
  36. Routines which have compiler magic
  37. ****************************************************************************}
  38. {$ifndef INTERNCONSTINTF}
  39. Function lo(i : Integer) : byte; [INTERNPROC: fpc_in_lo_Word];
  40. Function lo(w : Word) : byte; [INTERNPROC: fpc_in_lo_Word];
  41. Function lo(l : Longint) : Word; [INTERNPROC: fpc_in_lo_long];
  42. Function lo(l : DWord) : Word; [INTERNPROC: fpc_in_lo_long];
  43. Function hi(i : Integer) : byte; [INTERNPROC: fpc_in_hi_Word];
  44. Function hi(w : Word) : byte; [INTERNPROC: fpc_in_hi_Word];
  45. Function hi(l : Longint) : Word; [INTERNPROC: fpc_in_hi_long];
  46. Function hi(l : DWord) : Word; [INTERNPROC: fpc_in_hi_long];
  47. Function lo(q : QWord) : DWord; [INTERNPROC: fpc_in_lo_qword];
  48. Function lo(i : Int64) : DWord; [INTERNPROC: fpc_in_lo_qword];
  49. Function hi(q : QWord) : DWord; [INTERNPROC: fpc_in_hi_qword];
  50. Function hi(i : Int64) : DWord; [INTERNPROC: fpc_in_hi_qword];
  51. Function chr(b : byte) : Char; [INTERNPROC: fpc_in_chr_byte];
  52. {$ifndef INTERNLENGTH}
  53. Function Length(s : string) : byte; [INTERNPROC: fpc_in_Length_string];
  54. Function Length(c : char) : byte; [INTERNPROC: fpc_in_Length_string];
  55. {$endif INTERNLENGTH}
  56. Procedure Reset(var f : TypedFile); [INTERNPROC: fpc_in_Reset_TypedFile];
  57. Procedure Rewrite(var f : TypedFile); [INTERNPROC: fpc_in_Rewrite_TypedFile];
  58. {$endif INTERNCONSTINTF}
  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. { is now declared as external reference to another routine in the interface }
  66. {$i cgenstr.inc}
  67. {$endif FPC_USE_LIBC}
  68. {$ifdef cpui386}
  69. {$ifdef SYSPROCDEFINED}
  70. {$Error Can't determine processor type !}
  71. {$endif}
  72. {$i i386.inc} { Case dependent, don't change }
  73. {$endif cpui386}
  74. {$ifdef cpum68k}
  75. {$ifdef SYSPROCDEFINED}
  76. {$Error Can't determine processor type !}
  77. {$endif}
  78. {$i m68k.inc} { Case dependent, don't change }
  79. {$define SYSPROCDEFINED}
  80. {$endif cpum68k}
  81. {$ifdef cpux86_64}
  82. {$ifdef SYSPROCDEFINED}
  83. {$Error Can't determine processor type !}
  84. {$endif}
  85. {$i x86_64.inc} { Case dependent, don't change }
  86. {$define SYSPROCDEFINED}
  87. {$endif cpux86_64}
  88. {$ifdef cpupowerpc}
  89. {$ifdef SYSPROCDEFINED}
  90. {$Error Can't determine processor type !}
  91. {$endif}
  92. {$i powerpc.inc} { Case dependent, don't change }
  93. {$define SYSPROCDEFINED}
  94. {$endif cpupowerpc}
  95. {$ifdef cpualpha}
  96. {$ifdef SYSPROCDEFINED}
  97. {$Error Can't determine processor type !}
  98. {$endif}
  99. {$i alpha.inc} { Case dependent, don't change }
  100. {$define SYSPROCDEFINED}
  101. {$endif cpualpha}
  102. {$ifdef cpuiA64}
  103. {$ifdef SYSPROCDEFINED}
  104. {$Error Can't determine processor type !}
  105. {$endif}
  106. {$i ia64.inc} { Case dependent, don't change }
  107. {$define SYSPROCDEFINED}
  108. {$endif cpuiA64}
  109. {$ifdef cpusparc}
  110. {$ifdef SYSPROCDEFINED}
  111. {$Error Can't determine processor type !}
  112. {$endif}
  113. {$i sparc.inc} { Case dependent, don't change }
  114. {$define SYSPROCDEFINED}
  115. {$endif cpusparc}
  116. {$ifdef cpuarm}
  117. {$ifdef SYSPROCDEFINED}
  118. {$Error Can't determine processor type !}
  119. {$endif}
  120. {$i arm.inc} { Case dependent, don't change }
  121. {$define SYSPROCDEFINED}
  122. {$endif cpuarm}
  123. procedure fillchar(var x;count : SizeInt;value : boolean);{$ifdef SYSTEMINLINE}inline;{$endif}
  124. begin
  125. fillchar(x,count,byte(value));
  126. end;
  127. procedure fillchar(var x;count : SizeInt;value : char);{$ifdef SYSTEMINLINE}inline;{$endif}
  128. begin
  129. fillchar(x,count,byte(value));
  130. end;
  131. { Include generic pascal only routines which are not defined in the processor
  132. specific include file }
  133. {$I generic.inc}
  134. {****************************************************************************
  135. Set Handling
  136. ****************************************************************************}
  137. { Include set support which is processor specific}
  138. {$i set.inc}
  139. { Include generic pascal routines for sets if the processor }
  140. { specific routines are not available. }
  141. {$i genset.inc}
  142. {****************************************************************************
  143. Math Routines
  144. ****************************************************************************}
  145. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  146. begin
  147. Hi := b shr 4
  148. end;
  149. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  150. begin
  151. Lo := b and $0f
  152. end;
  153. Function swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  154. Begin
  155. swap:=(X and $ff) shl 8 + (X shr 8)
  156. End;
  157. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  158. Begin
  159. swap:=(X and $ff) shl 8 + (X shr 8)
  160. End;
  161. Function swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  162. Begin
  163. Swap:=(X and $ffff) shl 16 + (X shr 16)
  164. End;
  165. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  166. Begin
  167. Swap:=(X and $ffff) shl 16 + (X shr 16)
  168. End;
  169. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  170. Begin
  171. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  172. End;
  173. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  174. Begin
  175. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  176. End;
  177. {$ifdef SUPPORT_DOUBLE}
  178. operator := (b:real48) d:double;
  179. begin
  180. D:=real2double(b);
  181. end;
  182. {$endif SUPPORT_DOUBLE}
  183. {$ifdef SUPPORT_EXTENDED}
  184. operator := (b:real48) e:extended;
  185. begin
  186. e:=real2double(b);
  187. end;
  188. {$endif SUPPORT_EXTENDED}
  189. {$ifdef FPC_USE_LIBC}
  190. { Include libc versions }
  191. {$i cgenmath.inc}
  192. {$endif FPC_USE_LIBC}
  193. { Include processor specific routines }
  194. {$I math.inc}
  195. { Include generic version }
  196. {$I genmath.inc}
  197. {****************************************************************************
  198. Subroutines for String handling
  199. ****************************************************************************}
  200. { Needs to be before RTTI handling }
  201. {$i sstrings.inc}
  202. { requires sstrings.inc for initval }
  203. {$I int64p.inc}
  204. {$I int64.inc}
  205. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  206. {$i astrings.inc}
  207. {$i wstrings.inc}
  208. {$i aliases.inc}
  209. {*****************************************************************************
  210. Dynamic Array support
  211. *****************************************************************************}
  212. {$i dynarr.inc}
  213. {*****************************************************************************
  214. Object Pascal support
  215. *****************************************************************************}
  216. {$i objpas.inc}
  217. {*****************************************************************************
  218. Variant support
  219. *****************************************************************************}
  220. {$ifdef HASVARIANT}
  221. {$i variant.inc}
  222. {$endif HASVARIANT}
  223. {****************************************************************************
  224. Run-Time Type Information (RTTI)
  225. ****************************************************************************}
  226. {$i rtti.inc}
  227. {----------------------------------------------------------------------
  228. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  229. Pseudo-Random Number Generator.
  230. What is Mersenne Twister?
  231. Mersenne Twister(MT) is a pseudorandom number generator developped by
  232. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  233. 1996-1997. MT has the following merits:
  234. It is designed with consideration on the flaws of various existing
  235. generators.
  236. Far longer period and far higher order of equidistribution than any
  237. other implemented generators. (It is proved that the period is 2^19937-1,
  238. and 623-dimensional equidistribution property is assured.)
  239. Fast generation. (Although it depends on the system, it is reported that
  240. MT is sometimes faster than the standard ANSI-C library in a system
  241. with pipeline and cache memory.)
  242. Efficient use of the memory. (The implemented C-code mt19937.c
  243. consumes only 624 words of working area.)
  244. home page
  245. http://www.math.keio.ac.jp/~matumoto/emt.html
  246. original c source
  247. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  248. Coded by Takuji Nishimura, considering the suggestions by
  249. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  250. This library is free software; you can redistribute it and/or
  251. modify it under the terms of the GNU Library General Public
  252. License as published by the Free Software Foundation; either
  253. version 2 of the License, or (at your option) any later
  254. version.
  255. This library is distributed in the hope that it will be useful,
  256. but WITHOUT ANY WARRANTY; without even the implied warranty of
  257. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  258. See the GNU Library General Public License for more details.
  259. You should have received a copy of the GNU Library General
  260. Public License along with this library; if not, write to the
  261. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  262. 02111-1307 USA
  263. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  264. When you use this, send an email to: [email protected]
  265. with an appropriate reference to your work.
  266. REFERENCE
  267. M. Matsumoto and T. Nishimura,
  268. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  269. Pseudo-Random Number Generator",
  270. ACM Transactions on Modeling and Computer Simulation,
  271. Vol. 8, No. 1, January 1998, pp 3--30.
  272. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  273. http://www.rksolution.cz/delphi/tips.htm
  274. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  275. 2003/10/26: adapted to use the improved intialisation mentioned at
  276. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  277. removed the assembler code
  278. ----------------------------------------------------------------------}
  279. {$R-} {range checking off}
  280. {$Q-} {overflow checking off}
  281. { Period parameter }
  282. Const
  283. MT19937N=624;
  284. Type
  285. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  286. { Period parameters }
  287. const
  288. MT19937M=397;
  289. MT19937MATRIX_A =$9908b0df; // constant vector a
  290. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  291. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  292. { Tempering parameters }
  293. TEMPERING_MASK_B=$9d2c5680;
  294. TEMPERING_MASK_C=$efc60000;
  295. VAR
  296. mt : tMT19937StateArray;
  297. const
  298. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  299. { Initializing the array with a seed }
  300. procedure sgenrand_MT19937(seed: longint);
  301. var
  302. i: longint;
  303. begin
  304. mt[0] := seed;
  305. for i := 1 to MT19937N-1 do
  306. begin
  307. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  308. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  309. { In the previous versions, MSBs of the seed affect }
  310. { only MSBs of the array mt[]. }
  311. { 2002/01/09 modified by Makoto Matsumoto }
  312. end;
  313. mti := MT19937N;
  314. end;
  315. function genrand_MT19937: longint;
  316. const
  317. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  318. var
  319. y: longint;
  320. kk: longint;
  321. begin
  322. if RandSeed<>OldRandSeed then
  323. mti:=MT19937N+1;
  324. if (mti >= MT19937N) { generate MT19937N longints at one time }
  325. then begin
  326. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  327. begin
  328. sgenrand_MT19937(randseed); // default initial seed is used
  329. { hack: randseed is not used more than once in this algorithm. Most }
  330. { user changes are re-initialising reandseed with the value it had }
  331. { at the start -> with the "not", we will detect this change. }
  332. { Detecting other changes is not useful, since the generated }
  333. { numbers will be different anyway. }
  334. randseed := not(randseed);
  335. oldrandseed := randseed;
  336. end;
  337. for kk:=0 to MT19937N-MT19937M-1 do begin
  338. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  339. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  340. end;
  341. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  342. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  343. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  344. end;
  345. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  346. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  347. mti := 0;
  348. end;
  349. y := mt[mti]; inc(mti);
  350. y := y xor (y shr 11);
  351. y := y xor (y shl 7) and TEMPERING_MASK_B;
  352. y := y xor (y shl 15) and TEMPERING_MASK_C;
  353. y := y xor (y shr 18);
  354. Result := y;
  355. end;
  356. function random(l:longint): longint;
  357. begin
  358. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  359. end;
  360. function random(l:int64): int64;
  361. begin
  362. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff) mod l;
  363. end;
  364. function random: extended;
  365. begin
  366. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  367. end;
  368. {****************************************************************************
  369. Memory Management
  370. ****************************************************************************}
  371. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_ptr];{$endif}
  372. Begin
  373. ptr:=farpointer((sel shl 4)+off);
  374. End;
  375. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  376. Begin
  377. Cseg:=0;
  378. End;
  379. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  380. Begin
  381. Dseg:=0;
  382. End;
  383. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  384. Begin
  385. Sseg:=0;
  386. End;
  387. {*****************************************************************************
  388. Directory support.
  389. *****************************************************************************}
  390. Procedure getdir(drivenr:byte;Var dir:ansistring);
  391. { this is needed to also allow ansistrings, the shortstring version is
  392. OS dependent }
  393. var
  394. s : shortstring;
  395. begin
  396. getdir(drivenr,s);
  397. dir:=s;
  398. end;
  399. {$ifopt R+}
  400. {$define RangeCheckWasOn}
  401. {$R-}
  402. {$endif opt R+}
  403. {$ifopt I+}
  404. {$define IOCheckWasOn}
  405. {$I-}
  406. {$endif opt I+}
  407. {$ifopt Q+}
  408. {$define OverflowCheckWasOn}
  409. {$Q-}
  410. {$endif opt Q+}
  411. {*****************************************************************************
  412. Miscellaneous
  413. *****************************************************************************}
  414. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; {$ifdef hascompilerproc} compilerproc; {$endif}
  415. begin
  416. HandleErrorFrame(201,get_frame);
  417. end;
  418. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; {$ifdef hascompilerproc} compilerproc; {$endif}
  419. begin
  420. HandleErrorFrame(200,get_frame);
  421. end;
  422. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; {$ifdef hascompilerproc} compilerproc; {$endif}
  423. begin
  424. HandleErrorFrame(215,get_frame);
  425. end;
  426. procedure fpc_iocheck;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_IOCHECK']; {$ifdef hascompilerproc} compilerproc; {$endif}
  427. var
  428. l : longint;
  429. begin
  430. if InOutRes<>0 then
  431. begin
  432. l:=InOutRes;
  433. InOutRes:=0;
  434. HandleErrorFrame(l,get_frame);
  435. end;
  436. end;
  437. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  438. Begin
  439. IOResult:=InOutRes;
  440. InOutRes:=0;
  441. End;
  442. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  443. begin
  444. (* ThreadID is stored in a threadvar and made available in interface *)
  445. (* to allow setup of this value during thread initialization. *)
  446. GetThreadID := ThreadID;
  447. end;
  448. {*****************************************************************************
  449. Stack check code
  450. *****************************************************************************}
  451. {$IFNDEF NO_GENERIC_STACK_CHECK}
  452. {$IFOPT S+}
  453. {$DEFINE STACKCHECK}
  454. {$ENDIF}
  455. {$S-}
  456. procedure fpc_stackcheck(stack_size:Cardinal);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_STACKCHECK'];
  457. var
  458. c : Pointer;
  459. begin
  460. { Avoid recursive calls when called from the exit routines }
  461. if StackError then
  462. exit;
  463. c := Sptr - (stack_size + STACK_MARGIN);
  464. if (c <= StackBottom) then
  465. begin
  466. StackError:=true;
  467. HandleError(202);
  468. end;
  469. end;
  470. {$IFDEF STACKCHECK}
  471. {$S+}
  472. {$ENDIF}
  473. {$UNDEF STACKCHECK}
  474. {$ENDIF NO_GENERIC_STACK_CHECK}
  475. {*****************************************************************************
  476. Initialization / Finalization
  477. *****************************************************************************}
  478. const
  479. maxunits=1024; { See also files.pas of the compiler source }
  480. type
  481. TInitFinalRec=record
  482. InitProc,
  483. FinalProc : TProcedure;
  484. end;
  485. TInitFinalTable=record
  486. TableCount,
  487. InitCount : longint;
  488. Procs : array[1..maxunits] of TInitFinalRec;
  489. end;
  490. var
  491. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  492. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; {$ifdef hascompilerproc} compilerproc; {$endif}
  493. var
  494. i : longint;
  495. begin
  496. { call cpu/fpu initialisation routine }
  497. fpc_cpuinit;
  498. with InitFinalTable do
  499. begin
  500. for i:=1 to TableCount do
  501. begin
  502. if assigned(Procs[i].InitProc) then
  503. Procs[i].InitProc();
  504. InitCount:=i;
  505. end;
  506. end;
  507. if assigned(InitProc) then
  508. TProcedure(InitProc)();
  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. i : LongInt;
  681. begin
  682. if High(s)<Low(s) Then Exit(NIL);
  683. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  684. // for cmd
  685. if p=nil then
  686. begin
  687. {$ifdef xunix}
  688. fpseterrno(ESysEnomem);
  689. {$endif}
  690. exit(NIL);
  691. end;
  692. for i:=low(s) to high(s) do
  693. p[i+Reserveentries]:=pchar(s[i]);
  694. p[high(s)+1+Reserveentries]:=nil;
  695. ArrayStringToPPchar:=p;
  696. end;
  697. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  698. {
  699. Create a PPChar to structure of pchars which are the arguments specified
  700. in the string S. Especially usefull for creating an ArgV for Exec-calls
  701. }
  702. begin
  703. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  704. end;
  705. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  706. var
  707. i,nr : longint;
  708. Buf : ^char;
  709. p : ppchar;
  710. begin
  711. buf:=s;
  712. nr:=1;
  713. while (buf^<>#0) do // count nr of args
  714. begin
  715. while (buf^ in [' ',#9,#10]) do // Kill separators.
  716. inc(buf);
  717. inc(nr);
  718. if buf^='"' Then // quotes argument?
  719. begin
  720. inc(buf);
  721. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  722. inc(buf);
  723. if buf^='"' then // skip closing quote.
  724. inc(buf);
  725. end
  726. else
  727. begin // else std
  728. while not (buf^ in [' ',#0,#9,#10]) do
  729. inc(buf);
  730. end;
  731. end;
  732. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  733. StringToPPChar:=p;
  734. if p=nil then
  735. begin
  736. {$ifdef xunix}
  737. fpseterrno(ESysEnomem);
  738. {$endif}
  739. exit;
  740. end;
  741. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  742. buf:=s;
  743. while (buf^<>#0) do
  744. begin
  745. while (buf^ in [' ',#9,#10]) do // Kill separators.
  746. begin
  747. buf^:=#0;
  748. inc(buf);
  749. end;
  750. if buf^='"' Then // quotes argument?
  751. begin
  752. inc(buf);
  753. p^:=buf;
  754. inc(p);
  755. p^:=nil;
  756. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  757. inc(buf);
  758. if buf^='"' then // skip closing quote.
  759. begin
  760. buf^:=#0;
  761. inc(buf);
  762. end;
  763. end
  764. else
  765. begin
  766. p^:=buf;
  767. inc(p);
  768. p^:=nil;
  769. while not (buf^ in [' ',#0,#9,#10]) do
  770. inc(buf);
  771. end;
  772. end;
  773. end;
  774. {*****************************************************************************
  775. Abstract/Assert support.
  776. *****************************************************************************}
  777. procedure fpc_AbstractErrorIntern;{$ifdef hascompilerproc}compilerproc;{$endif}[public,alias : 'FPC_ABSTRACTERROR'];
  778. begin
  779. If pointer(AbstractErrorProc)<>nil then
  780. AbstractErrorProc();
  781. HandleErrorFrame(211,get_frame);
  782. end;
  783. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif} [Public,Alias : 'FPC_ASSERT']; {$ifdef hascompilerproc} compilerproc; {$endif}
  784. begin
  785. if pointer(AssertErrorProc)<>nil then
  786. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  787. else
  788. HandleErrorFrame(227,get_frame);
  789. end;
  790. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  791. begin
  792. If msg='' then
  793. write(stderr,'Assertion failed')
  794. else
  795. write(stderr,msg);
  796. Writeln(stderr,' (',FName,', line ',LineNo,').');
  797. Writeln(stderr,'');
  798. Halt(227);
  799. end;
  800. {*****************************************************************************
  801. SetJmp/LongJmp support.
  802. *****************************************************************************}
  803. {$i setjump.inc}
  804. {$ifdef IOCheckWasOn}
  805. {$I+}
  806. {$endif}
  807. {$ifdef RangeCheckWasOn}
  808. {$R+}
  809. {$endif}
  810. {$ifdef OverflowCheckWasOn}
  811. {$Q+}
  812. {$endif}
  813. {*****************************************************************************
  814. OS dependent Helpers/Syscalls
  815. *****************************************************************************}
  816. {$i sysos.inc}
  817. {*****************************************************************************
  818. Heap
  819. *****************************************************************************}
  820. {$i sysheap.inc}
  821. {$i heap.inc}
  822. {*****************************************************************************
  823. Thread support
  824. *****************************************************************************}
  825. { Generic threadmanager }
  826. {$i thread.inc}
  827. { Generic threadvar support }
  828. {$i threadvr.inc}
  829. { OS Dependent implementation }
  830. {$i systhrd.inc}
  831. {*****************************************************************************
  832. File Handling
  833. *****************************************************************************}
  834. { OS dependent low level file functions }
  835. {$i sysfile.inc}
  836. { Text file }
  837. {$i text.inc}
  838. { Untyped file }
  839. {$i file.inc}
  840. { Typed file }
  841. {$i typefile.inc}
  842. {*****************************************************************************
  843. Directory Handling
  844. *****************************************************************************}
  845. { OS dependent dir functions }
  846. {$i sysdir.inc}