system.inc 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. {$i variant.inc}
  221. {****************************************************************************
  222. Run-Time Type Information (RTTI)
  223. ****************************************************************************}
  224. {$i rtti.inc}
  225. {----------------------------------------------------------------------
  226. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  227. Pseudo-Random Number Generator.
  228. What is Mersenne Twister?
  229. Mersenne Twister(MT) is a pseudorandom number generator developped by
  230. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  231. 1996-1997. MT has the following merits:
  232. It is designed with consideration on the flaws of various existing
  233. generators.
  234. Far longer period and far higher order of equidistribution than any
  235. other implemented generators. (It is proved that the period is 2^19937-1,
  236. and 623-dimensional equidistribution property is assured.)
  237. Fast generation. (Although it depends on the system, it is reported that
  238. MT is sometimes faster than the standard ANSI-C library in a system
  239. with pipeline and cache memory.)
  240. Efficient use of the memory. (The implemented C-code mt19937.c
  241. consumes only 624 words of working area.)
  242. home page
  243. http://www.math.keio.ac.jp/~matumoto/emt.html
  244. original c source
  245. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  246. Coded by Takuji Nishimura, considering the suggestions by
  247. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  248. This library is free software; you can redistribute it and/or
  249. modify it under the terms of the GNU Library General Public
  250. License as published by the Free Software Foundation; either
  251. version 2 of the License, or (at your option) any later
  252. version.
  253. This library is distributed in the hope that it will be useful,
  254. but WITHOUT ANY WARRANTY; without even the implied warranty of
  255. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  256. See the GNU Library General Public License for more details.
  257. You should have received a copy of the GNU Library General
  258. Public License along with this library; if not, write to the
  259. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  260. 02111-1307 USA
  261. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  262. When you use this, send an email to: [email protected]
  263. with an appropriate reference to your work.
  264. REFERENCE
  265. M. Matsumoto and T. Nishimura,
  266. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  267. Pseudo-Random Number Generator",
  268. ACM Transactions on Modeling and Computer Simulation,
  269. Vol. 8, No. 1, January 1998, pp 3--30.
  270. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  271. http://www.rksolution.cz/delphi/tips.htm
  272. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  273. 2003/10/26: adapted to use the improved intialisation mentioned at
  274. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  275. removed the assembler code
  276. ----------------------------------------------------------------------}
  277. {$R-} {range checking off}
  278. {$Q-} {overflow checking off}
  279. { Period parameter }
  280. Const
  281. MT19937N=624;
  282. Type
  283. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  284. { Period parameters }
  285. const
  286. MT19937M=397;
  287. MT19937MATRIX_A =$9908b0df; // constant vector a
  288. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  289. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  290. { Tempering parameters }
  291. TEMPERING_MASK_B=$9d2c5680;
  292. TEMPERING_MASK_C=$efc60000;
  293. VAR
  294. mt : tMT19937StateArray;
  295. const
  296. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  297. { Initializing the array with a seed }
  298. procedure sgenrand_MT19937(seed: longint);
  299. var
  300. i: longint;
  301. begin
  302. mt[0] := seed;
  303. for i := 1 to MT19937N-1 do
  304. begin
  305. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  306. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  307. { In the previous versions, MSBs of the seed affect }
  308. { only MSBs of the array mt[]. }
  309. { 2002/01/09 modified by Makoto Matsumoto }
  310. end;
  311. mti := MT19937N;
  312. end;
  313. function genrand_MT19937: longint;
  314. const
  315. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  316. var
  317. y: longint;
  318. kk: longint;
  319. begin
  320. if RandSeed<>OldRandSeed then
  321. mti:=MT19937N+1;
  322. if (mti >= MT19937N) { generate MT19937N longints at one time }
  323. then begin
  324. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  325. begin
  326. sgenrand_MT19937(randseed); // default initial seed is used
  327. { hack: randseed is not used more than once in this algorithm. Most }
  328. { user changes are re-initialising reandseed with the value it had }
  329. { at the start -> with the "not", we will detect this change. }
  330. { Detecting other changes is not useful, since the generated }
  331. { numbers will be different anyway. }
  332. randseed := not(randseed);
  333. oldrandseed := randseed;
  334. end;
  335. for kk:=0 to MT19937N-MT19937M-1 do begin
  336. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  337. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  338. end;
  339. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  340. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  341. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  342. end;
  343. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  344. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  345. mti := 0;
  346. end;
  347. y := mt[mti]; inc(mti);
  348. y := y xor (y shr 11);
  349. y := y xor (y shl 7) and TEMPERING_MASK_B;
  350. y := y xor (y shl 15) and TEMPERING_MASK_C;
  351. y := y xor (y shr 18);
  352. Result := y;
  353. end;
  354. function random(l:longint): longint;
  355. begin
  356. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  357. end;
  358. function random(l:int64): int64;
  359. begin
  360. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff) mod l;
  361. end;
  362. function random: extended;
  363. begin
  364. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  365. end;
  366. {****************************************************************************
  367. Memory Management
  368. ****************************************************************************}
  369. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_ptr];{$endif}
  370. Begin
  371. ptr:=farpointer((sel shl 4)+off);
  372. End;
  373. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  374. Begin
  375. Cseg:=0;
  376. End;
  377. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  378. Begin
  379. Dseg:=0;
  380. End;
  381. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  382. Begin
  383. Sseg:=0;
  384. End;
  385. {*****************************************************************************
  386. Directory support.
  387. *****************************************************************************}
  388. Procedure getdir(drivenr:byte;Var dir:ansistring);
  389. { this is needed to also allow ansistrings, the shortstring version is
  390. OS dependent }
  391. var
  392. s : shortstring;
  393. begin
  394. getdir(drivenr,s);
  395. dir:=s;
  396. end;
  397. {$ifopt R+}
  398. {$define RangeCheckWasOn}
  399. {$R-}
  400. {$endif opt R+}
  401. {$ifopt I+}
  402. {$define IOCheckWasOn}
  403. {$I-}
  404. {$endif opt I+}
  405. {$ifopt Q+}
  406. {$define OverflowCheckWasOn}
  407. {$Q-}
  408. {$endif opt Q+}
  409. {*****************************************************************************
  410. Miscellaneous
  411. *****************************************************************************}
  412. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; {$ifdef hascompilerproc} compilerproc; {$endif}
  413. begin
  414. HandleErrorFrame(201,get_frame);
  415. end;
  416. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; {$ifdef hascompilerproc} compilerproc; {$endif}
  417. begin
  418. HandleErrorFrame(200,get_frame);
  419. end;
  420. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; {$ifdef hascompilerproc} compilerproc; {$endif}
  421. begin
  422. HandleErrorFrame(215,get_frame);
  423. end;
  424. procedure fpc_iocheck;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_IOCHECK']; {$ifdef hascompilerproc} compilerproc; {$endif}
  425. var
  426. l : longint;
  427. begin
  428. if InOutRes<>0 then
  429. begin
  430. l:=InOutRes;
  431. InOutRes:=0;
  432. HandleErrorFrame(l,get_frame);
  433. end;
  434. end;
  435. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  436. Begin
  437. IOResult:=InOutRes;
  438. InOutRes:=0;
  439. End;
  440. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  441. begin
  442. (* ThreadID is stored in a threadvar and made available in interface *)
  443. (* to allow setup of this value during thread initialization. *)
  444. GetThreadID := ThreadID;
  445. end;
  446. {*****************************************************************************
  447. Stack check code
  448. *****************************************************************************}
  449. {$IFNDEF NO_GENERIC_STACK_CHECK}
  450. {$IFOPT S+}
  451. {$DEFINE STACKCHECK}
  452. {$ENDIF}
  453. {$S-}
  454. procedure fpc_stackcheck(stack_size:Cardinal);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_STACKCHECK'];
  455. var
  456. c : Pointer;
  457. begin
  458. { Avoid recursive calls when called from the exit routines }
  459. if StackError then
  460. exit;
  461. c := Sptr - (stack_size + STACK_MARGIN);
  462. if (c <= StackBottom) then
  463. begin
  464. StackError:=true;
  465. HandleError(202);
  466. end;
  467. end;
  468. {$IFDEF STACKCHECK}
  469. {$S+}
  470. {$ENDIF}
  471. {$UNDEF STACKCHECK}
  472. {$ENDIF NO_GENERIC_STACK_CHECK}
  473. {*****************************************************************************
  474. Initialization / Finalization
  475. *****************************************************************************}
  476. const
  477. maxunits=1024; { See also files.pas of the compiler source }
  478. type
  479. TInitFinalRec=record
  480. InitProc,
  481. FinalProc : TProcedure;
  482. end;
  483. TInitFinalTable=record
  484. TableCount,
  485. InitCount : longint;
  486. Procs : array[1..maxunits] of TInitFinalRec;
  487. end;
  488. var
  489. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  490. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; {$ifdef hascompilerproc} compilerproc; {$endif}
  491. var
  492. i : longint;
  493. begin
  494. { call cpu/fpu initialisation routine }
  495. fpc_cpuinit;
  496. with InitFinalTable do
  497. begin
  498. for i:=1 to TableCount do
  499. begin
  500. if assigned(Procs[i].InitProc) then
  501. Procs[i].InitProc();
  502. InitCount:=i;
  503. end;
  504. end;
  505. if assigned(InitProc) then
  506. TProcedure(InitProc)();
  507. end;
  508. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  509. begin
  510. with InitFinalTable do
  511. begin
  512. while (InitCount>0) do
  513. begin
  514. // we've to decrement the cound before calling the final. code
  515. // else a halt in the final. code leads to a endless loop
  516. dec(InitCount);
  517. if assigned(Procs[InitCount+1].FinalProc) then
  518. Procs[InitCount+1].FinalProc();
  519. end;
  520. end;
  521. end;
  522. {*****************************************************************************
  523. Error / Exit / ExitProc
  524. *****************************************************************************}
  525. Procedure system_exit;forward;
  526. Procedure InternalExit;
  527. var
  528. current_exit : Procedure;
  529. Begin
  530. while exitProc<>nil Do
  531. Begin
  532. InOutRes:=0;
  533. current_exit:=tProcedure(exitProc);
  534. exitProc:=nil;
  535. current_exit();
  536. End;
  537. { Finalize units }
  538. FinalizeUnits;
  539. { Show runtime error and exit }
  540. If erroraddr<>nil Then
  541. Begin
  542. Writeln(stdout,'Runtime error ',Errorcode,' at $',hexstr(PtrInt(Erroraddr),sizeof(PtrInt)*2));
  543. { to get a nice symify }
  544. Writeln(stdout,BackTraceStrFunc(Erroraddr));
  545. dump_stack(stdout,ErrorBase);
  546. Writeln(stdout,'');
  547. End;
  548. End;
  549. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  550. begin
  551. InternalExit;
  552. System_exit;
  553. end;
  554. Procedure lib_exit;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[Public,Alias:'FPC_LIB_EXIT'];
  555. begin
  556. InternalExit;
  557. end;
  558. Procedure Halt(ErrNum: Byte);
  559. Begin
  560. ExitCode:=Errnum;
  561. Do_Exit;
  562. end;
  563. function SysBackTraceStr (Addr: Pointer): ShortString;
  564. begin
  565. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  566. end;
  567. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  568. begin
  569. If pointer(ErrorProc)<>Nil then
  570. ErrorProc(Errno,addr,frame);
  571. errorcode:=word(Errno);
  572. erroraddr:=addr;
  573. errorbase:=frame;
  574. if errorcode <= maxExitCode then
  575. halt(errorcode)
  576. else
  577. halt(255)
  578. end;
  579. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  580. {
  581. Procedure to handle internal errors, i.e. not user-invoked errors
  582. Internal function should ALWAYS call HandleError instead of RunError.
  583. Can be used for exception handlers to specify the frame
  584. }
  585. begin
  586. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  587. end;
  588. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  589. {
  590. Procedure to handle internal errors, i.e. not user-invoked errors
  591. Internal function should ALWAYS call HandleError instead of RunError.
  592. }
  593. begin
  594. HandleErrorFrame(Errno,get_frame);
  595. end;
  596. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  597. begin
  598. errorcode:=w;
  599. erroraddr:=get_caller_addr(get_frame);
  600. errorbase:=get_caller_frame(get_frame);
  601. if errorcode <= maxExitCode then
  602. halt(errorcode)
  603. else
  604. halt(255)
  605. end;
  606. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  607. Begin
  608. RunError (0);
  609. End;
  610. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  611. Begin
  612. Halt(0);
  613. End;
  614. function do_isdevice(handle:thandle):boolean;forward;
  615. Procedure dump_stack(var f : text;bp : Pointer);
  616. var
  617. i : Longint;
  618. prevbp : Pointer;
  619. is_dev : boolean;
  620. caller_frame,
  621. caller_addr : Pointer;
  622. Begin
  623. prevbp:=bp-1;
  624. i:=0;
  625. is_dev:=do_isdevice(textrec(f).Handle);
  626. while bp > prevbp Do
  627. Begin
  628. caller_addr := get_caller_addr(bp);
  629. caller_frame := get_caller_frame(bp);
  630. if (caller_addr=nil) or
  631. (caller_frame=nil) then
  632. break;
  633. Writeln(f,BackTraceStrFunc(caller_addr));
  634. Inc(i);
  635. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  636. break;
  637. prevbp:=bp;
  638. bp:=caller_frame;
  639. End;
  640. End;
  641. Type
  642. PExitProcInfo = ^TExitProcInfo;
  643. TExitProcInfo = Record
  644. Next : PExitProcInfo;
  645. SaveExit : Pointer;
  646. Proc : TProcedure;
  647. End;
  648. const
  649. ExitProcList: PExitProcInfo = nil;
  650. Procedure DoExitProc;
  651. var
  652. P : PExitProcInfo;
  653. Proc : TProcedure;
  654. Begin
  655. P:=ExitProcList;
  656. ExitProcList:=P^.Next;
  657. ExitProc:=P^.SaveExit;
  658. Proc:=P^.Proc;
  659. DisPose(P);
  660. Proc();
  661. End;
  662. Procedure AddExitProc(Proc: TProcedure);
  663. var
  664. P : PExitProcInfo;
  665. Begin
  666. New(P);
  667. P^.Next:=ExitProcList;
  668. P^.SaveExit:=ExitProc;
  669. P^.Proc:=Proc;
  670. ExitProcList:=P;
  671. ExitProc:=@DoExitProc;
  672. End;
  673. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  674. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  675. // Note: for internal use by skilled programmers only
  676. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  677. var p : ppchar;
  678. i : LongInt;
  679. begin
  680. if High(s)<Low(s) Then Exit(NIL);
  681. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  682. // for cmd
  683. if p=nil then
  684. begin
  685. {$ifdef xunix}
  686. fpseterrno(ESysEnomem);
  687. {$endif}
  688. exit(NIL);
  689. end;
  690. for i:=low(s) to high(s) do
  691. p[i+Reserveentries]:=pchar(s[i]);
  692. p[high(s)+1+Reserveentries]:=nil;
  693. ArrayStringToPPchar:=p;
  694. end;
  695. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  696. {
  697. Create a PPChar to structure of pchars which are the arguments specified
  698. in the string S. Especially usefull for creating an ArgV for Exec-calls
  699. }
  700. begin
  701. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  702. end;
  703. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  704. var
  705. i,nr : longint;
  706. Buf : ^char;
  707. p : ppchar;
  708. begin
  709. buf:=s;
  710. nr:=1;
  711. while (buf^<>#0) do // count nr of args
  712. begin
  713. while (buf^ in [' ',#9,#10]) do // Kill separators.
  714. inc(buf);
  715. inc(nr);
  716. if buf^='"' Then // quotes argument?
  717. begin
  718. inc(buf);
  719. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  720. inc(buf);
  721. if buf^='"' then // skip closing quote.
  722. inc(buf);
  723. end
  724. else
  725. begin // else std
  726. while not (buf^ in [' ',#0,#9,#10]) do
  727. inc(buf);
  728. end;
  729. end;
  730. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  731. StringToPPChar:=p;
  732. if p=nil then
  733. begin
  734. {$ifdef xunix}
  735. fpseterrno(ESysEnomem);
  736. {$endif}
  737. exit;
  738. end;
  739. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  740. buf:=s;
  741. while (buf^<>#0) do
  742. begin
  743. while (buf^ in [' ',#9,#10]) do // Kill separators.
  744. begin
  745. buf^:=#0;
  746. inc(buf);
  747. end;
  748. if buf^='"' Then // quotes argument?
  749. begin
  750. inc(buf);
  751. p^:=buf;
  752. inc(p);
  753. p^:=nil;
  754. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  755. inc(buf);
  756. if buf^='"' then // skip closing quote.
  757. begin
  758. buf^:=#0;
  759. inc(buf);
  760. end;
  761. end
  762. else
  763. begin
  764. p^:=buf;
  765. inc(p);
  766. p^:=nil;
  767. while not (buf^ in [' ',#0,#9,#10]) do
  768. inc(buf);
  769. end;
  770. end;
  771. end;
  772. {*****************************************************************************
  773. Abstract/Assert support.
  774. *****************************************************************************}
  775. procedure fpc_AbstractErrorIntern;{$ifdef hascompilerproc}compilerproc;{$endif}[public,alias : 'FPC_ABSTRACTERROR'];
  776. begin
  777. If pointer(AbstractErrorProc)<>nil then
  778. AbstractErrorProc();
  779. HandleErrorFrame(211,get_frame);
  780. end;
  781. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif} [Public,Alias : 'FPC_ASSERT']; {$ifdef hascompilerproc} compilerproc; {$endif}
  782. begin
  783. if pointer(AssertErrorProc)<>nil then
  784. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  785. else
  786. HandleErrorFrame(227,get_frame);
  787. end;
  788. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  789. begin
  790. If msg='' then
  791. write(stderr,'Assertion failed')
  792. else
  793. write(stderr,msg);
  794. Writeln(stderr,' (',FName,', line ',LineNo,').');
  795. Writeln(stderr,'');
  796. Halt(227);
  797. end;
  798. {*****************************************************************************
  799. SetJmp/LongJmp support.
  800. *****************************************************************************}
  801. {$i setjump.inc}
  802. {$ifdef IOCheckWasOn}
  803. {$I+}
  804. {$endif}
  805. {$ifdef RangeCheckWasOn}
  806. {$R+}
  807. {$endif}
  808. {$ifdef OverflowCheckWasOn}
  809. {$Q+}
  810. {$endif}
  811. {*****************************************************************************
  812. OS dependent Helpers/Syscalls
  813. *****************************************************************************}
  814. {$i sysos.inc}
  815. {*****************************************************************************
  816. Heap
  817. *****************************************************************************}
  818. {$i sysheap.inc}
  819. {$i heap.inc}
  820. {*****************************************************************************
  821. Thread support
  822. *****************************************************************************}
  823. { Generic threadmanager }
  824. {$i thread.inc}
  825. { Generic threadvar support }
  826. {$i threadvr.inc}
  827. { OS Dependent implementation }
  828. {$i systhrd.inc}
  829. {*****************************************************************************
  830. File Handling
  831. *****************************************************************************}
  832. { OS dependent low level file functions }
  833. {$i sysfile.inc}
  834. { Text file }
  835. {$i text.inc}
  836. { Untyped file }
  837. {$i file.inc}
  838. { Typed file }
  839. {$i typefile.inc}
  840. {*****************************************************************************
  841. Directory Handling
  842. *****************************************************************************}
  843. { OS dependent dir functions }
  844. {$i sysdir.inc}