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 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. End;
  544. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  545. begin
  546. InternalExit;
  547. System_exit;
  548. end;
  549. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  550. begin
  551. InternalExit;
  552. end;
  553. Procedure Halt(ErrNum: Byte);
  554. Begin
  555. ExitCode:=Errnum;
  556. Do_Exit;
  557. end;
  558. function SysBackTraceStr (Addr: Pointer): ShortString;
  559. begin
  560. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  561. end;
  562. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  563. begin
  564. If pointer(ErrorProc)<>Nil then
  565. ErrorProc(Errno,addr,frame);
  566. errorcode:=word(Errno);
  567. erroraddr:=addr;
  568. errorbase:=frame;
  569. if ExceptAddrStack <> nil then
  570. raise TObject(nil) at addr,frame;
  571. if errorcode <= maxExitCode then
  572. halt(errorcode)
  573. else
  574. halt(255)
  575. end;
  576. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  577. {
  578. Procedure to handle internal errors, i.e. not user-invoked errors
  579. Internal function should ALWAYS call HandleError instead of RunError.
  580. Can be used for exception handlers to specify the frame
  581. }
  582. begin
  583. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  584. end;
  585. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  586. {
  587. Procedure to handle internal errors, i.e. not user-invoked errors
  588. Internal function should ALWAYS call HandleError instead of RunError.
  589. }
  590. begin
  591. HandleErrorFrame(Errno,get_frame);
  592. end;
  593. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  594. begin
  595. errorcode:=w;
  596. erroraddr:=get_caller_addr(get_frame);
  597. errorbase:=get_caller_frame(get_frame);
  598. if errorcode <= maxExitCode then
  599. halt(errorcode)
  600. else
  601. halt(255)
  602. end;
  603. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  604. Begin
  605. RunError (0);
  606. End;
  607. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  608. Begin
  609. Halt(0);
  610. End;
  611. function do_isdevice(handle:thandle):boolean;forward;
  612. Procedure dump_stack(var f : text;bp : Pointer);
  613. var
  614. i : Longint;
  615. prevbp : Pointer;
  616. is_dev : boolean;
  617. caller_frame,
  618. caller_addr : Pointer;
  619. Begin
  620. try
  621. prevbp:=bp-1;
  622. i:=0;
  623. is_dev:=do_isdevice(textrec(f).Handle);
  624. while bp > prevbp Do
  625. Begin
  626. caller_addr := get_caller_addr(bp);
  627. caller_frame := get_caller_frame(bp);
  628. if (caller_addr=nil) or
  629. (caller_frame=nil) then
  630. break;
  631. Writeln(f,BackTraceStrFunc(caller_addr));
  632. Inc(i);
  633. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  634. break;
  635. prevbp:=bp;
  636. bp:=caller_frame;
  637. End;
  638. except
  639. { prevent endless dump if an exception occured }
  640. end;
  641. End;
  642. Type
  643. PExitProcInfo = ^TExitProcInfo;
  644. TExitProcInfo = Record
  645. Next : PExitProcInfo;
  646. SaveExit : Pointer;
  647. Proc : TProcedure;
  648. End;
  649. const
  650. ExitProcList: PExitProcInfo = nil;
  651. Procedure DoExitProc;
  652. var
  653. P : PExitProcInfo;
  654. Proc : TProcedure;
  655. Begin
  656. P:=ExitProcList;
  657. ExitProcList:=P^.Next;
  658. ExitProc:=P^.SaveExit;
  659. Proc:=P^.Proc;
  660. DisPose(P);
  661. Proc();
  662. End;
  663. Procedure AddExitProc(Proc: TProcedure);
  664. var
  665. P : PExitProcInfo;
  666. Begin
  667. New(P);
  668. P^.Next:=ExitProcList;
  669. P^.SaveExit:=ExitProc;
  670. P^.Proc:=Proc;
  671. ExitProcList:=P;
  672. ExitProc:=@DoExitProc;
  673. End;
  674. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  675. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  676. // Note: for internal use by skilled programmers only
  677. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  678. var p : ppchar;
  679. i : LongInt;
  680. begin
  681. if High(s)<Low(s) Then Exit(NIL);
  682. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  683. // for cmd
  684. if p=nil then
  685. begin
  686. {$ifdef xunix}
  687. fpseterrno(ESysEnomem);
  688. {$endif}
  689. exit(NIL);
  690. end;
  691. for i:=low(s) to high(s) do
  692. p[i+Reserveentries]:=pchar(s[i]);
  693. p[high(s)+1+Reserveentries]:=nil;
  694. ArrayStringToPPchar:=p;
  695. end;
  696. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  697. {
  698. Create a PPChar to structure of pchars which are the arguments specified
  699. in the string S. Especially usefull for creating an ArgV for Exec-calls
  700. }
  701. begin
  702. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  703. end;
  704. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  705. var
  706. i,nr : longint;
  707. Buf : ^char;
  708. p : ppchar;
  709. begin
  710. buf:=s;
  711. nr:=1;
  712. while (buf^<>#0) do // count nr of args
  713. begin
  714. while (buf^ in [' ',#9,#10]) do // Kill separators.
  715. inc(buf);
  716. inc(nr);
  717. if buf^='"' Then // quotes argument?
  718. begin
  719. inc(buf);
  720. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  721. inc(buf);
  722. if buf^='"' then // skip closing quote.
  723. inc(buf);
  724. end
  725. else
  726. begin // else std
  727. while not (buf^ in [' ',#0,#9,#10]) do
  728. inc(buf);
  729. end;
  730. end;
  731. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  732. StringToPPChar:=p;
  733. if p=nil then
  734. begin
  735. {$ifdef xunix}
  736. fpseterrno(ESysEnomem);
  737. {$endif}
  738. exit;
  739. end;
  740. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  741. buf:=s;
  742. while (buf^<>#0) do
  743. begin
  744. while (buf^ in [' ',#9,#10]) do // Kill separators.
  745. begin
  746. buf^:=#0;
  747. inc(buf);
  748. end;
  749. if buf^='"' Then // quotes argument?
  750. begin
  751. inc(buf);
  752. p^:=buf;
  753. inc(p);
  754. p^:=nil;
  755. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  756. inc(buf);
  757. if buf^='"' then // skip closing quote.
  758. begin
  759. buf^:=#0;
  760. inc(buf);
  761. end;
  762. end
  763. else
  764. begin
  765. p^:=buf;
  766. inc(p);
  767. p^:=nil;
  768. while not (buf^ in [' ',#0,#9,#10]) do
  769. inc(buf);
  770. end;
  771. end;
  772. end;
  773. {*****************************************************************************
  774. Abstract/Assert support.
  775. *****************************************************************************}
  776. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  777. begin
  778. If pointer(AbstractErrorProc)<>nil then
  779. AbstractErrorProc();
  780. HandleErrorFrame(211,get_frame);
  781. end;
  782. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  783. begin
  784. if pointer(AssertErrorProc)<>nil then
  785. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  786. else
  787. HandleErrorFrame(227,get_frame);
  788. end;
  789. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  790. begin
  791. If msg='' then
  792. write(stderr,'Assertion failed')
  793. else
  794. write(stderr,msg);
  795. Writeln(stderr,' (',FName,', line ',LineNo,').');
  796. Writeln(stderr,'');
  797. Halt(227);
  798. end;
  799. {*****************************************************************************
  800. SetJmp/LongJmp support.
  801. *****************************************************************************}
  802. {$i setjump.inc}
  803. {$ifdef IOCheckWasOn}
  804. {$I+}
  805. {$endif}
  806. {$ifdef RangeCheckWasOn}
  807. {$R+}
  808. {$endif}
  809. {$ifdef OverflowCheckWasOn}
  810. {$Q+}
  811. {$endif}
  812. {*****************************************************************************
  813. OS dependent Helpers/Syscalls
  814. *****************************************************************************}
  815. {$i sysos.inc}
  816. {*****************************************************************************
  817. Heap
  818. *****************************************************************************}
  819. {$i sysheap.inc}
  820. {$i heap.inc}
  821. {*****************************************************************************
  822. Thread support
  823. *****************************************************************************}
  824. { Generic threadmanager }
  825. {$i thread.inc}
  826. { Generic threadvar support }
  827. {$i threadvr.inc}
  828. { OS Dependent implementation }
  829. {$i systhrd.inc}
  830. {*****************************************************************************
  831. File Handling
  832. *****************************************************************************}
  833. { OS dependent low level file functions }
  834. {$i sysfile.inc}
  835. { Text file }
  836. {$i text.inc}
  837. { Untyped file }
  838. {$i file.inc}
  839. { Typed file }
  840. {$i typefile.inc}
  841. {*****************************************************************************
  842. Directory Handling
  843. *****************************************************************************}
  844. { OS dependent dir functions }
  845. {$i sysdir.inc}
  846. {*****************************************************************************
  847. Resources support
  848. *****************************************************************************}
  849. {$ifndef HAS_RESOURCES}
  850. {$i sysres.inc}
  851. {$endif}
  852. Function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: AnsiString): TResourceHandle;
  853. begin
  854. Result:=FindResource(ModuleHandle,PChar(ResourceName),PChar(ResourceType));
  855. end;