system.inc 33 KB

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