system.inc 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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 ansi/widestrings and maybe also other things in the future }
  32. var
  33. { widechar, because also used by widestring -> pwidechar conversions }
  34. emptychar : widechar;public name 'FPC_EMPTYCHAR';
  35. initialstklen : SizeUint;external name '__stklen';
  36. { checks whether the given suggested size for the stack of the current
  37. thread is acceptable. If this is the case, returns it unaltered.
  38. Otherwise it should return an acceptable value.
  39. Operating systems that automatically expand their stack on demand, should
  40. simply return a very large value.
  41. Operating systems which do not have a possibility to retrieve stack size
  42. information, should simply return the given stklen value (This is the default
  43. implementation).
  44. }
  45. {$ifdef FPC_HAS_FEATURE_STACKCHECK}
  46. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt; forward;
  47. {$endif FPC_HAS_FEATURE_STACKCHECK}
  48. {*****************************************************************************
  49. OS dependent Helpers/Syscalls
  50. *****************************************************************************}
  51. { for some OSes do_isdevice is defined in sysos.inc, but for others (win32)
  52. it isn't, and is used before the actual definition is encountered }
  53. {$ifdef FPC_HAS_FEATURE_FILEIO}
  54. function do_isdevice(handle:thandle):boolean;forward;
  55. {$endif FPC_HAS_FEATURE_FILEIO}
  56. {$i sysos.inc}
  57. {****************************************************************************
  58. Include processor specific routines
  59. ****************************************************************************}
  60. {$ifdef FPC_USE_LIBC}
  61. { prefer libc implementations over our own, as they're most likely faster }
  62. {$i cgeneric.inc}
  63. { is now declared as external reference to another routine in the interface }
  64. {$i cgenstr.inc}
  65. {$endif FPC_USE_LIBC}
  66. {$ifdef cpui386}
  67. {$ifdef SYSPROCDEFINED}
  68. {$Error Can't determine processor type !}
  69. {$endif}
  70. {$i i386.inc} { Case dependent, don't change }
  71. {$endif cpui386}
  72. {$ifdef cpum68k}
  73. {$ifdef SYSPROCDEFINED}
  74. {$Error Can't determine processor type !}
  75. {$endif}
  76. {$i m68k.inc} { Case dependent, don't change }
  77. {$define SYSPROCDEFINED}
  78. {$endif cpum68k}
  79. {$ifdef cpux86_64}
  80. {$ifdef SYSPROCDEFINED}
  81. {$Error Can't determine processor type !}
  82. {$endif}
  83. {$i x86_64.inc} { Case dependent, don't change }
  84. {$define SYSPROCDEFINED}
  85. {$endif cpux86_64}
  86. {$ifdef cpupowerpc32}
  87. {$ifdef SYSPROCDEFINED}
  88. {$Error Can't determine processor type !}
  89. {$endif}
  90. {$i powerpc.inc} { Case dependent, don't change }
  91. {$define SYSPROCDEFINED}
  92. {$endif cpupowerpc32}
  93. {$ifdef cpupowerpc64}
  94. {$ifdef SYSPROCDEFINED}
  95. {$Error Can't determine processor type !}
  96. {$endif}
  97. {$i powerpc64.inc} { Case dependent, don't change }
  98. {$define SYSPROCDEFINED}
  99. {$endif cpupowerpc64}
  100. {$ifdef cpualpha}
  101. {$ifdef SYSPROCDEFINED}
  102. {$Error Can't determine processor type !}
  103. {$endif}
  104. {$i alpha.inc} { Case dependent, don't change }
  105. {$define SYSPROCDEFINED}
  106. {$endif cpualpha}
  107. {$ifdef cpuiA64}
  108. {$ifdef SYSPROCDEFINED}
  109. {$Error Can't determine processor type !}
  110. {$endif}
  111. {$i ia64.inc} { Case dependent, don't change }
  112. {$define SYSPROCDEFINED}
  113. {$endif cpuiA64}
  114. {$ifdef cpusparc}
  115. {$ifdef SYSPROCDEFINED}
  116. {$Error Can't determine processor type !}
  117. {$endif}
  118. {$i sparc.inc} { Case dependent, don't change }
  119. {$define SYSPROCDEFINED}
  120. {$endif cpusparc}
  121. {$ifdef cpuarm}
  122. {$ifdef SYSPROCDEFINED}
  123. {$Error Can't determine processor type !}
  124. {$endif}
  125. {$i arm.inc} { Case dependent, don't change }
  126. {$define SYSPROCDEFINED}
  127. {$endif cpuarm}
  128. procedure fillchar(var x;count : SizeInt;value : boolean);{$ifdef SYSTEMINLINE}inline;{$endif}
  129. begin
  130. fillchar(x,count,byte(value));
  131. end;
  132. procedure fillchar(var x;count : SizeInt;value : char);{$ifdef SYSTEMINLINE}inline;{$endif}
  133. begin
  134. fillchar(x,count,byte(value));
  135. end;
  136. procedure FillByte (var x;count : SizeInt;value : byte ); {$ifdef SYSTEMINLINE}inline;{$endif}
  137. begin
  138. FillChar (X,Count,VALUE);
  139. end;
  140. function IndexChar(Const buf;len:SizeInt;b:char):SizeInt;{$ifdef SYSTEMINLINE}inline;{$endif}
  141. begin
  142. IndexChar:=IndexByte(Buf,Len,byte(B));
  143. end;
  144. function CompareChar(Const buf1,buf2;len:SizeInt):SizeInt;{$ifdef SYSTEMINLINE}inline;{$endif}
  145. begin
  146. CompareChar:=CompareByte(buf1,buf2,len);
  147. end;
  148. { Include generic pascal only routines which are not defined in the processor
  149. specific include file }
  150. {$I generic.inc}
  151. {****************************************************************************
  152. Set Handling
  153. ****************************************************************************}
  154. { Include set support which is processor specific}
  155. {$i set.inc}
  156. { Include generic pascal routines for sets if the processor }
  157. { specific routines are not available. }
  158. {$i genset.inc}
  159. {****************************************************************************
  160. Math Routines
  161. ****************************************************************************}
  162. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  163. begin
  164. Hi := b shr 4
  165. end;
  166. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  167. begin
  168. Lo := b and $0f
  169. end;
  170. Function swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  171. Begin
  172. swap:=(X and $ff) shl 8 + (X shr 8)
  173. End;
  174. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}
  175. Begin
  176. { the extra 'and $ff' in the right term is necessary because the }
  177. { 'X shr 8' is turned into "longint(X) shr 8", so if x < 0 then }
  178. { the sign bits from the upper 16 bits are shifted in rather than }
  179. { zeroes. Another bug for TP/Delphi compatibility... }
  180. swap:=(X and $ff) shl 8 + ((X shr 8) and $ff)
  181. End;
  182. Function swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}
  183. Begin
  184. Swap:=(X and $ffff) shl 16 + (X shr 16)
  185. End;
  186. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}
  187. Begin
  188. Swap:=(X and $ffff) shl 16 + (X shr 16)
  189. End;
  190. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}
  191. Begin
  192. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  193. End;
  194. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}
  195. Begin
  196. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  197. End;
  198. {$ifdef SUPPORT_DOUBLE}
  199. operator := (b:real48) d:double;{$ifdef SYSTEMINLINE}inline;{$endif}
  200. begin
  201. D:=real2double(b);
  202. end;
  203. {$endif SUPPORT_DOUBLE}
  204. {$ifdef SUPPORT_EXTENDED}
  205. operator := (b:real48) e:extended;{$ifdef SYSTEMINLINE}inline;{$endif}
  206. begin
  207. e:=real2double(b);
  208. end;
  209. {$endif SUPPORT_EXTENDED}
  210. {$ifdef FPC_USE_LIBC}
  211. { Include libc versions }
  212. {$i cgenmath.inc}
  213. {$endif FPC_USE_LIBC}
  214. { Include processor specific routines }
  215. {$I math.inc}
  216. { Include generic version }
  217. {$I genmath.inc}
  218. function aligntoptr(p : pointer) : pointer;inline;
  219. begin
  220. {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT}
  221. result:=align(p,sizeof(p));
  222. {$else FPC_REQUIRES_PROPER_ALIGNMENT}
  223. result:=p;
  224. {$endif FPC_REQUIRES_PROPER_ALIGNMENT}
  225. end;
  226. {****************************************************************************
  227. Subroutines for String handling
  228. ****************************************************************************}
  229. { Needs to be before RTTI handling }
  230. {$i sstrings.inc}
  231. { requires sstrings.inc for initval }
  232. {$I int64p.inc}
  233. {$I int64.inc}
  234. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  235. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  236. {$i astrings.inc}
  237. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  238. {$ifdef FPC_HAS_FEATURE_WIDESTRINGS}
  239. {$i wstrings.inc}
  240. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  241. {$i aliases.inc}
  242. {*****************************************************************************
  243. Dynamic Array support
  244. *****************************************************************************}
  245. {$ifdef FPC_HAS_FEATURE_DYNARRAYS}
  246. {$i dynarr.inc}
  247. {$endif FPC_HAS_FEATURE_DYNARRAYS}
  248. {*****************************************************************************
  249. Object Pascal support
  250. *****************************************************************************}
  251. {$ifdef FPC_HAS_FEATURE_CLASSES}
  252. {$i objpas.inc}
  253. {$endif FPC_HAS_FEATURE_CLASSES}
  254. {*****************************************************************************
  255. Variant support
  256. *****************************************************************************}
  257. {$ifdef FPC_HAS_FEATURE_VARIANTS}
  258. {$i variant.inc}
  259. {$endif FPC_HAS_FEATURE_VARIANTS}
  260. {****************************************************************************
  261. Run-Time Type Information (RTTI)
  262. ****************************************************************************}
  263. {$ifdef FPC_HAS_FEATURE_RTTI}
  264. {$i rtti.inc}
  265. {$endif FPC_HAS_FEATURE_VARIANTS}
  266. {----------------------------------------------------------------------
  267. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  268. Pseudo-Random Number Generator.
  269. What is Mersenne Twister?
  270. Mersenne Twister(MT) is a pseudorandom number generator developped by
  271. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  272. 1996-1997. MT has the following merits:
  273. It is designed with consideration on the flaws of various existing
  274. generators.
  275. Far longer period and far higher order of equidistribution than any
  276. other implemented generators. (It is proved that the period is 2^19937-1,
  277. and 623-dimensional equidistribution property is assured.)
  278. Fast generation. (Although it depends on the system, it is reported that
  279. MT is sometimes faster than the standard ANSI-C library in a system
  280. with pipeline and cache memory.)
  281. Efficient use of the memory. (The implemented C-code mt19937.c
  282. consumes only 624 words of working area.)
  283. home page
  284. http://www.math.keio.ac.jp/~matumoto/emt.html
  285. original c source
  286. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  287. Coded by Takuji Nishimura, considering the suggestions by
  288. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  289. This library is free software; you can redistribute it and/or
  290. modify it under the terms of the GNU Library General Public
  291. License as published by the Free Software Foundation; either
  292. version 2 of the License, or (at your option) any later
  293. version.
  294. This library is distributed in the hope that it will be useful,
  295. but WITHOUT ANY WARRANTY; without even the implied warranty of
  296. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  297. See the GNU Library General Public License for more details.
  298. You should have received a copy of the GNU Library General
  299. Public License along with this library; if not, write to the
  300. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  301. 02111-1307 USA
  302. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  303. When you use this, send an email to: [email protected]
  304. with an appropriate reference to your work.
  305. REFERENCE
  306. M. Matsumoto and T. Nishimura,
  307. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  308. Pseudo-Random Number Generator",
  309. ACM Transactions on Modeling and Computer Simulation,
  310. Vol. 8, No. 1, January 1998, pp 3--30.
  311. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  312. http://www.rksolution.cz/delphi/tips.htm
  313. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  314. 2003/10/26: adapted to use the improved intialisation mentioned at
  315. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  316. removed the assembler code
  317. ----------------------------------------------------------------------}
  318. {$R-} {range checking off}
  319. {$Q-} {overflow checking off}
  320. { Period parameter }
  321. Const
  322. MT19937N=624;
  323. Type
  324. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  325. { Period parameters }
  326. const
  327. MT19937M=397;
  328. MT19937MATRIX_A =$9908b0df; // constant vector a
  329. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  330. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  331. { Tempering parameters }
  332. TEMPERING_MASK_B=$9d2c5680;
  333. TEMPERING_MASK_C=$efc60000;
  334. VAR
  335. mt : tMT19937StateArray;
  336. const
  337. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  338. { Initializing the array with a seed }
  339. procedure sgenrand_MT19937(seed: longint);
  340. var
  341. i: longint;
  342. begin
  343. mt[0] := seed;
  344. for i := 1 to MT19937N-1 do
  345. begin
  346. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  347. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  348. { In the previous versions, MSBs of the seed affect }
  349. { only MSBs of the array mt[]. }
  350. { 2002/01/09 modified by Makoto Matsumoto }
  351. end;
  352. mti := MT19937N;
  353. end;
  354. function genrand_MT19937: longint;
  355. const
  356. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  357. var
  358. y: longint;
  359. kk: longint;
  360. begin
  361. if RandSeed<>OldRandSeed then
  362. mti:=MT19937N+1;
  363. if (mti >= MT19937N) { generate MT19937N longints at one time }
  364. then begin
  365. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  366. begin
  367. sgenrand_MT19937(randseed); // default initial seed is used
  368. { hack: randseed is not used more than once in this algorithm. Most }
  369. { user changes are re-initialising reandseed with the value it had }
  370. { at the start -> with the "not", we will detect this change. }
  371. { Detecting other changes is not useful, since the generated }
  372. { numbers will be different anyway. }
  373. randseed := not(randseed);
  374. oldrandseed := randseed;
  375. end;
  376. for kk:=0 to MT19937N-MT19937M-1 do begin
  377. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  378. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  379. end;
  380. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  381. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  382. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  383. end;
  384. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  385. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  386. mti := 0;
  387. end;
  388. y := mt[mti]; inc(mti);
  389. y := y xor (y shr 11);
  390. y := y xor (y shl 7) and TEMPERING_MASK_B;
  391. y := y xor (y shl 15) and TEMPERING_MASK_C;
  392. y := y xor (y shr 18);
  393. Result := y;
  394. end;
  395. function random(l:longint): longint;
  396. begin
  397. { otherwise we can return values = l (JM) }
  398. if (l < 0) then
  399. inc(l);
  400. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  401. end;
  402. function random(l:int64): int64;
  403. begin
  404. { always call random, so the random generator cycles (TP-compatible) (JM) }
  405. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff);
  406. if (l<>0) then
  407. random := random mod l
  408. else
  409. random := 0;
  410. end;
  411. function random: extended;
  412. begin
  413. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  414. end;
  415. {****************************************************************************
  416. Memory Management
  417. ****************************************************************************}
  418. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}
  419. Begin
  420. ptr:=farpointer((sel shl 4)+off);
  421. End;
  422. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  423. Begin
  424. Cseg:=0;
  425. End;
  426. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  427. Begin
  428. Dseg:=0;
  429. End;
  430. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  431. Begin
  432. Sseg:=0;
  433. End;
  434. {*****************************************************************************
  435. Directory support.
  436. *****************************************************************************}
  437. {$if defined(FPC_HAS_FEATURE_FILEIO) and defined(FPC_HAS_FEATURE_ANSISTRINGS)}
  438. Procedure getdir(drivenr:byte;Var dir:ansistring);
  439. { this is needed to also allow ansistrings, the shortstring version is
  440. OS dependent }
  441. var
  442. s : shortstring;
  443. begin
  444. getdir(drivenr,s);
  445. dir:=s;
  446. end;
  447. {$endif}
  448. {$ifopt R+}
  449. {$define RangeCheckWasOn}
  450. {$R-}
  451. {$endif opt R+}
  452. {$ifopt I+}
  453. {$define IOCheckWasOn}
  454. {$I-}
  455. {$endif opt I+}
  456. {$ifopt Q+}
  457. {$define OverflowCheckWasOn}
  458. {$Q-}
  459. {$endif opt Q+}
  460. {*****************************************************************************
  461. Miscellaneous
  462. *****************************************************************************}
  463. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; compilerproc;
  464. begin
  465. HandleErrorFrame(201,get_frame);
  466. end;
  467. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; compilerproc;
  468. begin
  469. HandleErrorFrame(200,get_frame);
  470. end;
  471. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; compilerproc;
  472. begin
  473. HandleErrorFrame(215,get_frame);
  474. end;
  475. procedure fpc_threaderror; [public,alias:'FPC_THREADERROR'];
  476. begin
  477. HandleErrorFrame(6,get_frame);
  478. end;
  479. procedure fpc_iocheck;[public,alias:'FPC_IOCHECK']; compilerproc;
  480. var
  481. l : longint;
  482. begin
  483. if InOutRes<>0 then
  484. begin
  485. l:=InOutRes;
  486. InOutRes:=0;
  487. HandleErrorFrame(l,get_frame);
  488. end;
  489. end;
  490. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  491. Begin
  492. IOResult:=InOutRes;
  493. InOutRes:=0;
  494. End;
  495. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  496. begin
  497. (* ThreadID is stored in a threadvar and made available in interface *)
  498. (* to allow setup of this value during thread initialization. *)
  499. GetThreadID := ThreadID;
  500. end;
  501. function fpc_safecallcheck(res : hresult) : hresult;[public,alias:'FPC_SAFECALLCHECK']; compilerproc;
  502. begin
  503. if res<0 then
  504. begin
  505. if assigned(SafeCallErrorProc) then
  506. SafeCallErrorProc(res,get_frame);
  507. HandleErrorFrame(229,get_frame);
  508. end;
  509. result:=res;
  510. end;
  511. {*****************************************************************************
  512. Stack check code
  513. *****************************************************************************}
  514. {$IFNDEF NO_GENERIC_STACK_CHECK}
  515. {$IFOPT S+}
  516. {$DEFINE STACKCHECK}
  517. {$ENDIF}
  518. {$S-}
  519. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK'];
  520. var
  521. c : Pointer;
  522. begin
  523. { Avoid recursive calls when called from the exit routines }
  524. if StackError then
  525. exit;
  526. c := Sptr - (stack_size + STACK_MARGIN);
  527. if (c <= StackBottom) then
  528. begin
  529. StackError:=true;
  530. HandleError(202);
  531. end;
  532. end;
  533. {$IFDEF STACKCHECK}
  534. {$S+}
  535. {$ENDIF}
  536. {$UNDEF STACKCHECK}
  537. {$ENDIF NO_GENERIC_STACK_CHECK}
  538. {*****************************************************************************
  539. Initialization / Finalization
  540. *****************************************************************************}
  541. const
  542. maxunits=1024; { See also files.pas of the compiler source }
  543. type
  544. TInitFinalRec=record
  545. InitProc,
  546. FinalProc : TProcedure;
  547. end;
  548. TInitFinalTable=record
  549. TableCount,
  550. InitCount : longint;
  551. Procs : array[1..maxunits] of TInitFinalRec;
  552. end;
  553. var
  554. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  555. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  556. var
  557. i : longint;
  558. begin
  559. { call cpu/fpu initialisation routine }
  560. fpc_cpuinit;
  561. with InitFinalTable do
  562. begin
  563. for i:=1 to TableCount do
  564. begin
  565. if assigned(Procs[i].InitProc) then
  566. Procs[i].InitProc();
  567. InitCount:=i;
  568. end;
  569. end;
  570. if assigned(InitProc) then
  571. TProcedure(InitProc)();
  572. end;
  573. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  574. begin
  575. with InitFinalTable do
  576. begin
  577. while (InitCount>0) do
  578. begin
  579. // we've to decrement the cound before calling the final. code
  580. // else a halt in the final. code leads to a endless loop
  581. dec(InitCount);
  582. if assigned(Procs[InitCount+1].FinalProc) then
  583. Procs[InitCount+1].FinalProc();
  584. end;
  585. end;
  586. end;
  587. {*****************************************************************************
  588. Error / Exit / ExitProc
  589. *****************************************************************************}
  590. Procedure system_exit;forward;
  591. {$ifdef FPC_HAS_FEATURE_HEAP}
  592. {$if not (defined(HAS_MEMORYMANAGER) or defined(HAS_MT_MEMORYMANAGER))}
  593. //not needed if independant memory manager
  594. Procedure FinalizeHeap;forward;
  595. {$endif HAS_MEMORYMANAGER}
  596. {$endif FPC_HAS_FEATURE_HEAP}
  597. Procedure InternalExit;
  598. var
  599. current_exit : Procedure;
  600. pstdout : ^Text;
  601. {$if defined(MSWINDOWS) or defined(OS2)}
  602. i : longint;
  603. {$endif}
  604. Begin
  605. {$ifdef SYSTEMDEBUG}
  606. writeln('InternalExit');
  607. {$endif SYSTEMDEBUG}
  608. while exitProc<>nil Do
  609. Begin
  610. InOutRes:=0;
  611. current_exit:=tProcedure(exitProc);
  612. exitProc:=nil;
  613. current_exit();
  614. End;
  615. { Finalize units }
  616. FinalizeUnits;
  617. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  618. { Show runtime error and exit }
  619. pstdout:=@stdout;
  620. If erroraddr<>nil Then
  621. Begin
  622. Writeln(pstdout^,'Runtime error ',Errorcode,' at $',hexstr(erroraddr));
  623. { to get a nice symify }
  624. Writeln(pstdout^,BackTraceStrFunc(Erroraddr));
  625. dump_stack(pstdout^,ErrorBase);
  626. Writeln(pstdout^,'');
  627. End;
  628. { Make sure that all output is written to the redirected file }
  629. Flush(Output);
  630. Flush(ErrOutput);
  631. Flush(pstdout^);
  632. Flush(StdErr);
  633. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  634. {$if defined(MSWINDOWS) or defined(OS2)}
  635. { finally release the heap if possible, especially
  636. important for DLLs }
  637. for i:=0 to argc do
  638. sysfreemem(argv[i]);
  639. sysfreemem(argv);
  640. {$endif}
  641. {$ifdef LINUX}
  642. {sysfreemem already checks for nil}
  643. sysfreemem(calculated_cmdline);
  644. {$endif}
  645. {$ifdef BSD}
  646. sysfreemem(cmdline);
  647. {$endif}
  648. {$ifdef FPC_HAS_FEATURE_HEAP}
  649. {$if not (defined(HAS_MEMORYMANAGER) or defined(HAS_MT_MEMORYMANAGER))}
  650. FinalizeHeap;
  651. {$endif HAS_MEMORYMANAGER}
  652. {$endif FPC_HAS_FEATURE_HEAP}
  653. End;
  654. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  655. begin
  656. InternalExit;
  657. System_exit;
  658. end;
  659. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  660. begin
  661. InternalExit;
  662. end;
  663. Procedure Halt(ErrNum: Byte);
  664. Begin
  665. ExitCode:=Errnum;
  666. Do_Exit;
  667. end;
  668. function SysBackTraceStr (Addr: Pointer): ShortString;
  669. begin
  670. SysBackTraceStr:=' $'+hexstr(addr);
  671. end;
  672. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  673. begin
  674. If pointer(ErrorProc)<>Nil then
  675. ErrorProc(Errno,addr,frame);
  676. errorcode:=word(Errno);
  677. erroraddr:=addr;
  678. errorbase:=frame;
  679. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  680. if ExceptAddrStack <> nil then
  681. raise TObject(nil) at addr,frame;
  682. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  683. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  684. if errorcode <= maxExitCode then
  685. halt(errorcode)
  686. else
  687. halt(255)
  688. {$else FPC_HAS_FEATURE_EXITCODE}
  689. halt;
  690. {$endif FPC_HAS_FEATURE_EXITCODE}
  691. end;
  692. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  693. {
  694. Procedure to handle internal errors, i.e. not user-invoked errors
  695. Internal function should ALWAYS call HandleError instead of RunError.
  696. Can be used for exception handlers to specify the frame
  697. }
  698. begin
  699. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  700. end;
  701. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  702. {
  703. Procedure to handle internal errors, i.e. not user-invoked errors
  704. Internal function should ALWAYS call HandleError instead of RunError.
  705. }
  706. begin
  707. HandleErrorFrame(Errno,get_frame);
  708. end;
  709. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  710. begin
  711. errorcode:=w;
  712. erroraddr:=get_caller_addr(get_frame);
  713. errorbase:=get_caller_frame(get_frame);
  714. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  715. if errorcode <= maxExitCode then
  716. halt(errorcode)
  717. else
  718. halt(255)
  719. {$else FPC_HAS_FEATURE_EXITCODE}
  720. halt;
  721. {$endif FPC_HAS_FEATURE_EXITCODE}
  722. end;
  723. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  724. Begin
  725. RunError (0);
  726. End;
  727. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  728. Begin
  729. Halt(0);
  730. End;
  731. Procedure Error(RunTimeError : TRunTimeError);
  732. begin
  733. RunError(RuntimeErrorExitCodes[RunTimeError]);
  734. end;
  735. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  736. Procedure dump_stack(var f : text;bp : Pointer);
  737. var
  738. i : Longint;
  739. prevbp : Pointer;
  740. is_dev : boolean;
  741. caller_frame,
  742. caller_addr : Pointer;
  743. Begin
  744. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  745. try
  746. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  747. prevbp:=bp-1;
  748. i:=0;
  749. is_dev:=do_isdevice(textrec(f).Handle);
  750. while bp > prevbp Do
  751. Begin
  752. caller_addr := get_caller_addr(bp);
  753. caller_frame := get_caller_frame(bp);
  754. if (caller_addr=nil) then
  755. break;
  756. Writeln(f,BackTraceStrFunc(caller_addr));
  757. if (caller_frame=nil) then
  758. break;
  759. Inc(i);
  760. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  761. break;
  762. prevbp:=bp;
  763. bp:=caller_frame;
  764. End;
  765. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  766. except
  767. { prevent endless dump if an exception occured }
  768. end;
  769. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  770. End;
  771. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  772. {$ifdef FPC_HAS_FEATURE_HEAP}
  773. Type
  774. PExitProcInfo = ^TExitProcInfo;
  775. TExitProcInfo = Record
  776. Next : PExitProcInfo;
  777. SaveExit : Pointer;
  778. Proc : TProcedure;
  779. End;
  780. const
  781. ExitProcList: PExitProcInfo = nil;
  782. Procedure DoExitProc;
  783. var
  784. P : PExitProcInfo;
  785. Proc : TProcedure;
  786. Begin
  787. P:=ExitProcList;
  788. ExitProcList:=P^.Next;
  789. ExitProc:=P^.SaveExit;
  790. Proc:=P^.Proc;
  791. DisPose(P);
  792. Proc();
  793. End;
  794. Procedure AddExitProc(Proc: TProcedure);
  795. var
  796. P : PExitProcInfo;
  797. Begin
  798. New(P);
  799. P^.Next:=ExitProcList;
  800. P^.SaveExit:=ExitProc;
  801. P^.Proc:=Proc;
  802. ExitProcList:=P;
  803. ExitProc:=@DoExitProc;
  804. End;
  805. {$endif FPC_HAS_FEATURE_HEAP}
  806. {$ifdef FPC_HAS_FEATURE_HEAP}
  807. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  808. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  809. // Note: for internal use by skilled programmers only
  810. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  811. var p : ppchar;
  812. i : LongInt;
  813. begin
  814. if High(s)<Low(s) Then Exit(NIL);
  815. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  816. // for cmd
  817. if p=nil then
  818. begin
  819. {$ifdef xunix}
  820. fpseterrno(ESysEnomem);
  821. {$endif}
  822. exit(NIL);
  823. end;
  824. for i:=low(s) to high(s) do
  825. p[i+Reserveentries]:=pchar(s[i]);
  826. p[high(s)+1+Reserveentries]:=nil;
  827. ArrayStringToPPchar:=p;
  828. end;
  829. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  830. {
  831. Create a PPChar to structure of pchars which are the arguments specified
  832. in the string S. Especially usefull for creating an ArgV for Exec-calls
  833. }
  834. begin
  835. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  836. end;
  837. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  838. var
  839. i,nr : longint;
  840. Buf : ^char;
  841. p : ppchar;
  842. begin
  843. buf:=s;
  844. nr:=1;
  845. while (buf^<>#0) do // count nr of args
  846. begin
  847. while (buf^ in [' ',#9,#10]) do // Kill separators.
  848. inc(buf);
  849. inc(nr);
  850. if buf^='"' Then // quotes argument?
  851. begin
  852. inc(buf);
  853. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  854. inc(buf);
  855. if buf^='"' then // skip closing quote.
  856. inc(buf);
  857. end
  858. else
  859. begin // else std
  860. while not (buf^ in [' ',#0,#9,#10]) do
  861. inc(buf);
  862. end;
  863. end;
  864. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  865. StringToPPChar:=p;
  866. if p=nil then
  867. begin
  868. {$ifdef xunix}
  869. fpseterrno(ESysEnomem);
  870. {$endif}
  871. exit;
  872. end;
  873. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  874. buf:=s;
  875. while (buf^<>#0) do
  876. begin
  877. while (buf^ in [' ',#9,#10]) do // Kill separators.
  878. begin
  879. buf^:=#0;
  880. inc(buf);
  881. end;
  882. if buf^='"' Then // quotes argument?
  883. begin
  884. inc(buf);
  885. p^:=buf;
  886. inc(p);
  887. p^:=nil;
  888. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  889. inc(buf);
  890. if buf^='"' then // skip closing quote.
  891. begin
  892. buf^:=#0;
  893. inc(buf);
  894. end;
  895. end
  896. else
  897. begin
  898. p^:=buf;
  899. inc(p);
  900. p^:=nil;
  901. while not (buf^ in [' ',#0,#9,#10]) do
  902. inc(buf);
  903. end;
  904. end;
  905. end;
  906. {$endif FPC_HAS_FEATURE_HEAP}
  907. {*****************************************************************************
  908. Abstract/Assert support.
  909. *****************************************************************************}
  910. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  911. begin
  912. If pointer(AbstractErrorProc)<>nil then
  913. AbstractErrorProc();
  914. HandleErrorFrame(211,get_frame);
  915. end;
  916. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  917. begin
  918. if pointer(AssertErrorProc)<>nil then
  919. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  920. else
  921. HandleErrorFrame(227,get_frame);
  922. end;
  923. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  924. begin
  925. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  926. If msg='' then
  927. write(stderr,'Assertion failed')
  928. else
  929. write(stderr,msg);
  930. Writeln(stderr,' (',FName,', line ',LineNo,').');
  931. Writeln(stderr,'');
  932. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  933. Halt(227);
  934. {$else FPC_HAS_FEATURE_EXITCODE}
  935. halt;
  936. {$endif FPC_HAS_FEATURE_EXITCODE}
  937. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  938. end;
  939. {*****************************************************************************
  940. SetJmp/LongJmp support.
  941. *****************************************************************************}
  942. {$i setjump.inc}
  943. {$ifdef IOCheckWasOn}
  944. {$I+}
  945. {$endif}
  946. {$ifdef RangeCheckWasOn}
  947. {$R+}
  948. {$endif}
  949. {$ifdef OverflowCheckWasOn}
  950. {$Q+}
  951. {$endif}
  952. {*****************************************************************************
  953. Heap
  954. *****************************************************************************}
  955. {$ifdef FPC_HAS_FEATURE_HEAP}
  956. {$i sysheap.inc}
  957. {$i heap.inc}
  958. {$endif FPC_HAS_FEATURE_HEAP}
  959. {*****************************************************************************
  960. Thread support
  961. *****************************************************************************}
  962. {$ifdef FPC_HAS_FEATURE_THREADING}
  963. { Generic threadmanager }
  964. {$i thread.inc}
  965. { Generic threadvar support }
  966. {$i threadvr.inc}
  967. { OS Dependent implementation }
  968. {$i systhrd.inc}
  969. {$endif FPC_HAS_FEATURE_THREADING}
  970. {*****************************************************************************
  971. File Handling
  972. *****************************************************************************}
  973. { OS dependent low level file functions }
  974. {$ifdef FPC_HAS_FEATURE_FILEIO}
  975. {$i sysfile.inc}
  976. {$endif FPC_HAS_FEATURE_FILEIO}
  977. { Text file }
  978. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  979. {$i text.inc}
  980. {$endif FPC_HAS_FEATURE_TEXTIO}
  981. {$ifdef FPC_HAS_FEATURE_FILEIO}
  982. { Untyped file }
  983. {$i file.inc}
  984. { Typed file }
  985. {$i typefile.inc}
  986. {$endif FPC_HAS_FEATURE_FILEIO}
  987. {*****************************************************************************
  988. Directory Handling
  989. *****************************************************************************}
  990. { OS dependent dir functions }
  991. {$i sysdir.inc}
  992. {*****************************************************************************
  993. Resources support
  994. *****************************************************************************}
  995. {$ifndef HAS_RESOURCES}
  996. {$i sysres.inc}
  997. {$endif}
  998. Function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: AnsiString): TResourceHandle;
  999. begin
  1000. Result:=FindResource(ModuleHandle,PChar(ResourceName),PChar(ResourceType));
  1001. end;
  1002. const
  1003. CtrlBreakHandler: TCtrlBreakHandler = nil;
  1004. {$IFNDEF FPC_HAS_SETCTRLBREAKHANDLER}
  1005. (* It is possible to provide platform specific implementation performing *)
  1006. (* special initialization; default implementation just sets the procedural *)
  1007. (* variable to make it available for use from the exception handler. *)
  1008. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  1009. begin
  1010. (* Return either nil or previous handler *)
  1011. SysSetCtrlBreakHandler := CtrlBreakHandler;
  1012. CtrlBreakHandler := Handler;
  1013. end;
  1014. {$ENDIF FPC_HAS_SETCTRLBREAKHANDLER}