system.inc 28 KB

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