system.inc 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814
  1. {
  2. This file is part of the Free Pascal Run time library.
  3. Copyright (c) 1999-2008 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. { The RTTI is implemented through a series of constants : }
  11. Const
  12. // please update tkManagedTypes below if you add new
  13. // values
  14. tkUnknown = 0;
  15. tkInteger = 1;
  16. tkChar = 2;
  17. tkEnumeration = 3;
  18. tkFloat = 4;
  19. tkSet = 5;
  20. tkMethod = 6;
  21. tkSString = 7;
  22. tkString = tkSString;
  23. tkLString = 8;
  24. tkAString = 9;
  25. tkWString = 10;
  26. tkVariant = 11;
  27. tkArray = 12;
  28. tkRecord = 13;
  29. tkInterface = 14;
  30. tkClass = 15;
  31. tkObject = 16;
  32. tkWChar = 17;
  33. tkBool = 18;
  34. tkInt64 = 19;
  35. tkQWord = 20;
  36. tkDynArray = 21;
  37. tkInterfaceCorba = 22;
  38. tkProcVar = 23;
  39. tkUString = 24;
  40. tkHelper = 26;
  41. tkFile = 27;
  42. tkClassRef = 28;
  43. tkPointer = 29;
  44. // all potentially managed types
  45. tkManagedTypes = [tkAstring,tkWstring,tkUstring,tkArray,
  46. tkObject,tkRecord,tkDynArray,tkInterface,tkVariant];
  47. {****************************************************************************
  48. Local types
  49. ****************************************************************************}
  50. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  51. {$ifdef FPC_OBJFPC_EXTENDED_IF}
  52. {$if High(errorcode)<>maxExitCode}
  53. {$define FPC_LIMITED_EXITCODE}
  54. {$endif}
  55. {$else}
  56. {$define FPC_LIMITED_EXITCODE}
  57. {$endif FPC_OBJFPC_EXTENDED_IF}
  58. {$endif FPC_HAS_FEATURE_EXITCODE}
  59. Procedure HandleError (Errno : Longint); external name 'FPC_HANDLEERROR';
  60. Procedure HandleErrorFrame (Errno : longint;frame : Pointer); forward;
  61. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer); forward;
  62. Procedure HandleErrorAddrFrameInd (Errno : longint;addr,frame : Pointer); forward;
  63. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  64. type
  65. FileFunc = Procedure(var t : TextRec);
  66. {$endif FPC_HAS_FEATURE_TEXTIO}
  67. const
  68. STACK_MARGIN = 16384; { Stack size margin for stack checking }
  69. { Random / Randomize constants }
  70. OldRandSeed : Cardinal = 0;
  71. { For Error Handling.}
  72. ErrorBase : Pointer = nil;public name 'FPC_ERRORBASE';
  73. { Used by the ansi/widestrings and maybe also other things in the future }
  74. var
  75. { widechar, because also used by widestring -> pwidechar conversions }
  76. emptychar : widechar;public name 'FPC_EMPTYCHAR';
  77. {$ifndef FPC_NO_GENERIC_STACK_CHECK}
  78. { if the OS does the stack checking, we don't need any stklen from the
  79. main program }
  80. initialstklen : SizeUint;external name '__stklen';
  81. {$endif FPC_NO_GENERIC_STACK_CHECK}
  82. { checks whether the given suggested size for the stack of the current
  83. thread is acceptable. If this is the case, returns it unaltered.
  84. Otherwise it should return an acceptable value.
  85. Operating systems that automatically expand their stack on demand, should
  86. simply return a very large value.
  87. Operating systems which do not have a possibility to retrieve stack size
  88. information, should simply return the given stklen value (This is the default
  89. implementation).
  90. }
  91. {$ifdef FPC_HAS_FEATURE_STACKCHECK}
  92. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt; forward;
  93. {$endif FPC_HAS_FEATURE_STACKCHECK}
  94. {*****************************************************************************
  95. OS dependent Helpers/Syscalls
  96. *****************************************************************************}
  97. { for some OSes do_isdevice is defined in sysos.inc, but for others (win32)
  98. it isn't, and is used before the actual definition is encountered }
  99. {$ifdef FPC_HAS_FEATURE_FILEIO}
  100. function do_isdevice(handle:thandle):boolean;forward;
  101. {$endif FPC_HAS_FEATURE_FILEIO}
  102. {$i sysos.inc}
  103. {****************************************************************************
  104. Include processor specific routines
  105. ****************************************************************************}
  106. {$ifdef FPC_USE_LIBC}
  107. { Under Haiku, bcopy cause a problem when searching for include file
  108. in the compiler. So, we use the internal implementation for now
  109. under BeOS and Haiku. }
  110. {$ifndef BEOS}
  111. { prefer libc implementations over our own, as they're most likely faster }
  112. {$i cgeneric.inc}
  113. { is now declared as external reference to another routine in the interface }
  114. {$i cgenstr.inc}
  115. {$endif}
  116. {$endif FPC_USE_LIBC}
  117. {$ifdef cpui386}
  118. {$ifdef SYSPROCDEFINED}
  119. {$Error Can't determine processor type !}
  120. {$endif}
  121. {$i i386.inc} { Case dependent, don't change }
  122. {$define SYSPROCDEFINED}
  123. {$endif cpui386}
  124. {$ifdef cpui8086}
  125. {$ifdef SYSPROCDEFINED}
  126. {$Error Can't determine processor type !}
  127. {$endif}
  128. {$i i8086.inc} { Case dependent, don't change }
  129. {$define SYSPROCDEFINED}
  130. {$endif cpui8086}
  131. {$ifdef cpum68k}
  132. {$ifdef SYSPROCDEFINED}
  133. {$Error Can't determine processor type !}
  134. {$endif}
  135. {$i m68k.inc} { Case dependent, don't change }
  136. {$define SYSPROCDEFINED}
  137. {$endif cpum68k}
  138. {$ifdef cpux86_64}
  139. {$ifdef SYSPROCDEFINED}
  140. {$Error Can't determine processor type !}
  141. {$endif}
  142. {$i x86_64.inc} { Case dependent, don't change }
  143. {$define SYSPROCDEFINED}
  144. {$endif cpux86_64}
  145. {$ifdef cpupowerpc32}
  146. {$ifdef SYSPROCDEFINED}
  147. {$Error Can't determine processor type !}
  148. {$endif}
  149. {$i powerpc.inc} { Case dependent, don't change }
  150. {$define SYSPROCDEFINED}
  151. {$endif cpupowerpc32}
  152. {$ifdef cpupowerpc64}
  153. {$ifdef SYSPROCDEFINED}
  154. {$Error Can't determine processor type !}
  155. {$endif}
  156. {$i powerpc64.inc} { Case dependent, don't change }
  157. {$define SYSPROCDEFINED}
  158. {$endif cpupowerpc64}
  159. {$ifdef cpualpha}
  160. {$ifdef SYSPROCDEFINED}
  161. {$Error Can't determine processor type !}
  162. {$endif}
  163. {$i alpha.inc} { Case dependent, don't change }
  164. {$define SYSPROCDEFINED}
  165. {$endif cpualpha}
  166. {$ifdef cpuiA64}
  167. {$ifdef SYSPROCDEFINED}
  168. {$Error Can't determine processor type !}
  169. {$endif}
  170. {$i ia64.inc} { Case dependent, don't change }
  171. {$define SYSPROCDEFINED}
  172. {$endif cpuiA64}
  173. {$ifdef cpusparc}
  174. {$ifdef SYSPROCDEFINED}
  175. {$Error Can't determine processor type !}
  176. {$endif}
  177. {$i sparc.inc} { Case dependent, don't change }
  178. {$define SYSPROCDEFINED}
  179. {$endif cpusparc}
  180. {$ifdef cpuarm}
  181. {$ifdef SYSPROCDEFINED}
  182. {$Error Can't determine processor type !}
  183. {$endif}
  184. {$i armdefines.inc}
  185. {$if defined(CPUTHUMB2)}
  186. {$i thumb2.inc} { Case dependent, don't change }
  187. {$else}
  188. {$if defined(CPUTHUMB)}
  189. {$i thumb.inc} { Case dependent, don't change }
  190. {$else}
  191. {$i arm.inc} { Case dependent, don't change }
  192. {$endif}
  193. {$endif}
  194. {$define SYSPROCDEFINED}
  195. {$endif cpuarm}
  196. {$ifdef cpuavr}
  197. {$ifdef SYSPROCDEFINED}
  198. {$Error Can't determine processor type !}
  199. {$endif}
  200. {$i avr.inc} { Case dependent, don't change }
  201. {$define SYSPROCDEFINED}
  202. {$endif cpuavr}
  203. {$ifdef cpumipsel}
  204. {$ifdef SYSPROCDEFINED}
  205. {$Error Can't determine processor type !}
  206. {$endif}
  207. { there is no mipsel.inc, we use mips.inc instead }
  208. {$i mips.inc} { Case dependent, don't change }
  209. {$define SYSPROCDEFINED}
  210. {$else not cpumipsel}
  211. {$ifdef cpumips}
  212. {$ifdef SYSPROCDEFINED}
  213. {$Error Can't determine processor type !}
  214. {$endif}
  215. {$i mips.inc} { Case dependent, don't change }
  216. {$define SYSPROCDEFINED}
  217. {$endif cpumips}
  218. {$endif not cpumipsel}
  219. {$ifndef SYSPROCDEFINED}
  220. {$Error Can't determine processor type !}
  221. {$endif}
  222. procedure fillchar(var x;count : SizeInt;value : boolean);
  223. begin
  224. fillchar(x,count,byte(value));
  225. end;
  226. procedure fillchar(var x;count : SizeInt;value : char);
  227. begin
  228. fillchar(x,count,byte(value));
  229. end;
  230. procedure FillByte (var x;count : SizeInt;value : byte );
  231. begin
  232. FillChar (X,Count,VALUE);
  233. end;
  234. function IndexChar(Const buf;len:SizeInt;b:char):SizeInt;
  235. begin
  236. IndexChar:=IndexByte(Buf,Len,byte(B));
  237. end;
  238. function CompareChar(Const buf1,buf2;len:SizeInt):SizeInt;
  239. begin
  240. CompareChar:=CompareByte(buf1,buf2,len);
  241. end;
  242. procedure fpc_zeromem(p:pointer;len:ptruint);
  243. begin
  244. FillChar(p^,len,0);
  245. end;
  246. procedure fpc_fillmem(out data;len:ptruint;b : byte);
  247. begin
  248. FillByte(data,len,b);
  249. end;
  250. { Include generic pascal only routines which are not defined in the processor
  251. specific include file }
  252. {$I generic.inc}
  253. {****************************************************************************
  254. Set Handling
  255. ****************************************************************************}
  256. { Include set support which is processor specific}
  257. {$i set.inc}
  258. { Include generic pascal routines for sets if the processor }
  259. { specific routines are not available. }
  260. {$i genset.inc}
  261. {****************************************************************************
  262. Math Routines
  263. ****************************************************************************}
  264. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  265. begin
  266. Hi := b shr 4
  267. end;
  268. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  269. begin
  270. Lo := b and $0f
  271. end;
  272. Function Swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  273. Begin
  274. Swap := SwapEndian(X);
  275. End;
  276. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}
  277. Begin
  278. Swap := SwapEndian(X);
  279. End;
  280. Function Swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}
  281. Begin
  282. Swap:=(X and $ffff) shl 16 + (X shr 16)
  283. End;
  284. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}
  285. Begin
  286. Swap:=(X and $ffff) shl 16 + (X shr 16)
  287. End;
  288. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}
  289. Begin
  290. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  291. End;
  292. Function swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}
  293. Begin
  294. Swap:=(X and $ffffffff) shl 32 + (X shr 32);
  295. End;
  296. {$ifdef SUPPORT_DOUBLE}
  297. operator := (b:real48) d:double;{$ifdef SYSTEMINLINE}inline;{$endif}
  298. begin
  299. D:=real2double(b);
  300. end;
  301. {$endif SUPPORT_DOUBLE}
  302. {$ifdef SUPPORT_EXTENDED}
  303. operator := (b:real48) e:extended;{$ifdef SYSTEMINLINE}inline;{$endif}
  304. begin
  305. e:=real2double(b);
  306. end;
  307. {$endif SUPPORT_EXTENDED}
  308. {$ifndef FPUNONE}
  309. {$ifdef FPC_USE_LIBC}
  310. { Include libc versions }
  311. {$i cgenmath.inc}
  312. {$endif FPC_USE_LIBC}
  313. { Include processor specific routines }
  314. {$I math.inc}
  315. { Include generic version }
  316. {$I genmath.inc}
  317. {$endif}
  318. {$i gencurr.inc}
  319. function aligntoptr(p : pointer) : pointer;inline;
  320. begin
  321. {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT}
  322. result:=align(p,sizeof(p));
  323. {$else FPC_REQUIRES_PROPER_ALIGNMENT}
  324. result:=p;
  325. {$endif FPC_REQUIRES_PROPER_ALIGNMENT}
  326. end;
  327. {****************************************************************************
  328. Subroutines for String handling
  329. ****************************************************************************}
  330. { Needs to be before RTTI handling }
  331. {$i sstrings.inc}
  332. { requires sstrings.inc for initval }
  333. {$I int64p.inc}
  334. {$I int64.inc}
  335. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  336. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  337. {$i astrings.inc}
  338. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  339. {$ifdef FPC_HAS_FEATURE_WIDESTRINGS}
  340. {$ifndef FPC_WIDESTRING_EQUAL_UNICODESTRING}
  341. {$i wstrings.inc}
  342. {$endif FPC_WIDESTRING_EQUAL_UNICODESTRING}
  343. {$i ustrings.inc}
  344. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  345. {$i aliases.inc}
  346. {*****************************************************************************
  347. Dynamic Array support
  348. *****************************************************************************}
  349. {$ifdef FPC_HAS_FEATURE_DYNARRAYS}
  350. {$i dynarr.inc}
  351. {$endif FPC_HAS_FEATURE_DYNARRAYS}
  352. {*****************************************************************************
  353. Object Pascal support
  354. *****************************************************************************}
  355. {$ifdef FPC_HAS_FEATURE_CLASSES}
  356. {$i objpas.inc}
  357. {$endif FPC_HAS_FEATURE_CLASSES}
  358. {*****************************************************************************
  359. Variant support
  360. *****************************************************************************}
  361. {$ifdef FPC_HAS_FEATURE_VARIANTS}
  362. {$i variant.inc}
  363. {$endif FPC_HAS_FEATURE_VARIANTS}
  364. {****************************************************************************
  365. Run-Time Type Information (RTTI)
  366. ****************************************************************************}
  367. {$ifdef FPC_HAS_FEATURE_RTTI}
  368. {$i rtti.inc}
  369. {$endif FPC_HAS_FEATURE_RTTI}
  370. {$if defined(FPC_HAS_FEATURE_RANDOM)}
  371. {----------------------------------------------------------------------
  372. Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  373. Pseudo-Random Number Generator.
  374. What is Mersenne Twister?
  375. Mersenne Twister(MT) is a pseudorandom number generator developped by
  376. Makoto Matsumoto and Takuji Nishimura (alphabetical order) during
  377. 1996-1997. MT has the following merits:
  378. It is designed with consideration on the flaws of various existing
  379. generators.
  380. Far longer period and far higher order of equidistribution than any
  381. other implemented generators. (It is proved that the period is 2^19937-1,
  382. and 623-dimensional equidistribution property is assured.)
  383. Fast generation. (Although it depends on the system, it is reported that
  384. MT is sometimes faster than the standard ANSI-C library in a system
  385. with pipeline and cache memory.)
  386. Efficient use of the memory. (The implemented C-code mt19937.c
  387. consumes only 624 words of working area.)
  388. home page
  389. http://www.math.keio.ac.jp/~matumoto/emt.html
  390. original c source
  391. http://www.math.keio.ac.jp/~nisimura/random/int/mt19937int.c
  392. Coded by Takuji Nishimura, considering the suggestions by
  393. Topher Cooper and Marc Rieffel in July-Aug. 1997.
  394. This library is free software; you can redistribute it and/or
  395. modify it under the terms of the GNU Library General Public
  396. License as published by the Free Software Foundation; either
  397. version 2 of the License, or (at your option) any later
  398. version.
  399. This library is distributed in the hope that it will be useful,
  400. but WITHOUT ANY WARRANTY; without even the implied warranty of
  401. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  402. See the GNU Library General Public License for more details.
  403. You should have received a copy of the GNU Library General
  404. Public License along with this library; if not, write to the
  405. Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  406. 02111-1307 USA
  407. Copyright (C) 1997, 1999 Makoto Matsumoto and Takuji Nishimura.
  408. When you use this, send an email to: [email protected]
  409. with an appropriate reference to your work.
  410. REFERENCE
  411. M. Matsumoto and T. Nishimura,
  412. "Mersenne Twister: A 623-Dimensionally Equidistributed Uniform
  413. Pseudo-Random Number Generator",
  414. ACM Transactions on Modeling and Computer Simulation,
  415. Vol. 8, No. 1, January 1998, pp 3--30.
  416. Translated to OP and Delphi interface added by Roman Krejci (6.12.1999)
  417. http://www.rksolution.cz/delphi/tips.htm
  418. Revised 21.6.2000: Bug in the function RandInt_MT19937 fixed
  419. 2003/10/26: adapted to use the improved intialisation mentioned at
  420. <http://www.math.keio.ac.jp/~matumoto/MT2002/emt19937ar.html> and
  421. removed the assembler code
  422. ----------------------------------------------------------------------}
  423. {$R-} {range checking off}
  424. {$Q-} {overflow checking off}
  425. { Period parameter }
  426. Const
  427. MT19937N=624;
  428. Type
  429. tMT19937StateArray = array [0..MT19937N-1] of longint; // the array for the state vector
  430. { Period parameters }
  431. const
  432. MT19937M=397;
  433. MT19937MATRIX_A =$9908b0df; // constant vector a
  434. MT19937UPPER_MASK=longint($80000000); // most significant w-r bits
  435. MT19937LOWER_MASK=longint($7fffffff); // least significant r bits
  436. { Tempering parameters }
  437. TEMPERING_MASK_B=longint($9d2c5680);
  438. TEMPERING_MASK_C=longint($efc60000);
  439. VAR
  440. mt : tMT19937StateArray;
  441. const
  442. mti: longint=MT19937N+1; // mti=MT19937N+1 means mt[] is not initialized
  443. { Initializing the array with a seed }
  444. procedure sgenrand_MT19937(seed: longint);
  445. var
  446. i: longint;
  447. begin
  448. mt[0] := seed;
  449. for i := 1 to MT19937N-1 do
  450. begin
  451. mt[i] := 1812433253 * (mt[i-1] xor (mt[i-1] shr 30)) + i;
  452. { See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. }
  453. { In the previous versions, MSBs of the seed affect }
  454. { only MSBs of the array mt[]. }
  455. { 2002/01/09 modified by Makoto Matsumoto }
  456. end;
  457. mti := MT19937N;
  458. end;
  459. function genrand_MT19937: longint;
  460. const
  461. mag01 : array [0..1] of longint =(0, longint(MT19937MATRIX_A));
  462. var
  463. y: longint;
  464. kk: longint;
  465. begin
  466. if RandSeed<>OldRandSeed then
  467. mti:=MT19937N+1;
  468. if (mti >= MT19937N) { generate MT19937N longints at one time }
  469. then begin
  470. if mti = (MT19937N+1) then // if sgenrand_MT19937() has not been called,
  471. begin
  472. sgenrand_MT19937(randseed); // default initial seed is used
  473. { hack: randseed is not used more than once in this algorithm. Most }
  474. { user changes are re-initialising reandseed with the value it had }
  475. { at the start -> with the "not", we will detect this change. }
  476. { Detecting other changes is not useful, since the generated }
  477. { numbers will be different anyway. }
  478. randseed := not(randseed);
  479. oldrandseed := randseed;
  480. end;
  481. for kk:=0 to MT19937N-MT19937M-1 do begin
  482. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  483. mt[kk] := mt[kk+MT19937M] xor (y shr 1) xor mag01[y and $00000001];
  484. end;
  485. for kk:= MT19937N-MT19937M to MT19937N-2 do begin
  486. y := (mt[kk] and MT19937UPPER_MASK) or (mt[kk+1] and MT19937LOWER_MASK);
  487. mt[kk] := mt[kk+(MT19937M-MT19937N)] xor (y shr 1) xor mag01[y and $00000001];
  488. end;
  489. y := (mt[MT19937N-1] and MT19937UPPER_MASK) or (mt[0] and MT19937LOWER_MASK);
  490. mt[MT19937N-1] := mt[MT19937M-1] xor (y shr 1) xor mag01[y and $00000001];
  491. mti := 0;
  492. end;
  493. y := mt[mti]; inc(mti);
  494. y := y xor (y shr 11);
  495. y := y xor (y shl 7) and TEMPERING_MASK_B;
  496. y := y xor (y shl 15) and TEMPERING_MASK_C;
  497. y := y xor (y shr 18);
  498. Result := y;
  499. end;
  500. function random(l:longint): longint;
  501. begin
  502. { otherwise we can return values = l (JM) }
  503. if (l < 0) then
  504. inc(l);
  505. random := longint((int64(cardinal(genrand_MT19937))*l) shr 32);
  506. end;
  507. function random(l:int64): int64;
  508. begin
  509. { always call random, so the random generator cycles (TP-compatible) (JM) }
  510. random := int64((qword(cardinal(genrand_MT19937)) or ((qword(cardinal(genrand_MT19937)) shl 32))) and $7fffffffffffffff);
  511. if (l<>0) then
  512. random := random mod l
  513. else
  514. random := 0;
  515. end;
  516. {$ifndef FPUNONE}
  517. function random: extended;
  518. begin
  519. random := cardinal(genrand_MT19937) * (extended(1.0)/(int64(1) shl 32));
  520. end;
  521. {$endif}
  522. {$endif FPC_HAS_FEATURE_RANDOM}
  523. {****************************************************************************
  524. Memory Management
  525. ****************************************************************************}
  526. {$ifndef FPC_SYSTEM_HAS_PTR}
  527. Function Ptr(sel,off : Longint) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}
  528. Begin
  529. ptr:=farpointer((sel shl 4)+off);
  530. End;
  531. {$endif not FPC_SYSTEM_HAS_PTR}
  532. {$ifndef FPC_SYSTEM_HAS_CSEG}
  533. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  534. Begin
  535. Cseg:=0;
  536. End;
  537. {$endif not FPC_SYSTEM_HAS_CSEG}
  538. {$ifndef FPC_SYSTEM_HAS_DSEG}
  539. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  540. Begin
  541. Dseg:=0;
  542. End;
  543. {$endif not FPC_SYSTEM_HAS_DSEG}
  544. {$ifndef FPC_SYSTEM_HAS_SSEG}
  545. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  546. Begin
  547. Sseg:=0;
  548. End;
  549. {$endif not FPC_SYSTEM_HAS_SSEG}
  550. {$push}
  551. {$R-}
  552. {$I-}
  553. {$Q-}
  554. {*****************************************************************************
  555. Miscellaneous
  556. *****************************************************************************}
  557. {$ifndef FPC_SYSTEM_HAS_GET_PC_ADDR}
  558. { This provides a dummy implementation
  559. of get_pc_addr function, for CPU's that don't need
  560. the instruction address to walk the stack. }
  561. function get_pc_addr : pointer;
  562. begin
  563. get_pc_addr:=nil;
  564. end;
  565. {$endif ndef FPC_SYSTEM_HAS_GET_PC_ADDR}
  566. {$ifndef FPC_SYSTEM_HAS_GET_CALLER_STACKINFO}
  567. { This provides a simple implementation
  568. of get_caller_stackinfo procedure,
  569. using get_caller_addr and get_caller_frame
  570. functions. }
  571. procedure get_caller_stackinfo(var framebp,addr : pointer);
  572. var
  573. nextbp,nextaddr : pointer;
  574. begin
  575. nextbp:=get_caller_frame(framebp,addr);
  576. nextaddr:=get_caller_addr(framebp,addr);
  577. framebp:=nextbp;
  578. addr:=nextaddr;
  579. end;
  580. {$endif ndef FPC_SYSTEM_HAS_GET_CALLER_STACKINFO}
  581. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; compilerproc;
  582. begin
  583. HandleErrorAddrFrameInd(201,get_pc_addr,get_frame);
  584. end;
  585. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; compilerproc;
  586. begin
  587. HandleErrorAddrFrameInd(200,get_pc_addr,get_frame);
  588. end;
  589. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; compilerproc;
  590. begin
  591. HandleErrorAddrFrameInd(215,get_pc_addr,get_frame);
  592. end;
  593. procedure fpc_threaderror; [public,alias:'FPC_THREADERROR'];
  594. begin
  595. HandleErrorAddrFrameInd(6,get_pc_addr,get_frame);
  596. end;
  597. procedure fpc_invalidpointer; [public,alias:'FPC_INVALIDPOINTER'];
  598. begin
  599. HandleErrorAddrFrameInd(216,get_pc_addr,get_frame);
  600. end;
  601. procedure fpc_iocheck;[public,alias:'FPC_IOCHECK']; compilerproc;
  602. var
  603. l : longint;
  604. HInoutRes : PWord;
  605. begin
  606. HInOutRes:=@InoutRes;
  607. if HInOutRes^<>0 then
  608. begin
  609. l:=HInOutRes^;
  610. HInOutRes^:=0;
  611. HandleErrorAddrFrameInd(l,get_pc_addr,get_frame);
  612. end;
  613. end;
  614. Function IOResult:Word;
  615. var
  616. HInoutRes : PWord;
  617. Begin
  618. HInoutRes:=@InoutRes;
  619. IOResult:=HInOutRes^;
  620. HInOutRes^:=0;
  621. End;
  622. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  623. begin
  624. (* ThreadID is stored in a threadvar and made available in interface *)
  625. (* to allow setup of this value during thread initialization. *)
  626. GetThreadID := ThreadID;
  627. end;
  628. function fpc_safecallcheck(res : hresult) : hresult;[public,alias:'FPC_SAFECALLCHECK']; compilerproc; {$ifdef CPU86} register; {$endif}
  629. begin
  630. if res<0 then
  631. begin
  632. if assigned(SafeCallErrorProc) then
  633. SafeCallErrorProc(res,get_frame);
  634. HandleErrorAddrFrameInd(229,get_pc_addr,get_frame);
  635. end;
  636. result:=res;
  637. end;
  638. {*****************************************************************************
  639. Stack check code
  640. *****************************************************************************}
  641. { be compatible with old code }
  642. {$ifdef FPC_NO_GENERIC_STACK_CHECK}
  643. {$define NO_GENERIC_STACK_CHECK}
  644. {$endif FPC_NO_GENERIC_STACK_CHECK}
  645. {$IFNDEF NO_GENERIC_STACK_CHECK}
  646. {$PUSH}
  647. {$S-}
  648. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK']; compilerproc;
  649. var
  650. c : Pointer;
  651. begin
  652. { Avoid recursive calls when called from the exit routines }
  653. if StackError then
  654. exit;
  655. { don't use sack_size, since the stack pointer has already been
  656. decreased when this routine is called
  657. }
  658. c := Sptr - STACK_MARGIN;
  659. if (c <= StackBottom) then
  660. begin
  661. StackError:=true;
  662. HandleError(202);
  663. end;
  664. end;
  665. {$POP}
  666. {$ENDIF NO_GENERIC_STACK_CHECK}
  667. {*****************************************************************************
  668. Initialization / Finalization
  669. *****************************************************************************}
  670. const
  671. maxunits=1024; { See also files.pas of the compiler source }
  672. type
  673. TInitFinalRec=record
  674. InitProc,
  675. FinalProc : TProcedure;
  676. end;
  677. TInitFinalTable = record
  678. TableCount,
  679. InitCount : longint;
  680. Procs : array[1..maxunits] of TInitFinalRec;
  681. end;
  682. PInitFinalTable = ^TInitFinalTable;
  683. {$ifndef FPC_HAS_INDIRECT_MAIN_INFORMATION}
  684. var
  685. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  686. {$endif FPC_HAS_INDIRECT_MAIN_INFORMATION}
  687. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  688. var
  689. i : longint;
  690. {$ifdef DEBUG}
  691. pt : PInitFinalTable;
  692. {$endif}
  693. begin
  694. { call cpu/fpu initialisation routine }
  695. fpc_cpuinit;
  696. {$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}
  697. {$ifdef DEBUG}
  698. pt := PInitFinalTable(EntryInformation.InitFinalTable);
  699. {$endif}
  700. with PInitFinalTable(EntryInformation.InitFinalTable)^ do
  701. {$else FPC_HAS_INDIRECT_MAIN_INFORMATION}
  702. {$ifdef DEBUG}
  703. pt := @InitFinalTable;
  704. {$endif}
  705. with InitFinalTable do
  706. {$endif FPC_HAS_INDIRECT_MAIN_INFORMATION}
  707. begin
  708. for i:=1 to TableCount do
  709. begin
  710. if assigned(Procs[i].InitProc) then
  711. Procs[i].InitProc();
  712. InitCount:=i;
  713. end;
  714. end;
  715. if assigned(InitProc) then
  716. TProcedure(InitProc)();
  717. end;
  718. procedure internal_initializeunits; external name 'FPC_INITIALIZEUNITS';
  719. procedure fpc_LibInitializeUnits;[public,alias:'FPC_LIBINITIALIZEUNITS'];
  720. begin
  721. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  722. IsLibrary:=true;
  723. { must also be set to true for packages when implemented }
  724. ModuleIsLib:=true;
  725. internal_initializeunits;
  726. {$endif FPC_HAS_FEATURE_DYNLIBS}
  727. end;
  728. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  729. begin
  730. {$ifdef FPC_HAS_INDIRECT_MAIN_INFORMATION}
  731. with PInitFinalTable(EntryInformation.InitFinalTable)^ do
  732. {$else FPC_HAS_INDIRECT_MAIN_INFORMATION}
  733. with InitFinalTable do
  734. {$endif FPC_HAS_INDIRECT_MAIN_INFORMATION}
  735. begin
  736. while (InitCount>0) do
  737. begin
  738. // we've to decrement the cound before calling the final. code
  739. // else a halt in the final. code leads to a endless loop
  740. dec(InitCount);
  741. if assigned(Procs[InitCount+1].FinalProc) then
  742. Procs[InitCount+1].FinalProc();
  743. end;
  744. end;
  745. end;
  746. {*****************************************************************************
  747. Error / Exit / ExitProc
  748. *****************************************************************************}
  749. Procedure system_exit;forward;
  750. {$ifdef FPC_HAS_FEATURE_HEAP}
  751. {$ifndef HAS_MEMORYMANAGER}
  752. //not needed if independant memory manager
  753. Procedure FinalizeHeap;forward;
  754. {$endif HAS_MEMORYMANAGER}
  755. {$endif FPC_HAS_FEATURE_HEAP}
  756. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  757. procedure SysFlushStdIO;
  758. begin
  759. { Make sure that all output is written to the redirected file }
  760. if Textrec(Output).Mode=fmOutput then
  761. Flush(Output);
  762. if Textrec(ErrOutput).Mode=fmOutput then
  763. Flush(ErrOutput);
  764. if Textrec(stdout).Mode=fmOutput then
  765. Flush(stdout);
  766. if Textrec(StdErr).Mode=fmOutput then
  767. Flush(StdErr);
  768. end;
  769. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  770. Procedure InternalExit;
  771. var
  772. current_exit : Procedure;
  773. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  774. pstdout : ^Text;
  775. {$endif}
  776. {$if defined(MSWINDOWS) or defined(OS2)}
  777. i : longint;
  778. {$endif}
  779. Begin
  780. {$ifdef SYSTEMDEBUG}
  781. writeln('InternalExit');
  782. {$endif SYSTEMDEBUG}
  783. while exitProc<>nil Do
  784. Begin
  785. InOutRes:=0;
  786. current_exit:=tProcedure(exitProc);
  787. exitProc:=nil;
  788. current_exit();
  789. End;
  790. { Finalize units }
  791. FinalizeUnits;
  792. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  793. { the embedded system unit itself contains no routines for console i/o
  794. console i/o is done by the Consoleio unit which can do things like
  795. redirection to seriell i/o }
  796. {$ifndef EMBEDDED}
  797. { Show runtime error and exit }
  798. pstdout:=@stdout;
  799. If erroraddr<>nil Then
  800. Begin
  801. Writeln(pstdout^,'Runtime error ',Errorcode,' at $',hexstr(erroraddr));
  802. { to get a nice symify }
  803. Writeln(pstdout^,BackTraceStrFunc(Erroraddr));
  804. dump_stack(pstdout^,ErrorBase,ErrorAddr);
  805. Writeln(pstdout^,'');
  806. End;
  807. SysFlushStdIO;
  808. {$endif EMBEDDED}
  809. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  810. {$if defined(MSWINDOWS) or defined(OS2)}
  811. { finally release the heap if possible, especially
  812. important for DLLs.
  813. Reset the array to nil, and finally also argv itself to
  814. avoid double freeing problem in case this function gets called twice. }
  815. if assigned(argv) then
  816. begin
  817. for i:=0 to argc-1 do
  818. if assigned(argv[i]) then
  819. begin
  820. sysfreemem(argv[i]);
  821. argv[i]:=nil;
  822. end;
  823. sysfreemem(argv);
  824. argv:=nil;
  825. end;
  826. {$endif}
  827. {$ifdef LINUX}
  828. {sysfreemem already checks for nil}
  829. { Do not try to do anything if the heap manager already reported an error }
  830. if (errorcode<>203) and (errorcode<>204) then
  831. sysfreemem(calculated_cmdline);
  832. {$endif}
  833. {$ifdef BSD}
  834. { Do not try to do anything if the heap manager already reported an error }
  835. if (errorcode<>203) and (errorcode<>204) then
  836. sysfreemem(cmdline);
  837. {$endif}
  838. {$ifdef FPC_HAS_FEATURE_HEAP}
  839. {$ifndef HAS_MEMORYMANAGER}
  840. FinalizeHeap;
  841. {$endif HAS_MEMORYMANAGER}
  842. {$endif FPC_HAS_FEATURE_HEAP}
  843. End;
  844. Procedure do_exit;[Public,Alias:'FPC_DO_EXIT'];
  845. begin
  846. InternalExit;
  847. System_exit;
  848. end;
  849. Procedure lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  850. begin
  851. InternalExit;
  852. end;
  853. Procedure Halt(ErrNum: Longint);
  854. Begin
  855. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  856. {$ifdef FPC_LIMITED_EXITCODE}
  857. if ErrNum > maxExitCode then
  858. ExitCode:=255
  859. else
  860. {$endif FPC_LIMITED_EXITCODE}
  861. ExitCode:=ErrNum;
  862. {$endif FPC_HAS_FEATURE_EXITCODE}
  863. Do_Exit;
  864. end;
  865. function SysBackTraceStr (Addr: Pointer): ShortString;
  866. begin
  867. SysBackTraceStr:=' $'+hexstr(addr);
  868. end;
  869. Procedure HandleErrorAddrFrame (Errno : longint;addr,frame : Pointer);[public,alias:'FPC_BREAK_ERROR']; {$ifdef CPUI386} register; {$endif}
  870. begin
  871. If pointer(ErrorProc)<>Nil then
  872. ErrorProc(Errno,addr,frame);
  873. errorcode:=word(Errno);
  874. erroraddr:=addr;
  875. errorbase:=frame;
  876. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  877. if ExceptAddrStack <> nil then
  878. raise TObject(nil) at addr,frame;
  879. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  880. Halt(errorcode);
  881. end;
  882. { This is used internally by system skip first level,
  883. and generated the same output as before, when
  884. HandleErrorFrame function was used internally. }
  885. Procedure HandleErrorAddrFrameInd (Errno : longint;addr,frame : Pointer);
  886. begin
  887. get_caller_stackinfo (frame, addr);
  888. HandleErrorAddrFrame (Errno,addr,frame);
  889. end;
  890. Procedure HandleErrorFrame (Errno : longint;frame : Pointer);
  891. {
  892. Procedure to handle internal errors, i.e. not user-invoked errors
  893. Internal function should ALWAYS call HandleError instead of RunError.
  894. Can be used for exception handlers to specify the frame
  895. }
  896. begin
  897. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  898. end;
  899. procedure fpc_handleerror (Errno : longint); compilerproc; [public,alias : 'FPC_HANDLEERROR'];
  900. {
  901. Procedure to handle internal errors, i.e. not user-invoked errors
  902. Internal function should ALWAYS call HandleError instead of RunError.
  903. }
  904. begin
  905. HandleErrorAddrFrameInd(Errno,get_pc_addr,get_frame);
  906. end;
  907. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];
  908. var
  909. bp,pcaddr : pointer;
  910. begin
  911. errorcode:=w;
  912. pcaddr:=get_pc_addr;
  913. bp:=get_frame;
  914. get_caller_stackinfo(bp,pcaddr);
  915. erroraddr:=pcaddr;
  916. errorbase:=bp;
  917. Halt(errorcode);
  918. end;
  919. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}
  920. Begin
  921. RunError (0);
  922. End;
  923. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}
  924. Begin
  925. Halt(0);
  926. End;
  927. Procedure Error(RunTimeError : TRunTimeError);
  928. begin
  929. RunError(RuntimeErrorExitCodes[RunTimeError]);
  930. end;
  931. Procedure dump_stack(var f : text;fp,addr : Pointer);
  932. var
  933. i : Longint;
  934. prevfp : Pointer;
  935. prevaddr : pointer;
  936. is_dev : boolean;
  937. caller_frame,
  938. caller_addr : Pointer;
  939. Begin
  940. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  941. try
  942. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  943. prevfp:=fp-1;
  944. prevaddr:=nil;
  945. i:=0;
  946. is_dev:=do_isdevice(textrec(f).Handle);
  947. { sanity checks, new frame pointer must be always greater than the old one, further
  948. it must point into the stack area, else something went wrong }
  949. while (fp>prevfp) and (fp<StackTop) and (fp>StackBottom) Do
  950. Begin
  951. caller_addr := get_caller_addr(fp,addr);
  952. caller_frame := get_caller_frame(fp,addr);
  953. if (caller_addr=nil) then
  954. break;
  955. Writeln(f,BackTraceStrFunc(caller_addr));
  956. if (caller_frame=nil) then
  957. break;
  958. Inc(i);
  959. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  960. break;
  961. prevfp:=fp;
  962. prevaddr:=addr;
  963. fp:=caller_frame;
  964. addr:=caller_addr;
  965. End;
  966. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  967. except
  968. { prevent endless dump if an exception occured }
  969. end;
  970. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  971. End;
  972. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  973. procedure DumpExceptionBackTrace(var f:text);
  974. var
  975. FrameNumber,
  976. FrameCount : longint;
  977. Frames : PPointer;
  978. begin
  979. if RaiseList=nil then
  980. exit;
  981. WriteLn(f,BackTraceStrFunc(RaiseList^.Addr));
  982. FrameCount:=RaiseList^.Framecount;
  983. Frames:=RaiseList^.Frames;
  984. for FrameNumber := 0 to FrameCount-1 do
  985. WriteLn(f,BackTraceStrFunc(Frames[FrameNumber]));
  986. end;
  987. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  988. {$ifdef FPC_HAS_FEATURE_HEAP}
  989. Type
  990. PExitProcInfo = ^TExitProcInfo;
  991. TExitProcInfo = Record
  992. Next : PExitProcInfo;
  993. SaveExit : CodePointer;
  994. Proc : TProcedure;
  995. End;
  996. const
  997. ExitProcList: PExitProcInfo = nil;
  998. Procedure DoExitProc;
  999. var
  1000. P : PExitProcInfo;
  1001. Proc : TProcedure;
  1002. Begin
  1003. P:=ExitProcList;
  1004. ExitProcList:=P^.Next;
  1005. ExitProc:=P^.SaveExit;
  1006. Proc:=P^.Proc;
  1007. DisPose(P);
  1008. Proc();
  1009. End;
  1010. Procedure AddExitProc(Proc: TProcedure);
  1011. var
  1012. P : PExitProcInfo;
  1013. Begin
  1014. New(P);
  1015. P^.Next:=ExitProcList;
  1016. P^.SaveExit:=ExitProc;
  1017. P^.Proc:=Proc;
  1018. ExitProcList:=P;
  1019. ExitProc:=@DoExitProc;
  1020. End;
  1021. {$endif FPC_HAS_FEATURE_HEAP}
  1022. {$ifdef FPC_HAS_FEATURE_HEAP}
  1023. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  1024. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  1025. // Note: for internal use by skilled programmers only
  1026. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  1027. var p : ppchar;
  1028. i : LongInt;
  1029. begin
  1030. if High(s)<Low(s) Then Exit(NIL);
  1031. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  1032. // for cmd
  1033. if p=nil then
  1034. begin
  1035. {$ifdef xunix}
  1036. fpseterrno(ESysEnomem);
  1037. {$endif}
  1038. exit(NIL);
  1039. end;
  1040. for i:=low(s) to high(s) do
  1041. p[i+Reserveentries]:=pchar(s[i]);
  1042. p[high(s)+1+Reserveentries]:=nil;
  1043. ArrayStringToPPchar:=p;
  1044. end;
  1045. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  1046. {
  1047. Create a PPChar to structure of pchars which are the arguments specified
  1048. in the string S. Especially useful for creating an ArgV for Exec-calls
  1049. }
  1050. begin
  1051. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  1052. end;
  1053. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  1054. var
  1055. i,nr : longint;
  1056. Buf : ^char;
  1057. p : ppchar;
  1058. begin
  1059. buf:=s;
  1060. nr:=1;
  1061. while (buf^<>#0) do // count nr of args
  1062. begin
  1063. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1064. inc(buf);
  1065. inc(nr);
  1066. if buf^='"' Then // quotes argument?
  1067. begin
  1068. inc(buf);
  1069. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1070. inc(buf);
  1071. if buf^='"' then // skip closing quote.
  1072. inc(buf);
  1073. end
  1074. else
  1075. begin // else std
  1076. while not (buf^ in [' ',#0,#9,#10]) do
  1077. inc(buf);
  1078. end;
  1079. end;
  1080. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  1081. StringToPPChar:=p;
  1082. if p=nil then
  1083. begin
  1084. {$ifdef xunix}
  1085. fpseterrno(ESysEnomem);
  1086. {$endif}
  1087. exit;
  1088. end;
  1089. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  1090. buf:=s;
  1091. while (buf^<>#0) do
  1092. begin
  1093. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1094. begin
  1095. buf^:=#0;
  1096. inc(buf);
  1097. end;
  1098. if buf^='"' Then // quotes argument?
  1099. begin
  1100. inc(buf);
  1101. p^:=buf;
  1102. inc(p);
  1103. p^:=nil;
  1104. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1105. inc(buf);
  1106. if buf^='"' then // skip closing quote.
  1107. begin
  1108. buf^:=#0;
  1109. inc(buf);
  1110. end;
  1111. end
  1112. else
  1113. begin
  1114. p^:=buf;
  1115. inc(p);
  1116. p^:=nil;
  1117. while not (buf^ in [' ',#0,#9,#10]) do
  1118. inc(buf);
  1119. end;
  1120. end;
  1121. end;
  1122. {$endif FPC_HAS_FEATURE_HEAP}
  1123. {*****************************************************************************
  1124. Abstract/Assert support.
  1125. *****************************************************************************}
  1126. procedure fpc_emptymethod;[public,alias : 'FPC_EMPTYMETHOD'];
  1127. begin
  1128. end;
  1129. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  1130. begin
  1131. If pointer(AbstractErrorProc)<>nil then
  1132. AbstractErrorProc();
  1133. HandleErrorAddrFrameInd(211,get_pc_addr,get_frame);
  1134. end;
  1135. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;
  1136. ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  1137. begin
  1138. if pointer(AssertErrorProc)<>nil then
  1139. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  1140. else
  1141. HandleErrorAddrFrameInd(227,get_pc_addr,get_frame);
  1142. end;
  1143. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  1144. begin
  1145. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1146. If msg='' then
  1147. write(stderr,'Assertion failed')
  1148. else
  1149. write(stderr,msg);
  1150. Writeln(stderr,' (',FName,', line ',LineNo,').');
  1151. Writeln(stderr,'');
  1152. Halt(227);
  1153. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1154. end;
  1155. {*****************************************************************************
  1156. SetJmp/LongJmp support.
  1157. *****************************************************************************}
  1158. {$i setjump.inc}
  1159. {$pop} //{$I-,R-,Q-} before 'procedure fpc_rangeerror'
  1160. {*****************************************************************************
  1161. Heap
  1162. *****************************************************************************}
  1163. {$i sysheap.inc}
  1164. {$i heap.inc}
  1165. {*****************************************************************************
  1166. Thread support
  1167. *****************************************************************************}
  1168. {$ifdef FPC_HAS_FEATURE_THREADING}
  1169. { Generic threadmanager }
  1170. {$i thread.inc}
  1171. { Generic threadvar support }
  1172. {$i threadvr.inc}
  1173. {$ifdef DISABLE_NO_THREAD_MANAGER}
  1174. { OS Dependent implementation }
  1175. {$i systhrd.inc}
  1176. {$endif DISABLE_NO_THREAD_MANAGER}
  1177. {$endif FPC_HAS_FEATURE_THREADING}
  1178. {*****************************************************************************
  1179. File Handling
  1180. *****************************************************************************}
  1181. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1182. { Allow slash and backslash as separators }
  1183. procedure DoDirSeparators(var p: pchar; inplace: boolean = true);
  1184. var
  1185. i : longint;
  1186. len : sizeint;
  1187. newp : pchar;
  1188. begin
  1189. len:=length(p);
  1190. newp:=nil;
  1191. for i:=0 to len do
  1192. if p[i] in AllowDirectorySeparators then
  1193. begin
  1194. if not inplace and
  1195. not assigned(newp) then
  1196. begin
  1197. getmem(newp,len+1);
  1198. move(p^,newp^,len+1);
  1199. p:=newp;
  1200. end;
  1201. p[i]:=DirectorySeparator;
  1202. end;
  1203. end;
  1204. procedure DoDirSeparators(var p: pwidechar; inplace: boolean = true);
  1205. var
  1206. i : longint;
  1207. len : sizeint;
  1208. newp : pwidechar;
  1209. begin
  1210. len:=length(p);
  1211. newp:=nil;
  1212. for i:=0 to len do
  1213. if (ord(p[i])<255) and
  1214. (ansichar(ord(p[i])) in AllowDirectorySeparators) then
  1215. begin
  1216. if not inplace and
  1217. not assigned(newp) then
  1218. begin
  1219. getmem(newp,(len+1)*2);
  1220. move(p^,newp^,(len+1)*2);
  1221. p:=newp;
  1222. end;
  1223. p[i]:=DirectorySeparator;
  1224. end;
  1225. end;
  1226. procedure DoDirSeparators(var p:shortstring);
  1227. var
  1228. i : longint;
  1229. begin
  1230. for i:=1 to length(p) do
  1231. if p[i] in AllowDirectorySeparators then
  1232. p[i]:=DirectorySeparator;
  1233. end;
  1234. procedure DoDirSeparators(var ps:RawByteString);
  1235. var
  1236. i : longint;
  1237. p : pchar;
  1238. unique : boolean;
  1239. begin
  1240. unique:=false;
  1241. for i:=1 to length(ps) do
  1242. if ps[i] in AllowDirectorySeparators then
  1243. begin
  1244. if not unique then
  1245. begin
  1246. uniquestring(ps);
  1247. p:=pchar(ps);
  1248. unique:=true;
  1249. end;
  1250. p[i-1]:=DirectorySeparator;
  1251. end;
  1252. end;
  1253. procedure DoDirSeparators(var ps:UnicodeString);
  1254. var
  1255. i : longint;
  1256. p : pwidechar;
  1257. unique : boolean;
  1258. begin
  1259. unique:=false;
  1260. for i:=1 to length(ps) do
  1261. if ps[i] in AllowDirectorySeparators then
  1262. begin
  1263. if not unique then
  1264. begin
  1265. uniquestring(ps);
  1266. p:=pwidechar(ps);
  1267. unique:=true;
  1268. end;
  1269. p[i-1]:=DirectorySeparator;
  1270. end;
  1271. end;
  1272. {$endif FPC_HAS_FEATURE_FILEIO}
  1273. { OS dependent low level file functions }
  1274. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1275. {$i sysfile.inc}
  1276. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1277. {$ifdef FPC_ANSI_TEXTFILEREC}
  1278. procedure do_open(var f; p: pansichar; flags: longint; pchangeable: boolean);
  1279. var
  1280. u: UnicodeString;
  1281. begin
  1282. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1283. do_open(f,pwidechar(u),flags,true);
  1284. end;
  1285. procedure do_erase(p: pansichar; pchangeable: boolean);
  1286. var
  1287. u: UnicodeString;
  1288. begin
  1289. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1290. do_erase(pwidechar(u),true);
  1291. end;
  1292. procedure do_rename(src, dst: pansichar; srcchangeable, dstchangeable: boolean);
  1293. var
  1294. usrc, udst: UnicodeString;
  1295. begin
  1296. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1297. widestringmanager.Ansi2UnicodeMoveProc(dst,DefaultFileSystemCodePage,udst,length(dst));
  1298. do_rename(pwidechar(usrc),pwidechar(udst),true,true);
  1299. end;
  1300. procedure do_rename(src: pansichar; dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1301. var
  1302. usrc: UnicodeString;
  1303. begin
  1304. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1305. do_rename(pwidechar(usrc),dst,true,dstchangeable);
  1306. end;
  1307. {$endif FPC_ANSI_TEXTFILEREC}
  1308. {$endif not FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1309. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1310. {$ifndef FPC_ANSI_TEXTFILEREC}
  1311. procedure do_open(var f; p: pwidechar; flags: longint; pchangeable: boolean);
  1312. var
  1313. s: RawByteString;
  1314. begin
  1315. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1316. do_open(f,pansichar(s),flags,true);
  1317. end;
  1318. procedure do_erase(p: pwidechar; pchangeable: boolean);
  1319. var
  1320. s: RawByteString;
  1321. begin
  1322. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1323. do_erase(pansichar(s),true);
  1324. end;
  1325. procedure do_rename(src, dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1326. var
  1327. rsrc, rdst: RawByteString;
  1328. begin
  1329. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1330. widestringmanager.Unicode2AnsiMoveProc(dst,rdst,DefaultFileSystemCodePage,length(dst));
  1331. do_rename(pansichar(rsrc),pansichar(rdst),true,true);
  1332. end;
  1333. procedure do_rename(src: pwidechar; dst: pansichar; srcchangeable, dstchangeable: boolean);
  1334. var
  1335. rsrc: RawByteString;
  1336. begin
  1337. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1338. do_rename(pansichar(rsrc),dst,true,dstchangeable);
  1339. end;
  1340. {$endif not FPC_ANSI_TEXTFILEREC}
  1341. {$endif not FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1342. {$endif FPC_HAS_FEATURE_FILEIO}
  1343. { Text file }
  1344. {$i text.inc}
  1345. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1346. { Untyped file }
  1347. {$i file.inc}
  1348. { Typed file }
  1349. {$i typefile.inc}
  1350. {$endif FPC_HAS_FEATURE_FILEIO}
  1351. {*****************************************************************************
  1352. Directory Handling
  1353. *****************************************************************************}
  1354. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1355. { OS dependent dir functions }
  1356. {$i sysdir.inc}
  1357. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1358. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1359. procedure do_getdir(drivenr : byte;var dir : rawbytestring);
  1360. var
  1361. u: unicodestring;
  1362. begin
  1363. Do_getdir(drivenr,u);
  1364. widestringmanager.Unicode2AnsiMoveProc(pwidechar(u),dir,DefaultRTLFileSystemCodePage,length(u));
  1365. end;
  1366. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1367. Procedure MkDir(Const s: RawByteString);[IOCheck];
  1368. Begin
  1369. If (s='') or (InOutRes <> 0) then
  1370. exit;
  1371. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1372. Do_mkdir(ToSingleByteFileSystemEncodedFileName(S));
  1373. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1374. Do_mkdir(S);
  1375. {$endif}
  1376. end;
  1377. Procedure RmDir(Const s: RawByteString);[IOCheck];
  1378. Begin
  1379. If (s='') or (InOutRes <> 0) then
  1380. exit;
  1381. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1382. Do_rmdir(ToSingleByteFileSystemEncodedFileName(S));
  1383. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1384. Do_rmdir(S);
  1385. {$endif}
  1386. End;
  1387. Procedure ChDir(Const s: RawByteString);[IOCheck];
  1388. Begin
  1389. If (s='') or (InOutRes <> 0) then
  1390. exit;
  1391. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1392. Do_chdir(ToSingleByteFileSystemEncodedFileName(S));
  1393. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1394. Do_chdir(S);
  1395. {$endif}
  1396. End;
  1397. Procedure getdir(drivenr:byte;Var dir:rawbytestring);
  1398. begin
  1399. Do_getdir(drivenr,dir);
  1400. { we should return results in the DefaultRTLFileSystemCodePage -> convert if
  1401. necessary }
  1402. setcodepage(dir,DefaultRTLFileSystemCodePage,true);
  1403. end;
  1404. { the generic shortstring ones are only implemented elsewhere for systems *not*
  1405. supporting ansi/unicodestrings; for now assume there are no systems that
  1406. support unicodestrings but not ansistrings }
  1407. { avoid double string conversions }
  1408. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1409. function GetDirStrFromShortstring(const s: shortstring): RawByteString;
  1410. begin
  1411. GetDirStrFromShortstring:=ToSingleByteFileSystemEncodedFileName(ansistring(s));
  1412. end;
  1413. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1414. function GetDirStrFromShortstring(const s: shortstring): UnicodeString;
  1415. begin
  1416. GetDirStrFromShortstring:=s;
  1417. end;
  1418. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1419. Procedure MkDir(Const s: shortstring);[IOCheck];
  1420. Begin
  1421. If (s='') or (InOutRes <> 0) then
  1422. exit;
  1423. Do_mkdir(GetDirStrFromShortstring(S));
  1424. End;
  1425. Procedure RmDir(Const s: shortstring);[IOCheck];
  1426. Begin
  1427. If (s='') or (InOutRes <> 0) then
  1428. exit;
  1429. Do_rmdir(GetDirStrFromShortstring(S));
  1430. End;
  1431. Procedure ChDir(Const s: shortstring);[IOCheck];
  1432. Begin
  1433. If (s='') or (InOutRes <> 0) then
  1434. exit;
  1435. Do_chdir(GetDirStrFromShortstring(S));
  1436. End;
  1437. Procedure getdir(drivenr:byte;Var dir:shortstring);
  1438. var
  1439. s: rawbytestring;
  1440. begin
  1441. Do_getdir(drivenr,s);
  1442. if length(s)<=high(dir) then
  1443. dir:=s
  1444. else
  1445. inoutres:=3;
  1446. end;
  1447. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1448. {$if defined(FPC_HAS_FEATURE_WIDESTRINGS)}
  1449. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1450. { overloads required for mkdir/rmdir/chdir to ensure that the string is
  1451. converted to the right code page }
  1452. procedure do_mkdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1453. begin
  1454. do_mkdir(ToSingleByteFileSystemEncodedFileName(s));
  1455. end;
  1456. procedure do_rmdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1457. begin
  1458. do_rmdir(ToSingleByteFileSystemEncodedFileName(s));
  1459. end;
  1460. procedure do_chdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1461. begin
  1462. do_chdir(ToSingleByteFileSystemEncodedFileName(s));
  1463. end;
  1464. procedure do_getdir(drivenr : byte;var dir : unicodestring);
  1465. var
  1466. s: rawbytestring;
  1467. begin
  1468. Do_getdir(drivenr,s);
  1469. dir:=s;
  1470. end;
  1471. {$endif FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1472. Procedure MkDir(Const s: UnicodeString);[IOCheck];
  1473. Begin
  1474. if (s='') or (InOutRes <> 0) then
  1475. exit;
  1476. Do_mkdir(S);
  1477. End;
  1478. Procedure RmDir(Const s: UnicodeString);[IOCheck];
  1479. Begin
  1480. if (s='') or (InOutRes <> 0) then
  1481. exit;
  1482. Do_rmdir(S);
  1483. End;
  1484. Procedure ChDir(Const s: UnicodeString);[IOCheck];
  1485. Begin
  1486. if (s='') or (InOutRes <> 0) then
  1487. exit;
  1488. Do_chdir(S);
  1489. End;
  1490. Procedure getdir(drivenr:byte;Var dir:unicodestring);
  1491. begin
  1492. Do_getdir(drivenr,dir);
  1493. end;
  1494. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  1495. {$endif FPC_HAS_FEATURE_FILEIO}
  1496. {*****************************************************************************
  1497. Resources support
  1498. *****************************************************************************}
  1499. {$i sysres.inc}
  1500. const
  1501. CtrlBreakHandler: TCtrlBreakHandler = nil;
  1502. {$IFNDEF FPC_HAS_SETCTRLBREAKHANDLER}
  1503. (* It is possible to provide platform specific implementation performing *)
  1504. (* special initialization; default implementation just sets the procedural *)
  1505. (* variable to make it available for use from the exception handler. *)
  1506. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  1507. begin
  1508. (* Return either nil or previous handler *)
  1509. SysSetCtrlBreakHandler := CtrlBreakHandler;
  1510. CtrlBreakHandler := Handler;
  1511. end;
  1512. {$ENDIF FPC_HAS_SETCTRLBREAKHANDLER}