system.inc 29 KB

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