system.inc 32 KB

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