system.inc 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. {
  2. $Id$
  3. This file is part of the Free Pascal Run time library.
  4. Copyright (c) 1999-2000 by the Free Pascal development team
  5. See the file COPYING.FPC, included in this distribution,
  6. For details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {****************************************************************************
  12. Local types
  13. ****************************************************************************}
  14. {
  15. TextRec and FileRec are put in a separate file to make it available to other
  16. units without putting it explicitly in systemh.
  17. This way we keep TP compatibility, and the TextRec definition is available
  18. for everyone who needs it.
  19. }
  20. {$i filerec.inc}
  21. {$i textrec.inc}
  22. Procedure HandleError (Errno : Longint); forward;
  23. Procedure HandleErrorFrame (Errno : longint;frame : Pointer); forward;
  24. type
  25. FileFunc = Procedure(var t : TextRec);
  26. const
  27. STACK_MARGIN = 16384; { Stack size margin for stack checking }
  28. { Random / Randomize constants }
  29. OldRandSeed : Cardinal = 0;
  30. { For Error Handling.}
  31. ErrorBase : Pointer = nil;
  32. { Used by the ansistrings and maybe also other things in the future }
  33. var
  34. emptychar : char;public name 'FPC_EMPTYCHAR';
  35. initialstklen : longint;external name '__stklen';
  36. {****************************************************************************
  37. Routines which have compiler magic
  38. ****************************************************************************}
  39. {$ifndef INTERNCONSTINTF}
  40. Function lo(i : Integer) : byte; [INTERNPROC: fpc_in_lo_Word];
  41. Function lo(w : Word) : byte; [INTERNPROC: fpc_in_lo_Word];
  42. Function lo(l : Longint) : Word; [INTERNPROC: fpc_in_lo_long];
  43. Function lo(l : DWord) : Word; [INTERNPROC: fpc_in_lo_long];
  44. Function hi(i : Integer) : byte; [INTERNPROC: fpc_in_hi_Word];
  45. Function hi(w : Word) : byte; [INTERNPROC: fpc_in_hi_Word];
  46. Function hi(l : Longint) : Word; [INTERNPROC: fpc_in_hi_long];
  47. Function hi(l : DWord) : Word; [INTERNPROC: fpc_in_hi_long];
  48. Function lo(q : QWord) : DWord; [INTERNPROC: fpc_in_lo_qword];
  49. Function lo(i : Int64) : DWord; [INTERNPROC: fpc_in_lo_qword];
  50. Function hi(q : QWord) : DWord; [INTERNPROC: fpc_in_hi_qword];
  51. Function hi(i : Int64) : DWord; [INTERNPROC: fpc_in_hi_qword];
  52. Function chr(b : byte) : Char; [INTERNPROC: fpc_in_chr_byte];
  53. {$ifndef INTERNLENGTH}
  54. Function Length(s : string) : byte; [INTERNPROC: fpc_in_Length_string];
  55. Function Length(c : char) : byte; [INTERNPROC: fpc_in_Length_string];
  56. {$endif INTERNLENGTH}
  57. Procedure Reset(var f : TypedFile); [INTERNPROC: fpc_in_Reset_TypedFile];
  58. Procedure Rewrite(var f : TypedFile); [INTERNPROC: fpc_in_Rewrite_TypedFile];
  59. {$endif INTERNCONSTINTF}
  60. {****************************************************************************
  61. Include processor specific routines
  62. ****************************************************************************}
  63. {$ifdef FPC_USE_LIBC}
  64. { prefer libc implementations over our own, as they're most likely faster }
  65. {$i cgeneric.inc}
  66. { is now declared as external reference to another routine in the interface }
  67. {$i cgenstr.inc}
  68. {$endif FPC_USE_LIBC}
  69. {$ifdef cpui386}
  70. {$ifdef SYSPROCDEFINED}
  71. {$Error Can't determine processor type !}
  72. {$endif}
  73. {$i i386.inc} { Case dependent, don't change }
  74. {$endif cpui386}
  75. {$ifdef cpum68k}
  76. {$ifdef SYSPROCDEFINED}
  77. {$Error Can't determine processor type !}
  78. {$endif}
  79. {$i m68k.inc} { Case dependent, don't change }
  80. {$define SYSPROCDEFINED}
  81. {$endif cpum68k}
  82. {$ifdef cpux86_64}
  83. {$ifdef SYSPROCDEFINED}
  84. {$Error Can't determine processor type !}
  85. {$endif}
  86. {$i x86_64.inc} { Case dependent, don't change }
  87. {$define SYSPROCDEFINED}
  88. {$endif cpux86_64}
  89. {$ifdef cpupowerpc}
  90. {$ifdef SYSPROCDEFINED}
  91. {$Error Can't determine processor type !}
  92. {$endif}
  93. {$i powerpc.inc} { Case dependent, don't change }
  94. {$define SYSPROCDEFINED}
  95. {$endif cpupowerpc}
  96. {$ifdef cpualpha}
  97. {$ifdef SYSPROCDEFINED}
  98. {$Error Can't determine processor type !}
  99. {$endif}
  100. {$i alpha.inc} { Case dependent, don't change }
  101. {$define SYSPROCDEFINED}
  102. {$endif cpualpha}
  103. {$ifdef cpuiA64}
  104. {$ifdef SYSPROCDEFINED}
  105. {$Error Can't determine processor type !}
  106. {$endif}
  107. {$i ia64.inc} { Case dependent, don't change }
  108. {$define SYSPROCDEFINED}
  109. {$endif cpuiA64}
  110. {$ifdef cpusparc}
  111. {$ifdef SYSPROCDEFINED}
  112. {$Error Can't determine processor type !}
  113. {$endif}
  114. {$i sparc.inc} { Case dependent, don't change }
  115. {$define SYSPROCDEFINED}
  116. {$endif cpusparc}
  117. {$ifdef cpuarm}
  118. {$ifdef SYSPROCDEFINED}
  119. {$Error Can't determine processor type !}
  120. {$endif}
  121. {$i arm.inc} { Case dependent, don't change }
  122. {$define SYSPROCDEFINED}
  123. {$endif cpuarm}
  124. procedure fillchar(var x;count : SizeInt;value : boolean);{$ifdef SYSTEMINLINE}inline;{$endif}
  125. begin
  126. fillchar(x,count,byte(value));
  127. end;
  128. procedure fillchar(var x;count : SizeInt;value : char);{$ifdef SYSTEMINLINE}inline;{$endif}
  129. begin
  130. fillchar(x,count,byte(value));
  131. end;
  132. { Include generic pascal only routines which are not defined in the processor
  133. specific include file }
  134. {$I generic.inc}
  135. {****************************************************************************
  136. Set Handling
  137. ****************************************************************************}
  138. { Include set support which is processor specific}
  139. {$i set.inc}
  140. { Include generic pascal routines for sets if the processor }
  141. { specific routines are not available. }
  142. {$i genset.inc}
  143. {****************************************************************************
  144. Math Routines
  145. ****************************************************************************}
  146. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  147. begin
  148. Hi := b shr 4
  149. end;
  150. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  151. begin
  152. Lo := b and $0f
  153. end;
  154. Function swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  155. Begin
  156. swap:=(X and $ff) shl 8 + (X shr 8)
  157. End;
  158. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_word];{$endif}
  159. Begin
  160. swap:=(X and $ff) shl 8 + (X shr 8)
  161. End;
  162. Function swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  163. Begin
  164. Swap:=(X and $ffff) shl 16 + (X shr 16)
  165. End;
  166. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_long];{$endif}
  167. Begin
  168. Swap:=(X and $ffff) shl 16 + (X shr 16)
  169. End;
  170. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  171. Begin
  172. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  173. End;
  174. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_swap_qword];{$endif}
  175. Begin
  176. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  177. End;
  178. {$ifdef SUPPORT_DOUBLE}
  179. operator := (b:real48) d:double;
  180. begin
  181. D:=real2double(b);
  182. end;
  183. {$endif SUPPORT_DOUBLE}
  184. {$ifdef SUPPORT_EXTENDED}
  185. operator := (b:real48) e:extended;
  186. begin
  187. e:=real2double(b);
  188. end;
  189. {$endif SUPPORT_EXTENDED}
  190. {$ifdef FPC_USE_LIBC}
  191. { Include libc versions }
  192. {$i cgenmath.inc}
  193. {$endif FPC_USE_LIBC}
  194. { Include processor specific routines }
  195. {$I math.inc}
  196. { Include generic version }
  197. {$I genmath.inc}
  198. operator ** (bas,expo : real) e: real;
  199. begin
  200. e:=power(bas,expo);
  201. end;
  202. operator ** (bas,expo : int64) i: int64;
  203. begin
  204. i:=power(bas,expo);
  205. end;
  206. {****************************************************************************
  207. Subroutines for String handling
  208. ****************************************************************************}
  209. { Needs to be before RTTI handling }
  210. {$i sstrings.inc}
  211. { requires sstrings.inc for initval }
  212. {$I int64p.inc}
  213. {$I int64.inc}
  214. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  215. {$i astrings.inc}
  216. {$ifdef HASWIDESTRING}
  217. {$i wstrings.inc}
  218. {$endif HASWIDESTRING}
  219. {$i aliases.inc}
  220. {*****************************************************************************
  221. Dynamic Array support
  222. *****************************************************************************}
  223. {$i dynarr.inc}
  224. {*****************************************************************************
  225. Object Pascal support
  226. *****************************************************************************}
  227. {$i objpas.inc}
  228. {*****************************************************************************
  229. Variant support
  230. *****************************************************************************}
  231. {$ifdef HASVARIANT}
  232. {$i variant.inc}
  233. {$endif HASVARIANT}
  234. {****************************************************************************
  235. Run-Time Type Information (RTTI)
  236. ****************************************************************************}
  237. {$i rtti.inc}
  238. {----------------------------------------------------------------------
  239. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  240. Pseudo-Random Number Generator.
  241. What is Mersenne Twister?
  242. Mersenne Twister(MT) is a pseudorandom number generator developped by
  243. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  244. 1996-1997. MT has the following merits:
  245. It is designed with consideration on the flaws of various existing
  246. generators.
  247. Far longer period and far higher order of equidistribution than any
  248. other implemented generators. (It is proved that the period is 2^19937-1,
  249. and 623-dimensional equidistribution property is assured.)
  250. Fast generation. (Although it depends on the system, it is reported that
  251. MT is sometimes faster than the standard ANSI-C library in a system
  252. with pipeline and cache memory.)
  253. Efficient use of the memory. (The implemented C-code mt19937.c
  254. consumes only 624 words of working area.)
  255. home page
  256. http://www.math.keio.ac.jp/~matumoto/emt.html
  257. original c source
  258. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  259. Coded by Takuji Nishimura, considering the suggestions by
  260. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  261. This library is free software; you can redistribute it and/or
  262. modify it under the terms of the GNU Library General Public
  263. License as published by the Free Software Foundation; either
  264. version 2 of the License, or (at your option) any later
  265. version.
  266. This library is distributed in the hope that it will be useful,
  267. but WITHOUT ANY WARRANTY; without even the implied warranty of
  268. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  269. See the GNU Library General Public License for more details.
  270. You should have received a copy of the GNU Library General
  271. Public License along with this library; if not, write to the
  272. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  273. 02111-1307 USA
  274. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  275. When you use this, send an email to: [email protected]
  276. with an appropriate reference to your work.
  277. REFERENCE
  278. M. Matsumoto and T. Nishimura,
  279. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  280. Pseudo-Random Number Generator",
  281. ACM Transactions on Modeling and Computer Simulation,
  282. Vol. 8, No. 1, January 1998, pp 3--30.
  283. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  284. http://www.rksolution.cz/delphi/tips.htm
  285. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  286. 2003/10/26: adapted to use the improved intialisation mentioned at
  287. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  288. removed the assembler code
  289. ----------------------------------------------------------------------}
  290. {$R-} {range checking off}
  291. {$Q-} {overflow checking off}
  292. { Period parameter }
  293. Const
  294. MT19937N=624;
  295. Type
  296. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  297. { Period parameters }
  298. const
  299. MT19937M=397;
  300. MT19937MATRIX_A =$9908b0df; // constant vector a
  301. MT19937UPPER_MASK=$80000000; // most significant w-r bits
  302. MT19937LOWER_MASK=$7fffffff; // least significant r bits
  303. { Tempering parameters }
  304. TEMPERING_MASK_B=$9d2c5680;
  305. TEMPERING_MASK_C=$efc60000;
  306. VAR
  307. mt : tMT19937StateArray;
  308. const
  309. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  310. { Initializing the array with a seed }
  311. procedure sgenrand_MT19937(seed: longint);
  312. var
  313. i: longint;
  314. begin
  315. mt[0] := seed;
  316. for i := 1 to MT19937N-1 do
  317. begin
  318. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  319. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  320. { In the previous versions, MSBs of the seed affect }
  321. { only MSBs of the array mt[]. }
  322. { 2002/01/09 modified by Makoto Matsumoto }
  323. end;
  324. mti := MT19937N;
  325. end;
  326. function genrand_MT19937: longint;
  327. const
  328. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  329. var
  330. y: longint;
  331. kk: longint;
  332. begin
  333. if (mti >= MT19937N) or
  334. (randseed <> oldrandseed) { generate MT19937N longints at one time }
  335. then begin
  336. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  337. begin
  338. sgenrand_MT19937(randseed); // default initial seed is used
  339. { hack: randseed is not used more than once in this algorithm. Most }
  340. { user changes are re-initialising reandseed with the value it had }
  341. { at the start -> with the "not", we will detect this change. }
  342. { Detecting other changes is not useful, since the generated }
  343. { numbers will be different anyway. }
  344. randseed := not(randseed);
  345. oldrandseed := randseed;
  346. end;
  347. for kk:=0 to MT19937N-MT19937M-1 do begin
  348. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  349. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  350. end;
  351. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  352. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  353. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  354. end;
  355. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  356. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  357. mti := 0;
  358. end;
  359. y := mt[mti]; inc(mti);
  360. y := y xor (y shr 11);
  361. y := y xor (y shl 7) and TEMPERING_MASK_B;
  362. y := y xor (y shl 15) and TEMPERING_MASK_C;
  363. y := y xor (y shr 18);
  364. Result := y;
  365. end;
  366. function random(l:longint): longint;
  367. begin
  368. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  369. end;
  370. function random(l:int64): int64;
  371. begin
  372. {$ifndef VER1_0}
  373. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff) mod l;
  374. {$endif VER1_0}
  375. end;
  376. function random: extended;
  377. begin
  378. random := cardinal(genrand_MT19937) * (1.0/(int64(1) shl 32));
  379. end;
  380. {****************************************************************************
  381. Memory Management
  382. ****************************************************************************}
  383. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}{$ifndef INTERNCONSTINTF}[internconst:fpc_in_const_ptr];{$endif}
  384. Begin
  385. ptr:=farpointer((sel shl 4)+off);
  386. End;
  387. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  388. Begin
  389. Cseg:=0;
  390. End;
  391. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  392. Begin
  393. Dseg:=0;
  394. End;
  395. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  396. Begin
  397. Sseg:=0;
  398. End;
  399. {*****************************************************************************
  400. Directory support.
  401. *****************************************************************************}
  402. Procedure getdir(drivenr:byte;Var dir:ansistring);
  403. { this is needed to also allow ansistrings, the shortstring version is
  404. OS dependent }
  405. var
  406. s : shortstring;
  407. begin
  408. getdir(drivenr,s);
  409. dir:=s;
  410. end;
  411. {$ifopt R+}
  412. {$define RangeCheckWasOn}
  413. {$R-}
  414. {$endif opt R+}
  415. {$ifopt I+}
  416. {$define IOCheckWasOn}
  417. {$I-}
  418. {$endif opt I+}
  419. {$ifopt Q+}
  420. {$define OverflowCheckWasOn}
  421. {$Q-}
  422. {$endif opt Q+}
  423. {*****************************************************************************
  424. Miscellaneous
  425. *****************************************************************************}
  426. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; {$ifdef hascompilerproc} compilerproc; {$endif}
  427. begin
  428. HandleErrorFrame(201,get_frame);
  429. end;
  430. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; {$ifdef hascompilerproc} compilerproc; {$endif}
  431. begin
  432. HandleErrorFrame(200,get_frame);
  433. end;
  434. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; {$ifdef hascompilerproc} compilerproc; {$endif}
  435. begin
  436. HandleErrorFrame(215,get_frame);
  437. end;
  438. procedure fpc_iocheck;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_IOCHECK']; {$ifdef hascompilerproc} compilerproc; {$endif}
  439. var
  440. l : longint;
  441. begin
  442. if InOutRes<>0 then
  443. begin
  444. l:=InOutRes;
  445. InOutRes:=0;
  446. HandleErrorFrame(l,get_frame);
  447. end;
  448. end;
  449. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  450. Begin
  451. IOResult:=InOutRes;
  452. InOutRes:=0;
  453. End;
  454. Function GetThreadID:SizeUInt;{$ifdef SYSTEMINLINE}inline;{$endif}
  455. begin
  456. (* ThreadID is stored in a threadvar and made available in interface *)
  457. (* to allow setup of this value during thread initialization. *)
  458. GetThreadID := ThreadID;
  459. end;
  460. {*****************************************************************************
  461. Stack check code
  462. *****************************************************************************}
  463. {$IFNDEF NO_GENERIC_STACK_CHECK}
  464. {$IFOPT S+}
  465. {$DEFINE STACKCHECK}
  466. {$ENDIF}
  467. {$S-}
  468. procedure fpc_stackcheck(stack_size:Cardinal);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[public,alias:'FPC_STACKCHECK'];
  469. var
  470. c : Pointer;
  471. begin
  472. { Avoid recursive calls when called from the exit routines }
  473. if StackError then
  474. exit;
  475. c := Sptr - (stack_size + STACK_MARGIN);
  476. if (c <= StackBottom) then
  477. begin
  478. StackError:=true;
  479. HandleError(202);
  480. end;
  481. end;
  482. {$IFDEF STACKCHECK}
  483. {$S+}
  484. {$ENDIF}
  485. {$UNDEF STACKCHECK}
  486. {$ENDIF NO_GENERIC_STACK_CHECK}
  487. {*****************************************************************************
  488. Initialization / Finalization
  489. *****************************************************************************}
  490. const
  491. maxunits=1024; { See also files.pas of the compiler source }
  492. type
  493. TInitFinalRec=record
  494. InitProc,
  495. FinalProc : TProcedure;
  496. end;
  497. TInitFinalTable=record
  498. TableCount,
  499. InitCount : longint;
  500. Procs : array[1..maxunits] of TInitFinalRec;
  501. end;
  502. var
  503. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  504. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; {$ifdef hascompilerproc} compilerproc; {$endif}
  505. var
  506. i : longint;
  507. begin
  508. { call cpu/fpu initialisation routine }
  509. fpc_cpuinit;
  510. with InitFinalTable do
  511. begin
  512. for i:=1 to TableCount do
  513. begin
  514. if assigned(Procs[i].InitProc) then
  515. Procs[i].InitProc();
  516. InitCount:=i;
  517. end;
  518. end;
  519. end;
  520. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  521. begin
  522. with InitFinalTable do
  523. begin
  524. while (InitCount>0) do
  525. begin
  526. // we've to decrement the cound before calling the final. code
  527. // else a halt in the final. code leads to a endless loop
  528. dec(InitCount);
  529. if assigned(Procs[InitCount+1].FinalProc) then
  530. Procs[InitCount+1].FinalProc();
  531. end;
  532. end;
  533. end;
  534. {*****************************************************************************
  535. Error / Exit / ExitProc
  536. *****************************************************************************}
  537. Procedure system_exit;forward;
  538. Procedure InternalExit;
  539. var
  540. current_exit : Procedure;
  541. Begin
  542. while exitProc<>nil Do
  543. Begin
  544. InOutRes:=0;
  545. current_exit:=tProcedure(exitProc);
  546. exitProc:=nil;
  547. current_exit();
  548. End;
  549. { Finalize units }
  550. FinalizeUnits;
  551. { Show runtime error and exit }
  552. If erroraddr<>nil Then
  553. Begin
  554. Writeln(stdout,'Runtime error ',Errorcode,' at $',hexstr(PtrInt(Erroraddr),sizeof(PtrInt)*2));
  555. { to get a nice symify }
  556. Writeln(stdout,BackTraceStrFunc(Erroraddr));
  557. dump_stack(stdout,ErrorBase);
  558. Writeln(stdout,'');
  559. End;
  560. End;
  561. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  562. begin
  563. InternalExit;
  564. System_exit;
  565. end;
  566. Procedure lib_exit;{$ifndef NOSAVEREGISTERS}saveregisters;{$endif}[Public,Alias:'FPC_LIB_EXIT'];
  567. begin
  568. InternalExit;
  569. end;
  570. Procedure Halt(ErrNum: Byte);
  571. Begin
  572. ExitCode:=Errnum;
  573. Do_Exit;
  574. end;
  575. function SysBackTraceStr (Addr: Pointer): ShortString;
  576. begin
  577. SysBackTraceStr:=' $'+HexStr(Ptrint(addr),sizeof(PtrInt)*2);
  578. end;
  579. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  580. begin
  581. If pointer(ErrorProc)<>Nil then
  582. ErrorProc(Errno,addr,frame);
  583. errorcode:=word(Errno);
  584. erroraddr:=addr;
  585. errorbase:=frame;
  586. if errorcode <= maxExitCode then
  587. halt(errorcode)
  588. else
  589. halt(255)
  590. end;
  591. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  592. {
  593. Procedure to handle internal errors, i.e. not user-invoked errors
  594. Internal function should ALWAYS call HandleError instead of RunError.
  595. Can be used for exception handlers to specify the frame
  596. }
  597. begin
  598. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  599. end;
  600. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  601. {
  602. Procedure to handle internal errors, i.e. not user-invoked errors
  603. Internal function should ALWAYS call HandleError instead of RunError.
  604. }
  605. begin
  606. HandleErrorFrame(Errno,get_frame);
  607. end;
  608. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  609. begin
  610. errorcode:=w;
  611. erroraddr:=get_caller_addr(get_frame);
  612. errorbase:=get_caller_frame(get_frame);
  613. if errorcode <= maxExitCode then
  614. halt(errorcode)
  615. else
  616. halt(255)
  617. end;
  618. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  619. Begin
  620. RunError (0);
  621. End;
  622. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  623. Begin
  624. Halt(0);
  625. End;
  626. function do_isdevice(handle:thandle):boolean;forward;
  627. Procedure dump_stack(var f : text;bp : Pointer);
  628. var
  629. i : Longint;
  630. prevbp : Pointer;
  631. is_dev : boolean;
  632. caller_frame,
  633. caller_addr : Pointer;
  634. Begin
  635. prevbp:=bp-1;
  636. i:=0;
  637. is_dev:=do_isdevice(textrec(f).Handle);
  638. while bp > prevbp Do
  639. Begin
  640. caller_addr := get_caller_addr(bp);
  641. caller_frame := get_caller_frame(bp);
  642. if (caller_addr=nil) or
  643. (caller_frame=nil) then
  644. break;
  645. Writeln(f,BackTraceStrFunc(caller_addr));
  646. Inc(i);
  647. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  648. break;
  649. prevbp:=bp;
  650. bp:=caller_frame;
  651. End;
  652. End;
  653. Type
  654. PExitProcInfo = ^TExitProcInfo;
  655. TExitProcInfo = Record
  656. Next : PExitProcInfo;
  657. SaveExit : Pointer;
  658. Proc : TProcedure;
  659. End;
  660. const
  661. ExitProcList: PExitProcInfo = nil;
  662. Procedure DoExitProc;
  663. var
  664. P : PExitProcInfo;
  665. Proc : TProcedure;
  666. Begin
  667. P:=ExitProcList;
  668. ExitProcList:=P^.Next;
  669. ExitProc:=P^.SaveExit;
  670. Proc:=P^.Proc;
  671. DisPose(P);
  672. Proc();
  673. End;
  674. Procedure AddExitProc(Proc: TProcedure);
  675. var
  676. P : PExitProcInfo;
  677. Begin
  678. New(P);
  679. P^.Next:=ExitProcList;
  680. P^.SaveExit:=ExitProc;
  681. P^.Proc:=Proc;
  682. ExitProcList:=P;
  683. ExitProc:=@DoExitProc;
  684. End;
  685. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  686. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  687. // Note: for internal use by skilled programmers only
  688. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  689. var p : ppchar;
  690. Res,
  691. i : LongInt;
  692. begin
  693. if High(s)<Low(s) Then Exit(NIL);
  694. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  695. // for cmd
  696. if p=nil then
  697. begin
  698. {$ifdef xunix}
  699. fpseterrno(ESysEnomem);
  700. {$endif}
  701. exit(NIL);
  702. end;
  703. for i:=low(s) to high(s) do
  704. p[i+Reserveentries]:=pchar(s[i]);
  705. p[high(s)+1+Reserveentries]:=nil;
  706. ArrayStringToPPchar:=p;
  707. end;
  708. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  709. {
  710. Create a PPChar to structure of pchars which are the arguments specified
  711. in the string S. Especially usefull for creating an ArgV for Exec-calls
  712. }
  713. begin
  714. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  715. end;
  716. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  717. var
  718. i,nr : longint;
  719. Buf : ^char;
  720. p : ppchar;
  721. InQuote : Boolean;
  722. begin
  723. buf:=s;
  724. nr:=1;
  725. InQuote:=false;
  726. while (buf^<>#0) do // count nr of args
  727. begin
  728. while (buf^ in [' ',#9,#10]) do // Kill separators.
  729. inc(buf);
  730. inc(nr);
  731. if buf^='"' Then // quotes argument?
  732. begin
  733. inc(buf);
  734. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  735. inc(buf);
  736. if buf^='"' then // skip closing quote.
  737. inc(buf);
  738. end
  739. else
  740. begin // else std
  741. while not (buf^ in [' ',#0,#9,#10]) do
  742. inc(buf);
  743. end;
  744. end;
  745. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  746. StringToPPChar:=p;
  747. if p=nil then
  748. begin
  749. {$ifdef xunix}
  750. fpseterrno(ESysEnomem);
  751. {$endif}
  752. exit;
  753. end;
  754. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  755. buf:=s;
  756. while (buf^<>#0) do
  757. begin
  758. while (buf^ in [' ',#9,#10]) do // Kill separators.
  759. begin
  760. buf^:=#0;
  761. inc(buf);
  762. end;
  763. if buf^='"' Then // quotes argument?
  764. begin
  765. inc(buf);
  766. p^:=buf;
  767. inc(p);
  768. p^:=nil;
  769. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  770. inc(buf);
  771. if buf^='"' then // skip closing quote.
  772. begin
  773. buf^:=#0;
  774. inc(buf);
  775. end;
  776. end
  777. else
  778. begin
  779. p^:=buf;
  780. inc(p);
  781. p^:=nil;
  782. while not (buf^ in [' ',#0,#9,#10]) do
  783. inc(buf);
  784. end;
  785. end;
  786. end;
  787. {*****************************************************************************
  788. Abstract/Assert support.
  789. *****************************************************************************}
  790. procedure fpc_AbstractErrorIntern;{$ifdef hascompilerproc}compilerproc;{$endif}[public,alias : 'FPC_ABSTRACTERROR'];
  791. begin
  792. If pointer(AbstractErrorProc)<>nil then
  793. AbstractErrorProc();
  794. HandleErrorFrame(211,get_frame);
  795. end;
  796. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);{$ifndef NOSAVEREGISTERS}saveregisters;{$endif} [Public,Alias : 'FPC_ASSERT']; {$ifdef hascompilerproc} compilerproc; {$endif}
  797. begin
  798. if pointer(AssertErrorProc)<>nil then
  799. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  800. else
  801. HandleErrorFrame(227,get_frame);
  802. end;
  803. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  804. begin
  805. If msg='' then
  806. write(stderr,'Assertion failed')
  807. else
  808. write(stderr,msg);
  809. Writeln(stderr,' (',FName,', line ',LineNo,').');
  810. Writeln(stderr,'');
  811. Halt(227);
  812. end;
  813. {*****************************************************************************
  814. SetJmp/LongJmp support.
  815. *****************************************************************************}
  816. {$i setjump.inc}
  817. {$ifdef IOCheckWasOn}
  818. {$I+}
  819. {$endif}
  820. {$ifdef RangeCheckWasOn}
  821. {$R+}
  822. {$endif}
  823. {$ifdef OverflowCheckWasOn}
  824. {$Q+}
  825. {$endif}
  826. {
  827. $Log$
  828. Revision 1.71 2004-12-05 14:36:37 hajny
  829. + GetProcessID added
  830. Revision 1.70 2004/11/21 16:14:59 jonas
  831. * fixed remaining compilation problems
  832. Revision 1.69 2004/11/20 15:49:21 jonas
  833. * some compilation fixes for powerpc after all the internconst and
  834. internproc changes, still crashes with internalerror(88) for ppc1
  835. on real2str.inc(193,39)
  836. Revision 1.68 2004/11/17 22:19:04 peter
  837. internconst, internproc and some external declarations moved to interface
  838. Revision 1.67 2004/10/30 20:49:10 marco
  839. * arraytostring added
  840. Revision 1.66 2004/10/24 20:01:42 peter
  841. * saveregisters calling convention is obsolete
  842. Revision 1.65 2004/10/09 21:00:46 jonas
  843. + cgenmath with libc math functions. Faster than the routines in genmath
  844. and also have full double support (exp() only has support for values in
  845. the single range in genmath, for example). Used in FPC_USE_LIBC is
  846. defined
  847. * several fixes to allow compilation with -dHASINLINE, but internalerrors
  848. because of missing support for inlining assembler code
  849. Revision 1.64 2004/09/03 19:26:01 olle
  850. + added maxExitCode to all System.pp
  851. * constrained error code to be below maxExitCode in RunError et. al.
  852. Revision 1.63 2004/08/31 12:23:53 jonas
  853. * fixed compilation with 1.0.x
  854. Revision 1.62 2004/08/30 17:36:18 jonas
  855. * fixed random(int64)
  856. Revision 1.61 2004/08/29 10:23:12 peter
  857. no message
  858. Revision 1.60 2004/07/18 20:21:44 florian
  859. + several unicode (to/from utf-8 conversion) stuff added
  860. * some longint -> SizeInt changes
  861. Revision 1.59 2004/05/27 23:34:23 peter
  862. * stop backtrace also when caller frame is nil
  863. Revision 1.58 2004/05/16 18:51:20 peter
  864. * use thandle in do_*
  865. Revision 1.57 2004/05/01 15:26:33 jonas
  866. * use some more string routines from libc if FPC_USE_LIBC is used
  867. Revision 1.56 2004/04/22 19:43:43 peter
  868. * fix 64bit address printing
  869. Revision 1.55 2004/04/22 17:10:38 peter
  870. * random(int64) added
  871. Revision 1.54 2004/02/20 11:01:20 daniel
  872. * Applied
  873. Revision 1.53 2004/02/06 20:17:13 daniel
  874. * Use $ for hex numbers instead of alien 0x
  875. Revision 1.52 2004/01/22 20:12:37 florian
  876. * fixed syscall number
  877. Revision 1.51 2004/01/11 12:21:06 jonas
  878. * fixed wrong include filename
  879. Revision 1.50 2004/01/11 11:10:07 jonas
  880. + cgeneric.inc: implementations of rtl routines based on libc
  881. * system.inc: include cgeneric.inc before powerpc.inc/i386.inc/... if
  882. FPC_USE_LIBC is defined
  883. * powerpc.inc, i386.inc: check whether the routines they implement aren't
  884. implemented yet in another include file (cgeneric.inc)
  885. Revision 1.49 2004/01/02 17:21:50 jonas
  886. + fpc_cpuinit procedure to allow cpu/fpu initialisation before any unit
  887. initialises
  888. + fpu exceptions for invalid operations and division by zero enabled for
  889. ppc
  890. Revision 1.48 2004/01/01 17:58:16 jonas
  891. + integer division-by-zero detection support for ppc
  892. + compilerproc FPC_DIVBYZERO
  893. Revision 1.47 2003/11/03 09:42:28 marco
  894. * Peter's Cardinal<->Longint fixes patch
  895. Revision 1.46 2003/10/29 18:23:45 jonas
  896. * hack to allow repeatable random sequences using the new random number
  897. generator
  898. * fixed range warning/error
  899. Revision 1.45 2003/10/26 21:15:43 hajny
  900. * minor fix for new Random
  901. Revision 1.44 2003/10/26 18:46:02 jonas
  902. * replaced random generator with the Mersenne twister, which is about
  903. 3.5 times faster
  904. Revision 1.43 2003/09/14 11:34:13 peter
  905. * moved int64 asm code to int64p.inc
  906. * save ebx,esi
  907. Revision 1.42 2003/09/03 14:09:37 florian
  908. * arm fixes to the common rtl code
  909. * some generic math code fixed
  910. * ...
  911. Revision 1.41 2003/08/21 22:10:55 olle
  912. - removed parameter from fpc_iocheck
  913. * changed processor compiler directive * to cpu*
  914. Revision 1.40 2003/03/17 14:30:11 peter
  915. * changed address parameter/return values to pointer instead
  916. of longint
  917. Revision 1.39 2003/02/05 21:48:34 mazen
  918. * fixing run time errors related to unimplemented abstract methods in CG
  919. + giving empty emplementations for some RTL functions
  920. Revision 1.38 2002/12/07 14:36:33 carl
  921. - avoid warnings (add typecast)
  922. Revision 1.37 2002/11/18 18:33:51 peter
  923. * Swap(QWord) constant support
  924. Revision 1.36 2002/10/14 19:39:17 peter
  925. * threads unit added for thread support
  926. Revision 1.35 2002/09/18 18:32:01 carl
  927. * assert now halts with exitcode 227 (as Delphi does)
  928. Revision 1.34 2002/09/07 15:07:46 peter
  929. * old logs removed and tabs fixed
  930. Revision 1.33 2002/08/19 19:34:02 peter
  931. * SYSTEMINLINE define that will add inline directives for small
  932. functions and wrappers. This will be defined automaticly when
  933. the compiler defines the HASINLINE directive
  934. Revision 1.32 2002/07/28 20:43:48 florian
  935. * several fixes for linux/powerpc
  936. * several fixes to MT
  937. Revision 1.31 2002/07/26 22:46:06 florian
  938. * interface of system unit for Linux/PowerPC compiles
  939. Revision 1.30 2002/07/26 16:42:00 florian
  940. * endian directive for PowerPC fixed
  941. Revision 1.29 2002/07/04 20:40:09 florian
  942. + some x86-64 support added
  943. Revision 1.28 2002/04/21 15:51:50 carl
  944. * StackError is now a typed constant
  945. + $S can be used under unix
  946. Revision 1.27 2002/04/15 19:38:40 peter
  947. * stackcheck protected against infinite recursive after stack error
  948. * stackcheck requires saveregisters, because it can be called from
  949. iocheck and then will destroy the result of the original function
  950. Revision 1.26 2002/04/15 18:51:20 carl
  951. + generic stack checking can be overriden
  952. Revision 1.25 2002/04/12 17:37:36 carl
  953. + generic stack checking
  954. }