system.inc 35 KB

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