system.inc 33 KB

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