system.inc 34 KB

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