system.inc 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. {*****************************************************************************
  450. Stack check code
  451. *****************************************************************************}
  452. {$IFNDEF NO_GENERIC_STACK_CHECK}
  453. {$IFOPT S+}
  454. {$DEFINE STACKCHECK}
  455. {$ENDIF}
  456. {$S-}
  457. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK'];
  458. var
  459. c : Pointer;
  460. begin
  461. { Avoid recursive calls when called from the exit routines }
  462. if StackError then
  463. exit;
  464. c := Sptr - (stack_size + STACK_MARGIN);
  465. if (c <= StackBottom) then
  466. begin
  467. StackError:=true;
  468. HandleError(202);
  469. end;
  470. end;
  471. {$IFDEF STACKCHECK}
  472. {$S+}
  473. {$ENDIF}
  474. {$UNDEF STACKCHECK}
  475. {$ENDIF NO_GENERIC_STACK_CHECK}
  476. {*****************************************************************************
  477. Initialization / Finalization
  478. *****************************************************************************}
  479. const
  480. maxunits=1024; { See also files.pas of the compiler source }
  481. type
  482. TInitFinalRec=record
  483. InitProc,
  484. FinalProc : TProcedure;
  485. end;
  486. TInitFinalTable=record
  487. TableCount,
  488. InitCount : longint;
  489. Procs : array[1..maxunits] of TInitFinalRec;
  490. end;
  491. var
  492. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  493. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  494. var
  495. i : longint;
  496. begin
  497. { call cpu/fpu initialisation routine }
  498. fpc_cpuinit;
  499. with InitFinalTable do
  500. begin
  501. for i:=1 to TableCount do
  502. begin
  503. if assigned(Procs[i].InitProc) then
  504. Procs[i].InitProc();
  505. InitCount:=i;
  506. end;
  507. end;
  508. if assigned(InitProc) then
  509. TProcedure(InitProc)();
  510. end;
  511. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  512. begin
  513. with InitFinalTable do
  514. begin
  515. while (InitCount>0) do
  516. begin
  517. // we've to decrement the cound before calling the final. code
  518. // else a halt in the final. code leads to a endless loop
  519. dec(InitCount);
  520. if assigned(Procs[InitCount+1].FinalProc) then
  521. Procs[InitCount+1].FinalProc();
  522. end;
  523. end;
  524. end;
  525. {*****************************************************************************
  526. Error / Exit / ExitProc
  527. *****************************************************************************}
  528. Procedure system_exit;forward;
  529. Procedure InternalExit;
  530. var
  531. current_exit : Procedure;
  532. Begin
  533. while exitProc<>nil Do
  534. Begin
  535. InOutRes:=0;
  536. current_exit:=tProcedure(exitProc);
  537. exitProc:=nil;
  538. current_exit();
  539. End;
  540. { Finalize units }
  541. FinalizeUnits;
  542. { Show runtime error and exit }
  543. If erroraddr<>nil Then
  544. Begin
  545. Writeln(stdout,'Runtime error ',Errorcode,' at $',hexstr(PtrInt(Erroraddr),sizeof(PtrInt)*2));
  546. { to get a nice symify }
  547. Writeln(stdout,BackTraceStrFunc(Erroraddr));
  548. dump_stack(stdout,ErrorBase);
  549. Writeln(stdout,'');
  550. End;
  551. { Make sure that all output is written to the redirected file }
  552. Flush(Output);
  553. Flush(ErrOutput);
  554. Flush(StdOut);
  555. Flush(StdErr);
  556. End;
  557. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  558. begin
  559. InternalExit;
  560. System_exit;
  561. end;
  562. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  563. begin
  564. InternalExit;
  565. end;
  566. Procedure Halt(ErrNum: Byte);
  567. Begin
  568. ExitCode:=Errnum;
  569. Do_Exit;
  570. end;
  571. function SysBackTraceStr (Addr: Pointer): ShortString;
  572. begin
  573. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  574. end;
  575. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  576. begin
  577. If pointer(ErrorProc)<>Nil then
  578. ErrorProc(Errno,addr,frame);
  579. errorcode:=word(Errno);
  580. erroraddr:=addr;
  581. errorbase:=frame;
  582. if ExceptAddrStack <> nil then
  583. raise TObject(nil) at addr,frame;
  584. if errorcode <= maxExitCode then
  585. halt(errorcode)
  586. else
  587. halt(255)
  588. end;
  589. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  590. {
  591. Procedure to handle internal errors, i.e. not user-invoked errors
  592. Internal function should ALWAYS call HandleError instead of RunError.
  593. Can be used for exception handlers to specify the frame
  594. }
  595. begin
  596. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  597. end;
  598. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  599. {
  600. Procedure to handle internal errors, i.e. not user-invoked errors
  601. Internal function should ALWAYS call HandleError instead of RunError.
  602. }
  603. begin
  604. HandleErrorFrame(Errno,get_frame);
  605. end;
  606. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  607. begin
  608. errorcode:=w;
  609. erroraddr:=get_caller_addr(get_frame);
  610. errorbase:=get_caller_frame(get_frame);
  611. if errorcode <= maxExitCode then
  612. halt(errorcode)
  613. else
  614. halt(255)
  615. end;
  616. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  617. Begin
  618. RunError (0);
  619. End;
  620. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  621. Begin
  622. Halt(0);
  623. End;
  624. function do_isdevice(handle:thandle):boolean;forward;
  625. Procedure dump_stack(var f : text;bp : Pointer);
  626. var
  627. i : Longint;
  628. prevbp : Pointer;
  629. is_dev : boolean;
  630. caller_frame,
  631. caller_addr : Pointer;
  632. Begin
  633. try
  634. prevbp:=bp-1;
  635. i:=0;
  636. is_dev:=do_isdevice(textrec(f).Handle);
  637. while bp > prevbp Do
  638. Begin
  639. caller_addr := get_caller_addr(bp);
  640. caller_frame := get_caller_frame(bp);
  641. if (caller_addr=nil) then
  642. break;
  643. Writeln(f,BackTraceStrFunc(caller_addr));
  644. if (caller_frame=nil) then
  645. break;
  646. Inc(i);
  647. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  648. break;
  649. prevbp:=bp;
  650. bp:=caller_frame;
  651. End;
  652. except
  653. { prevent endless dump if an exception occured }
  654. end;
  655. End;
  656. Type
  657. PExitProcInfo = ^TExitProcInfo;
  658. TExitProcInfo = Record
  659. Next : PExitProcInfo;
  660. SaveExit : Pointer;
  661. Proc : TProcedure;
  662. End;
  663. const
  664. ExitProcList: PExitProcInfo = nil;
  665. Procedure DoExitProc;
  666. var
  667. P : PExitProcInfo;
  668. Proc : TProcedure;
  669. Begin
  670. P:=ExitProcList;
  671. ExitProcList:=P^.Next;
  672. ExitProc:=P^.SaveExit;
  673. Proc:=P^.Proc;
  674. DisPose(P);
  675. Proc();
  676. End;
  677. Procedure AddExitProc(Proc: TProcedure);
  678. var
  679. P : PExitProcInfo;
  680. Begin
  681. New(P);
  682. P^.Next:=ExitProcList;
  683. P^.SaveExit:=ExitProc;
  684. P^.Proc:=Proc;
  685. ExitProcList:=P;
  686. ExitProc:=@DoExitProc;
  687. End;
  688. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  689. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  690. // Note: for internal use by skilled programmers only
  691. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  692. var p : ppchar;
  693. i : LongInt;
  694. begin
  695. if High(s)<Low(s) Then Exit(NIL);
  696. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  697. // for cmd
  698. if p=nil then
  699. begin
  700. {$ifdef xunix}
  701. fpseterrno(ESysEnomem);
  702. {$endif}
  703. exit(NIL);
  704. end;
  705. for i:=low(s) to high(s) do
  706. p[i+Reserveentries]:=pchar(s[i]);
  707. p[high(s)+1+Reserveentries]:=nil;
  708. ArrayStringToPPchar:=p;
  709. end;
  710. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  711. {
  712. Create a PPChar to structure of pchars which are the arguments specified
  713. in the string S. Especially usefull for creating an ArgV for Exec-calls
  714. }
  715. begin
  716. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  717. end;
  718. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  719. var
  720. i,nr : longint;
  721. Buf : ^char;
  722. p : ppchar;
  723. begin
  724. buf:=s;
  725. nr:=1;
  726. while (buf^<>#0) do // count nr of args
  727. begin
  728. while (buf^ in [' ',#9,#10]) do // Kill separators.
  729. inc(buf);
  730. inc(nr);
  731. if buf^='"' Then // quotes argument?
  732. begin
  733. inc(buf);
  734. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  735. inc(buf);
  736. if buf^='"' then // skip closing quote.
  737. inc(buf);
  738. end
  739. else
  740. begin // else std
  741. while not (buf^ in [' ',#0,#9,#10]) do
  742. inc(buf);
  743. end;
  744. end;
  745. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  746. StringToPPChar:=p;
  747. if p=nil then
  748. begin
  749. {$ifdef xunix}
  750. fpseterrno(ESysEnomem);
  751. {$endif}
  752. exit;
  753. end;
  754. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  755. buf:=s;
  756. while (buf^<>#0) do
  757. begin
  758. while (buf^ in [' ',#9,#10]) do // Kill separators.
  759. begin
  760. buf^:=#0;
  761. inc(buf);
  762. end;
  763. if buf^='"' Then // quotes argument?
  764. begin
  765. inc(buf);
  766. p^:=buf;
  767. inc(p);
  768. p^:=nil;
  769. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  770. inc(buf);
  771. if buf^='"' then // skip closing quote.
  772. begin
  773. buf^:=#0;
  774. inc(buf);
  775. end;
  776. end
  777. else
  778. begin
  779. p^:=buf;
  780. inc(p);
  781. p^:=nil;
  782. while not (buf^ in [' ',#0,#9,#10]) do
  783. inc(buf);
  784. end;
  785. end;
  786. end;
  787. {*****************************************************************************
  788. Abstract/Assert support.
  789. *****************************************************************************}
  790. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  791. begin
  792. If pointer(AbstractErrorProc)<>nil then
  793. AbstractErrorProc();
  794. HandleErrorFrame(211,get_frame);
  795. end;
  796. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  797. begin
  798. if pointer(AssertErrorProc)<>nil then
  799. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  800. else
  801. HandleErrorFrame(227,get_frame);
  802. end;
  803. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  804. begin
  805. If msg='' then
  806. write(stderr,'Assertion failed')
  807. else
  808. write(stderr,msg);
  809. Writeln(stderr,' (',FName,', line ',LineNo,').');
  810. Writeln(stderr,'');
  811. Halt(227);
  812. end;
  813. {*****************************************************************************
  814. SetJmp/LongJmp support.
  815. *****************************************************************************}
  816. {$i setjump.inc}
  817. {$ifdef IOCheckWasOn}
  818. {$I+}
  819. {$endif}
  820. {$ifdef RangeCheckWasOn}
  821. {$R+}
  822. {$endif}
  823. {$ifdef OverflowCheckWasOn}
  824. {$Q+}
  825. {$endif}
  826. {*****************************************************************************
  827. OS dependent Helpers/Syscalls
  828. *****************************************************************************}
  829. {$i sysos.inc}
  830. {*****************************************************************************
  831. Heap
  832. *****************************************************************************}
  833. {$i sysheap.inc}
  834. {$i heap.inc}
  835. {*****************************************************************************
  836. Thread support
  837. *****************************************************************************}
  838. { Generic threadmanager }
  839. {$i thread.inc}
  840. { Generic threadvar support }
  841. {$i threadvr.inc}
  842. { OS Dependent implementation }
  843. {$i systhrd.inc}
  844. {*****************************************************************************
  845. File Handling
  846. *****************************************************************************}
  847. { OS dependent low level file functions }
  848. {$i sysfile.inc}
  849. { Text file }
  850. {$i text.inc}
  851. { Untyped file }
  852. {$i file.inc}
  853. { Typed file }
  854. {$i typefile.inc}
  855. {*****************************************************************************
  856. Directory Handling
  857. *****************************************************************************}
  858. { OS dependent dir functions }
  859. {$i sysdir.inc}
  860. {*****************************************************************************
  861. Resources support
  862. *****************************************************************************}
  863. {$ifndef HAS_RESOURCES}
  864. {$i sysres.inc}
  865. {$endif}
  866. Function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: AnsiString): TResourceHandle;
  867. begin
  868. Result:=FindResource(ModuleHandle,PChar(ResourceName),PChar(ResourceType));
  869. end;