system.inc 29 KB

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