system.inc 28 KB

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