system.inc 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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_iocheck;[public,alias:'FPC_IOCHECK']; compilerproc;
  456. var
  457. l : longint;
  458. begin
  459. if InOutRes<>0 then
  460. begin
  461. l:=InOutRes;
  462. InOutRes:=0;
  463. HandleErrorFrame(l,get_frame);
  464. end;
  465. end;
  466. Function IOResult:Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  467. Begin
  468. IOResult:=InOutRes;
  469. InOutRes:=0;
  470. End;
  471. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  472. begin
  473. (* ThreadID is stored in a threadvar and made available in interface *)
  474. (* to allow setup of this value during thread initialization. *)
  475. GetThreadID := ThreadID;
  476. end;
  477. function fpc_safecallcheck(res : hresult) : hresult;[public,alias:'FPC_SAFECALLCHECK']; compilerproc;
  478. begin
  479. if res<0 then
  480. begin
  481. if assigned(SafeCallErrorProc) then
  482. SafeCallErrorProc(res,get_frame);
  483. HandleErrorFrame(229,get_frame);
  484. end;
  485. result:=res;
  486. end;
  487. {*****************************************************************************
  488. Stack check code
  489. *****************************************************************************}
  490. {$IFNDEF NO_GENERIC_STACK_CHECK}
  491. {$IFOPT S+}
  492. {$DEFINE STACKCHECK}
  493. {$ENDIF}
  494. {$S-}
  495. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK'];
  496. var
  497. c : Pointer;
  498. begin
  499. { Avoid recursive calls when called from the exit routines }
  500. if StackError then
  501. exit;
  502. c := Sptr - (stack_size + STACK_MARGIN);
  503. if (c <= StackBottom) then
  504. begin
  505. StackError:=true;
  506. HandleError(202);
  507. end;
  508. end;
  509. {$IFDEF STACKCHECK}
  510. {$S+}
  511. {$ENDIF}
  512. {$UNDEF STACKCHECK}
  513. {$ENDIF NO_GENERIC_STACK_CHECK}
  514. {*****************************************************************************
  515. Initialization / Finalization
  516. *****************************************************************************}
  517. const
  518. maxunits=1024; { See also files.pas of the compiler source }
  519. type
  520. TInitFinalRec=record
  521. InitProc,
  522. FinalProc : TProcedure;
  523. end;
  524. TInitFinalTable=record
  525. TableCount,
  526. InitCount : longint;
  527. Procs : array[1..maxunits] of TInitFinalRec;
  528. end;
  529. var
  530. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  531. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  532. var
  533. i : longint;
  534. begin
  535. { call cpu/fpu initialisation routine }
  536. fpc_cpuinit;
  537. with InitFinalTable do
  538. begin
  539. for i:=1 to TableCount do
  540. begin
  541. if assigned(Procs[i].InitProc) then
  542. Procs[i].InitProc();
  543. InitCount:=i;
  544. end;
  545. end;
  546. if assigned(InitProc) then
  547. TProcedure(InitProc)();
  548. end;
  549. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  550. begin
  551. with InitFinalTable do
  552. begin
  553. while (InitCount>0) do
  554. begin
  555. // we've to decrement the cound before calling the final. code
  556. // else a halt in the final. code leads to a endless loop
  557. dec(InitCount);
  558. if assigned(Procs[InitCount+1].FinalProc) then
  559. Procs[InitCount+1].FinalProc();
  560. end;
  561. end;
  562. end;
  563. {*****************************************************************************
  564. Error / Exit / ExitProc
  565. *****************************************************************************}
  566. Procedure system_exit;forward;
  567. {$ifdef FPC_HAS_FEATURE_HEAP}
  568. {$if not (defined(HAS_MEMORYMANAGER) or defined(HAS_MT_MEMORYMANAGER))}
  569. //not needed if independant memory manager
  570. Procedure FinalizeHeap;forward;
  571. {$endif HAS_MEMORYMANAGER}
  572. {$endif FPC_HAS_FEATURE_HEAP}
  573. Procedure InternalExit;
  574. var
  575. current_exit : Procedure;
  576. pstdout : ^Text;
  577. {$if defined(MSWINDOWS) or defined(OS2)}
  578. i : longint;
  579. {$endif}
  580. Begin
  581. {$ifdef SYSTEMDEBUG}
  582. writeln('InternalExit');
  583. {$endif SYSTEMDEBUG}
  584. while exitProc<>nil Do
  585. Begin
  586. InOutRes:=0;
  587. current_exit:=tProcedure(exitProc);
  588. exitProc:=nil;
  589. current_exit();
  590. End;
  591. { Finalize units }
  592. FinalizeUnits;
  593. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  594. { Show runtime error and exit }
  595. pstdout:=@stdout;
  596. If erroraddr<>nil Then
  597. Begin
  598. Writeln(pstdout^,'Runtime error ',Errorcode,' at $',hexstr(erroraddr));
  599. { to get a nice symify }
  600. Writeln(pstdout^,BackTraceStrFunc(Erroraddr));
  601. dump_stack(pstdout^,ErrorBase);
  602. Writeln(pstdout^,'');
  603. End;
  604. { Make sure that all output is written to the redirected file }
  605. Flush(Output);
  606. Flush(ErrOutput);
  607. Flush(pstdout^);
  608. Flush(StdErr);
  609. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  610. {$if defined(MSWINDOWS) or defined(OS2)}
  611. { finally release the heap if possible, especially
  612. important for DLLs }
  613. for i:=0 to argc do
  614. sysfreemem(argv[i]);
  615. sysfreemem(argv);
  616. {$endif}
  617. {$ifdef LINUX}
  618. {sysfreemem already checks for nil}
  619. sysfreemem(calculated_cmdline);
  620. {$endif}
  621. {$ifdef BSD}
  622. sysfreemem(cmdline);
  623. {$endif}
  624. {$ifdef FPC_HAS_FEATURE_HEAP}
  625. {$if not (defined(HAS_MEMORYMANAGER) or defined(HAS_MT_MEMORYMANAGER))}
  626. FinalizeHeap;
  627. {$endif HAS_MEMORYMANAGER}
  628. {$endif FPC_HAS_FEATURE_HEAP}
  629. End;
  630. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  631. begin
  632. InternalExit;
  633. System_exit;
  634. end;
  635. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  636. begin
  637. InternalExit;
  638. end;
  639. Procedure Halt(ErrNum: Byte);
  640. Begin
  641. ExitCode:=Errnum;
  642. Do_Exit;
  643. end;
  644. function SysBackTraceStr (Addr: Pointer): ShortString;
  645. begin
  646. SysBackTraceStr:=' $'+hexstr(addr);
  647. end;
  648. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR'];
  649. begin
  650. If pointer(ErrorProc)<>Nil then
  651. ErrorProc(Errno,addr,frame);
  652. errorcode:=word(Errno);
  653. erroraddr:=addr;
  654. errorbase:=frame;
  655. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  656. if ExceptAddrStack <> nil then
  657. raise TObject(nil) at addr,frame;
  658. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  659. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  660. if errorcode <= maxExitCode then
  661. halt(errorcode)
  662. else
  663. halt(255)
  664. {$else FPC_HAS_FEATURE_EXITCODE}
  665. halt;
  666. {$endif FPC_HAS_FEATURE_EXITCODE}
  667. end;
  668. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  669. {
  670. Procedure to handle internal errors, i.e. not user-invoked errors
  671. Internal function should ALWAYS call HandleError instead of RunError.
  672. Can be used for exception handlers to specify the frame
  673. }
  674. begin
  675. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  676. end;
  677. Procedure HandleError (Errno : longint);[public,alias : 'FPC_HANDLEERROR'];
  678. {
  679. Procedure to handle internal errors, i.e. not user-invoked errors
  680. Internal function should ALWAYS call HandleError instead of RunError.
  681. }
  682. begin
  683. HandleErrorFrame(Errno,get_frame);
  684. end;
  685. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  686. begin
  687. errorcode:=w;
  688. erroraddr:=get_caller_addr(get_frame);
  689. errorbase:=get_caller_frame(get_frame);
  690. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  691. if errorcode <= maxExitCode then
  692. halt(errorcode)
  693. else
  694. halt(255)
  695. {$else FPC_HAS_FEATURE_EXITCODE}
  696. halt;
  697. {$endif FPC_HAS_FEATURE_EXITCODE}
  698. end;
  699. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  700. Begin
  701. RunError (0);
  702. End;
  703. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  704. Begin
  705. Halt(0);
  706. End;
  707. Procedure Error(RunTimeError : TRunTimeError);
  708. begin
  709. RunError(RuntimeErrorExitCodes[RunTimeError]);
  710. end;
  711. {$ifdef FPC_HAS_FEATURE_FILEIO}
  712. function do_isdevice(handle:thandle):boolean;forward;
  713. {$endif FPC_HAS_FEATURE_FILEIO}
  714. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  715. Procedure dump_stack(var f : text;bp : Pointer);
  716. var
  717. i : Longint;
  718. prevbp : Pointer;
  719. is_dev : boolean;
  720. caller_frame,
  721. caller_addr : Pointer;
  722. Begin
  723. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  724. try
  725. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  726. prevbp:=bp-1;
  727. i:=0;
  728. is_dev:=do_isdevice(textrec(f).Handle);
  729. while bp > prevbp Do
  730. Begin
  731. caller_addr := get_caller_addr(bp);
  732. caller_frame := get_caller_frame(bp);
  733. if (caller_addr=nil) then
  734. break;
  735. Writeln(f,BackTraceStrFunc(caller_addr));
  736. if (caller_frame=nil) then
  737. break;
  738. Inc(i);
  739. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  740. break;
  741. prevbp:=bp;
  742. bp:=caller_frame;
  743. End;
  744. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  745. except
  746. { prevent endless dump if an exception occured }
  747. end;
  748. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  749. End;
  750. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  751. {$ifdef FPC_HAS_FEATURE_HEAP}
  752. Type
  753. PExitProcInfo = ^TExitProcInfo;
  754. TExitProcInfo = Record
  755. Next : PExitProcInfo;
  756. SaveExit : Pointer;
  757. Proc : TProcedure;
  758. End;
  759. const
  760. ExitProcList: PExitProcInfo = nil;
  761. Procedure DoExitProc;
  762. var
  763. P : PExitProcInfo;
  764. Proc : TProcedure;
  765. Begin
  766. P:=ExitProcList;
  767. ExitProcList:=P^.Next;
  768. ExitProc:=P^.SaveExit;
  769. Proc:=P^.Proc;
  770. DisPose(P);
  771. Proc();
  772. End;
  773. Procedure AddExitProc(Proc: TProcedure);
  774. var
  775. P : PExitProcInfo;
  776. Begin
  777. New(P);
  778. P^.Next:=ExitProcList;
  779. P^.SaveExit:=ExitProc;
  780. P^.Proc:=Proc;
  781. ExitProcList:=P;
  782. ExitProc:=@DoExitProc;
  783. End;
  784. {$endif FPC_HAS_FEATURE_HEAP}
  785. {$ifdef FPC_HAS_FEATURE_HEAP}
  786. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  787. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  788. // Note: for internal use by skilled programmers only
  789. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  790. var p : ppchar;
  791. i : LongInt;
  792. begin
  793. if High(s)<Low(s) Then Exit(NIL);
  794. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  795. // for cmd
  796. if p=nil then
  797. begin
  798. {$ifdef xunix}
  799. fpseterrno(ESysEnomem);
  800. {$endif}
  801. exit(NIL);
  802. end;
  803. for i:=low(s) to high(s) do
  804. p[i+Reserveentries]:=pchar(s[i]);
  805. p[high(s)+1+Reserveentries]:=nil;
  806. ArrayStringToPPchar:=p;
  807. end;
  808. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  809. {
  810. Create a PPChar to structure of pchars which are the arguments specified
  811. in the string S. Especially usefull for creating an ArgV for Exec-calls
  812. }
  813. begin
  814. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  815. end;
  816. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  817. var
  818. i,nr : longint;
  819. Buf : ^char;
  820. p : ppchar;
  821. begin
  822. buf:=s;
  823. nr:=1;
  824. while (buf^<>#0) do // count nr of args
  825. begin
  826. while (buf^ in [' ',#9,#10]) do // Kill separators.
  827. inc(buf);
  828. inc(nr);
  829. if buf^='"' Then // quotes argument?
  830. begin
  831. inc(buf);
  832. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  833. inc(buf);
  834. if buf^='"' then // skip closing quote.
  835. inc(buf);
  836. end
  837. else
  838. begin // else std
  839. while not (buf^ in [' ',#0,#9,#10]) do
  840. inc(buf);
  841. end;
  842. end;
  843. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  844. StringToPPChar:=p;
  845. if p=nil then
  846. begin
  847. {$ifdef xunix}
  848. fpseterrno(ESysEnomem);
  849. {$endif}
  850. exit;
  851. end;
  852. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  853. buf:=s;
  854. while (buf^<>#0) do
  855. begin
  856. while (buf^ in [' ',#9,#10]) do // Kill separators.
  857. begin
  858. buf^:=#0;
  859. inc(buf);
  860. end;
  861. if buf^='"' Then // quotes argument?
  862. begin
  863. inc(buf);
  864. p^:=buf;
  865. inc(p);
  866. p^:=nil;
  867. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  868. inc(buf);
  869. if buf^='"' then // skip closing quote.
  870. begin
  871. buf^:=#0;
  872. inc(buf);
  873. end;
  874. end
  875. else
  876. begin
  877. p^:=buf;
  878. inc(p);
  879. p^:=nil;
  880. while not (buf^ in [' ',#0,#9,#10]) do
  881. inc(buf);
  882. end;
  883. end;
  884. end;
  885. {$endif FPC_HAS_FEATURE_HEAP}
  886. {*****************************************************************************
  887. Abstract/Assert support.
  888. *****************************************************************************}
  889. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  890. begin
  891. If pointer(AbstractErrorProc)<>nil then
  892. AbstractErrorProc();
  893. HandleErrorFrame(211,get_frame);
  894. end;
  895. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  896. begin
  897. if pointer(AssertErrorProc)<>nil then
  898. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  899. else
  900. HandleErrorFrame(227,get_frame);
  901. end;
  902. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  903. begin
  904. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  905. If msg='' then
  906. write(stderr,'Assertion failed')
  907. else
  908. write(stderr,msg);
  909. Writeln(stderr,' (',FName,', line ',LineNo,').');
  910. Writeln(stderr,'');
  911. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  912. Halt(227);
  913. {$else FPC_HAS_FEATURE_EXITCODE}
  914. halt;
  915. {$endif FPC_HAS_FEATURE_EXITCODE}
  916. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  917. end;
  918. {*****************************************************************************
  919. SetJmp/LongJmp support.
  920. *****************************************************************************}
  921. {$i setjump.inc}
  922. {$ifdef IOCheckWasOn}
  923. {$I+}
  924. {$endif}
  925. {$ifdef RangeCheckWasOn}
  926. {$R+}
  927. {$endif}
  928. {$ifdef OverflowCheckWasOn}
  929. {$Q+}
  930. {$endif}
  931. {*****************************************************************************
  932. OS dependent Helpers/Syscalls
  933. *****************************************************************************}
  934. {$i sysos.inc}
  935. {*****************************************************************************
  936. Heap
  937. *****************************************************************************}
  938. {$ifdef FPC_HAS_FEATURE_HEAP}
  939. {$i sysheap.inc}
  940. {$i heap.inc}
  941. {$endif FPC_HAS_FEATURE_HEAP}
  942. {*****************************************************************************
  943. Thread support
  944. *****************************************************************************}
  945. {$ifdef FPC_HAS_FEATURE_THREADING}
  946. { Generic threadmanager }
  947. {$i thread.inc}
  948. { Generic threadvar support }
  949. {$i threadvr.inc}
  950. { OS Dependent implementation }
  951. {$i systhrd.inc}
  952. {$endif FPC_HAS_FEATURE_THREADING}
  953. {*****************************************************************************
  954. File Handling
  955. *****************************************************************************}
  956. { OS dependent low level file functions }
  957. {$ifdef FPC_HAS_FEATURE_FILEIO}
  958. {$i sysfile.inc}
  959. {$endif FPC_HAS_FEATURE_FILEIO}
  960. { Text file }
  961. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  962. {$i text.inc}
  963. {$endif FPC_HAS_FEATURE_TEXTIO}
  964. {$ifdef FPC_HAS_FEATURE_FILEIO}
  965. { Untyped file }
  966. {$i file.inc}
  967. { Typed file }
  968. {$i typefile.inc}
  969. {$endif FPC_HAS_FEATURE_FILEIO}
  970. {*****************************************************************************
  971. Directory Handling
  972. *****************************************************************************}
  973. { OS dependent dir functions }
  974. {$i sysdir.inc}
  975. {*****************************************************************************
  976. Resources support
  977. *****************************************************************************}
  978. {$ifndef HAS_RESOURCES}
  979. {$i sysres.inc}
  980. {$endif}
  981. Function FindResource(ModuleHandle: HMODULE; ResourceName, ResourceType: AnsiString): TResourceHandle;
  982. begin
  983. Result:=FindResource(ModuleHandle,PChar(ResourceName),PChar(ResourceType));
  984. end;