system.inc 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800
  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(CPUARMV7EM) or defined(CPUARMV7M)}
  186. {$i thumb2.inc} { Case dependent, don't change }
  187. {$else}
  188. {$if defined(CPUARMV6M)}
  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;bp,addr : Pointer);
  932. var
  933. i : Longint;
  934. prevbp : 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. prevbp:=bp-1;
  944. prevaddr:=nil;
  945. i:=0;
  946. is_dev:=do_isdevice(textrec(f).Handle);
  947. while bp > prevbp Do
  948. Begin
  949. caller_addr := get_caller_addr(bp,addr);
  950. caller_frame := get_caller_frame(bp,addr);
  951. if (caller_addr=nil) then
  952. break;
  953. Writeln(f,BackTraceStrFunc(caller_addr));
  954. if (caller_frame=nil) then
  955. break;
  956. Inc(i);
  957. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  958. break;
  959. prevbp:=bp;
  960. prevaddr:=addr;
  961. bp:=caller_frame;
  962. addr:=caller_addr;
  963. End;
  964. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  965. except
  966. { prevent endless dump if an exception occured }
  967. end;
  968. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  969. End;
  970. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  971. procedure DumpExceptionBackTrace(var f:text);
  972. var
  973. FrameNumber,
  974. FrameCount : longint;
  975. Frames : PPointer;
  976. begin
  977. if RaiseList=nil then
  978. exit;
  979. WriteLn(f,BackTraceStrFunc(RaiseList^.Addr));
  980. FrameCount:=RaiseList^.Framecount;
  981. Frames:=RaiseList^.Frames;
  982. for FrameNumber := 0 to FrameCount-1 do
  983. WriteLn(f,BackTraceStrFunc(Frames[FrameNumber]));
  984. end;
  985. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  986. {$ifdef FPC_HAS_FEATURE_HEAP}
  987. Type
  988. PExitProcInfo = ^TExitProcInfo;
  989. TExitProcInfo = Record
  990. Next : PExitProcInfo;
  991. SaveExit : CodePointer;
  992. Proc : TProcedure;
  993. End;
  994. const
  995. ExitProcList: PExitProcInfo = nil;
  996. Procedure DoExitProc;
  997. var
  998. P : PExitProcInfo;
  999. Proc : TProcedure;
  1000. Begin
  1001. P:=ExitProcList;
  1002. ExitProcList:=P^.Next;
  1003. ExitProc:=P^.SaveExit;
  1004. Proc:=P^.Proc;
  1005. DisPose(P);
  1006. Proc();
  1007. End;
  1008. Procedure AddExitProc(Proc: TProcedure);
  1009. var
  1010. P : PExitProcInfo;
  1011. Begin
  1012. New(P);
  1013. P^.Next:=ExitProcList;
  1014. P^.SaveExit:=ExitProc;
  1015. P^.Proc:=Proc;
  1016. ExitProcList:=P;
  1017. ExitProc:=@DoExitProc;
  1018. End;
  1019. {$endif FPC_HAS_FEATURE_HEAP}
  1020. {$ifdef FPC_HAS_FEATURE_HEAP}
  1021. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppchar; // const ?
  1022. // Extra allocate reserveentries pchar's at the beginning (default param=0 after 1.0.x ?)
  1023. // Note: for internal use by skilled programmers only
  1024. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  1025. var p : ppchar;
  1026. i : LongInt;
  1027. begin
  1028. if High(s)<Low(s) Then Exit(NIL);
  1029. Getmem(p,sizeof(pchar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  1030. // for cmd
  1031. if p=nil then
  1032. begin
  1033. {$ifdef xunix}
  1034. fpseterrno(ESysEnomem);
  1035. {$endif}
  1036. exit(NIL);
  1037. end;
  1038. for i:=low(s) to high(s) do
  1039. p[i+Reserveentries]:=pchar(s[i]);
  1040. p[high(s)+1+Reserveentries]:=nil;
  1041. ArrayStringToPPchar:=p;
  1042. end;
  1043. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppchar;
  1044. {
  1045. Create a PPChar to structure of pchars which are the arguments specified
  1046. in the string S. Especially useful for creating an ArgV for Exec-calls
  1047. }
  1048. begin
  1049. StringToPPChar:=StringToPPChar(PChar(S),ReserveEntries);
  1050. end;
  1051. Function StringToPPChar(S: PChar;ReserveEntries:integer):ppchar;
  1052. var
  1053. i,nr : longint;
  1054. Buf : ^char;
  1055. p : ppchar;
  1056. begin
  1057. buf:=s;
  1058. nr:=1;
  1059. while (buf^<>#0) do // count nr of args
  1060. begin
  1061. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1062. inc(buf);
  1063. inc(nr);
  1064. if buf^='"' Then // quotes argument?
  1065. begin
  1066. inc(buf);
  1067. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1068. inc(buf);
  1069. if buf^='"' then // skip closing quote.
  1070. inc(buf);
  1071. end
  1072. else
  1073. begin // else std
  1074. while not (buf^ in [' ',#0,#9,#10]) do
  1075. inc(buf);
  1076. end;
  1077. end;
  1078. getmem(p,(ReserveEntries+nr)*sizeof(pchar));
  1079. StringToPPChar:=p;
  1080. if p=nil then
  1081. begin
  1082. {$ifdef xunix}
  1083. fpseterrno(ESysEnomem);
  1084. {$endif}
  1085. exit;
  1086. end;
  1087. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  1088. buf:=s;
  1089. while (buf^<>#0) do
  1090. begin
  1091. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1092. begin
  1093. buf^:=#0;
  1094. inc(buf);
  1095. end;
  1096. if buf^='"' Then // quotes argument?
  1097. begin
  1098. inc(buf);
  1099. p^:=buf;
  1100. inc(p);
  1101. p^:=nil;
  1102. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1103. inc(buf);
  1104. if buf^='"' then // skip closing quote.
  1105. begin
  1106. buf^:=#0;
  1107. inc(buf);
  1108. end;
  1109. end
  1110. else
  1111. begin
  1112. p^:=buf;
  1113. inc(p);
  1114. p^:=nil;
  1115. while not (buf^ in [' ',#0,#9,#10]) do
  1116. inc(buf);
  1117. end;
  1118. end;
  1119. end;
  1120. {$endif FPC_HAS_FEATURE_HEAP}
  1121. {*****************************************************************************
  1122. Abstract/Assert support.
  1123. *****************************************************************************}
  1124. procedure fpc_emptymethod;[public,alias : 'FPC_EMPTYMETHOD'];
  1125. begin
  1126. end;
  1127. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  1128. begin
  1129. If pointer(AbstractErrorProc)<>nil then
  1130. AbstractErrorProc();
  1131. HandleErrorAddrFrameInd(211,get_pc_addr,get_frame);
  1132. end;
  1133. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;
  1134. ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  1135. begin
  1136. if pointer(AssertErrorProc)<>nil then
  1137. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  1138. else
  1139. HandleErrorAddrFrameInd(227,get_pc_addr,get_frame);
  1140. end;
  1141. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  1142. begin
  1143. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1144. If msg='' then
  1145. write(stderr,'Assertion failed')
  1146. else
  1147. write(stderr,msg);
  1148. Writeln(stderr,' (',FName,', line ',LineNo,').');
  1149. Writeln(stderr,'');
  1150. Halt(227);
  1151. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1152. end;
  1153. {*****************************************************************************
  1154. SetJmp/LongJmp support.
  1155. *****************************************************************************}
  1156. {$i setjump.inc}
  1157. {$pop} //{$I-,R-,Q-} before 'procedure fpc_rangeerror'
  1158. {*****************************************************************************
  1159. Heap
  1160. *****************************************************************************}
  1161. {$i sysheap.inc}
  1162. {$i heap.inc}
  1163. {*****************************************************************************
  1164. Thread support
  1165. *****************************************************************************}
  1166. {$ifdef FPC_HAS_FEATURE_THREADING}
  1167. { Generic threadmanager }
  1168. {$i thread.inc}
  1169. { Generic threadvar support }
  1170. {$i threadvr.inc}
  1171. {$ifdef DISABLE_NO_THREAD_MANAGER}
  1172. { OS Dependent implementation }
  1173. {$i systhrd.inc}
  1174. {$endif DISABLE_NO_THREAD_MANAGER}
  1175. {$endif FPC_HAS_FEATURE_THREADING}
  1176. {*****************************************************************************
  1177. File Handling
  1178. *****************************************************************************}
  1179. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1180. { Allow slash and backslash as separators }
  1181. procedure DoDirSeparators(var p: pchar; inplace: boolean = true);
  1182. var
  1183. i : longint;
  1184. len : sizeint;
  1185. newp : pchar;
  1186. begin
  1187. len:=length(p);
  1188. newp:=nil;
  1189. for i:=0 to len do
  1190. if p[i] in AllowDirectorySeparators then
  1191. begin
  1192. if not inplace and
  1193. not assigned(newp) then
  1194. begin
  1195. getmem(newp,len+1);
  1196. move(p^,newp^,len+1);
  1197. p:=newp;
  1198. end;
  1199. p[i]:=DirectorySeparator;
  1200. end;
  1201. end;
  1202. procedure DoDirSeparators(var p: pwidechar; inplace: boolean = true);
  1203. var
  1204. i : longint;
  1205. len : sizeint;
  1206. newp : pwidechar;
  1207. begin
  1208. len:=length(p);
  1209. newp:=nil;
  1210. for i:=0 to len do
  1211. if (ord(p[i])<255) and
  1212. (ansichar(ord(p[i])) in AllowDirectorySeparators) then
  1213. begin
  1214. if not inplace and
  1215. not assigned(newp) then
  1216. begin
  1217. getmem(newp,(len+1)*2);
  1218. move(p^,newp^,(len+1)*2);
  1219. p:=newp;
  1220. end;
  1221. p[i]:=DirectorySeparator;
  1222. end;
  1223. end;
  1224. procedure DoDirSeparators(var p:shortstring);
  1225. var
  1226. i : longint;
  1227. begin
  1228. for i:=1 to length(p) do
  1229. if p[i] in AllowDirectorySeparators then
  1230. p[i]:=DirectorySeparator;
  1231. end;
  1232. procedure DoDirSeparators(var ps:RawByteString);
  1233. var
  1234. i : longint;
  1235. p : pchar;
  1236. unique : boolean;
  1237. begin
  1238. unique:=false;
  1239. for i:=1 to length(ps) do
  1240. if ps[i] in AllowDirectorySeparators then
  1241. begin
  1242. if not unique then
  1243. begin
  1244. uniquestring(ps);
  1245. p:=pchar(ps);
  1246. unique:=true;
  1247. end;
  1248. p[i-1]:=DirectorySeparator;
  1249. end;
  1250. end;
  1251. procedure DoDirSeparators(var ps:UnicodeString);
  1252. var
  1253. i : longint;
  1254. p : pwidechar;
  1255. unique : boolean;
  1256. begin
  1257. unique:=false;
  1258. for i:=1 to length(ps) do
  1259. if ps[i] in AllowDirectorySeparators then
  1260. begin
  1261. if not unique then
  1262. begin
  1263. uniquestring(ps);
  1264. p:=pwidechar(ps);
  1265. unique:=true;
  1266. end;
  1267. p[i-1]:=DirectorySeparator;
  1268. end;
  1269. end;
  1270. {$endif FPC_HAS_FEATURE_FILEIO}
  1271. { OS dependent low level file functions }
  1272. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1273. {$i sysfile.inc}
  1274. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1275. {$ifdef FPC_ANSI_TEXTFILEREC}
  1276. procedure do_open(var f; p: pansichar; flags: longint; pchangeable: boolean);
  1277. var
  1278. u: UnicodeString;
  1279. begin
  1280. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1281. do_open(f,pwidechar(u),flags,true);
  1282. end;
  1283. procedure do_erase(p: pansichar; pchangeable: boolean);
  1284. var
  1285. u: UnicodeString;
  1286. begin
  1287. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1288. do_erase(pwidechar(u),true);
  1289. end;
  1290. procedure do_rename(src, dst: pansichar; srcchangeable, dstchangeable: boolean);
  1291. var
  1292. usrc, udst: UnicodeString;
  1293. begin
  1294. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1295. widestringmanager.Ansi2UnicodeMoveProc(dst,DefaultFileSystemCodePage,udst,length(dst));
  1296. do_rename(pwidechar(usrc),pwidechar(udst),true,true);
  1297. end;
  1298. procedure do_rename(src: pansichar; dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1299. var
  1300. usrc: UnicodeString;
  1301. begin
  1302. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1303. do_rename(pwidechar(usrc),dst,true,dstchangeable);
  1304. end;
  1305. {$endif FPC_ANSI_TEXTFILEREC}
  1306. {$endif not FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1307. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1308. {$ifndef FPC_ANSI_TEXTFILEREC}
  1309. procedure do_open(var f; p: pwidechar; flags: longint; pchangeable: boolean);
  1310. var
  1311. s: RawByteString;
  1312. begin
  1313. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1314. do_open(f,pansichar(s),flags,true);
  1315. end;
  1316. procedure do_erase(p: pwidechar; pchangeable: boolean);
  1317. var
  1318. s: RawByteString;
  1319. begin
  1320. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1321. do_erase(pansichar(s),true);
  1322. end;
  1323. procedure do_rename(src, dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1324. var
  1325. rsrc, rdst: RawByteString;
  1326. begin
  1327. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1328. widestringmanager.Unicode2AnsiMoveProc(dst,rdst,DefaultFileSystemCodePage,length(dst));
  1329. do_rename(pansichar(rsrc),pansichar(rdst),true,true);
  1330. end;
  1331. procedure do_rename(src: pwidechar; dst: pansichar; srcchangeable, dstchangeable: boolean);
  1332. var
  1333. rsrc: RawByteString;
  1334. begin
  1335. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1336. do_rename(pansichar(rsrc),dst,true,dstchangeable);
  1337. end;
  1338. {$endif not FPC_ANSI_TEXTFILEREC}
  1339. {$endif not FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1340. {$endif FPC_HAS_FEATURE_FILEIO}
  1341. { Text file }
  1342. {$i text.inc}
  1343. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1344. { Untyped file }
  1345. {$i file.inc}
  1346. { Typed file }
  1347. {$i typefile.inc}
  1348. {$endif FPC_HAS_FEATURE_FILEIO}
  1349. {*****************************************************************************
  1350. Directory Handling
  1351. *****************************************************************************}
  1352. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1353. { OS dependent dir functions }
  1354. {$i sysdir.inc}
  1355. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1356. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1357. procedure do_getdir(drivenr : byte;var dir : rawbytestring);
  1358. var
  1359. u: unicodestring;
  1360. begin
  1361. Do_getdir(drivenr,u);
  1362. widestringmanager.Unicode2AnsiMoveProc(pwidechar(u),dir,DefaultRTLFileSystemCodePage,length(u));
  1363. end;
  1364. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1365. Procedure MkDir(Const s: RawByteString);[IOCheck];
  1366. Begin
  1367. If (s='') or (InOutRes <> 0) then
  1368. exit;
  1369. Do_mkdir(S);
  1370. End;
  1371. Procedure RmDir(Const s: RawByteString);[IOCheck];
  1372. Begin
  1373. If (s='') or (InOutRes <> 0) then
  1374. exit;
  1375. Do_rmdir(S);
  1376. End;
  1377. Procedure ChDir(Const s: RawByteString);[IOCheck];
  1378. Begin
  1379. If (s='') or (InOutRes <> 0) then
  1380. exit;
  1381. Do_chdir(S);
  1382. End;
  1383. Procedure getdir(drivenr:byte;Var dir:rawbytestring);
  1384. begin
  1385. Do_getdir(drivenr,dir);
  1386. { we should return results in the DefaultRTLFileSystemCodePage -> convert if
  1387. necessary }
  1388. setcodepage(dir,DefaultRTLFileSystemCodePage,true);
  1389. end;
  1390. { the generic shortstring ones are only implemented elsewhere for systems *not*
  1391. supporting ansi/unicodestrings; for now assume there are no systems that
  1392. support unicodestrings but not ansistrings }
  1393. { avoid double string conversions }
  1394. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1395. function GetDirStrFromShortstring(const s: shortstring): RawByteString;
  1396. begin
  1397. GetDirStrFromShortstring:=ToSingleByteFileSystemEncodedFileName(ansistring(s));
  1398. end;
  1399. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1400. function GetDirStrFromShortstring(const s: shortstring): UnicodeString;
  1401. begin
  1402. GetDirStrFromShortstring:=s;
  1403. end;
  1404. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1405. Procedure MkDir(Const s: shortstring);[IOCheck];
  1406. Begin
  1407. If (s='') or (InOutRes <> 0) then
  1408. exit;
  1409. Do_mkdir(GetDirStrFromShortstring(S));
  1410. End;
  1411. Procedure RmDir(Const s: shortstring);[IOCheck];
  1412. Begin
  1413. If (s='') or (InOutRes <> 0) then
  1414. exit;
  1415. Do_rmdir(GetDirStrFromShortstring(S));
  1416. End;
  1417. Procedure ChDir(Const s: shortstring);[IOCheck];
  1418. Begin
  1419. If (s='') or (InOutRes <> 0) then
  1420. exit;
  1421. Do_chdir(GetDirStrFromShortstring(S));
  1422. End;
  1423. Procedure getdir(drivenr:byte;Var dir:shortstring);
  1424. var
  1425. s: rawbytestring;
  1426. begin
  1427. Do_getdir(drivenr,s);
  1428. if length(s)<=high(dir) then
  1429. dir:=s
  1430. else
  1431. inoutres:=3;
  1432. end;
  1433. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1434. {$if defined(FPC_HAS_FEATURE_WIDESTRINGS)}
  1435. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1436. { overloads required for mkdir/rmdir/chdir to ensure that the string is
  1437. converted to the right code page }
  1438. procedure do_mkdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1439. begin
  1440. do_mkdir(ToSingleByteFileSystemEncodedFileName(s));
  1441. end;
  1442. procedure do_rmdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1443. begin
  1444. do_rmdir(ToSingleByteFileSystemEncodedFileName(s));
  1445. end;
  1446. procedure do_chdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1447. begin
  1448. do_chdir(ToSingleByteFileSystemEncodedFileName(s));
  1449. end;
  1450. procedure do_getdir(drivenr : byte;var dir : unicodestring);
  1451. var
  1452. s: rawbytestring;
  1453. begin
  1454. Do_getdir(drivenr,s);
  1455. dir:=s;
  1456. end;
  1457. {$endif FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1458. Procedure MkDir(Const s: UnicodeString);[IOCheck];
  1459. Begin
  1460. if (s='') or (InOutRes <> 0) then
  1461. exit;
  1462. Do_mkdir(S);
  1463. End;
  1464. Procedure RmDir(Const s: UnicodeString);[IOCheck];
  1465. Begin
  1466. if (s='') or (InOutRes <> 0) then
  1467. exit;
  1468. Do_rmdir(S);
  1469. End;
  1470. Procedure ChDir(Const s: UnicodeString);[IOCheck];
  1471. Begin
  1472. if (s='') or (InOutRes <> 0) then
  1473. exit;
  1474. Do_chdir(S);
  1475. End;
  1476. Procedure getdir(drivenr:byte;Var dir:unicodestring);
  1477. begin
  1478. Do_getdir(drivenr,dir);
  1479. end;
  1480. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  1481. {$endif FPC_HAS_FEATURE_FILEIO}
  1482. {*****************************************************************************
  1483. Resources support
  1484. *****************************************************************************}
  1485. {$i sysres.inc}
  1486. const
  1487. CtrlBreakHandler: TCtrlBreakHandler = nil;
  1488. {$IFNDEF FPC_HAS_SETCTRLBREAKHANDLER}
  1489. (* It is possible to provide platform specific implementation performing *)
  1490. (* special initialization; default implementation just sets the procedural *)
  1491. (* variable to make it available for use from the exception handler. *)
  1492. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  1493. begin
  1494. (* Return either nil or previous handler *)
  1495. SysSetCtrlBreakHandler := CtrlBreakHandler;
  1496. CtrlBreakHandler := Handler;
  1497. end;
  1498. {$ENDIF FPC_HAS_SETCTRLBREAKHANDLER}