system.inc 28 KB

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