system.inc 29 KB

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