system.inc 28 KB

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