system.inc 35 KB

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