system.inc 32 KB

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