system.inc 33 KB

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