system.inc 35 KB

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