system.inc 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237
  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. { ObjpasInt is the integer type, equivalent to Objpas.Integer (the Integer
  11. type in ObjFpc and Delphi modes). It is defined here for use in the
  12. implementation part of the System unit. }
  13. {$ifdef CPU16}
  14. type
  15. ObjpasInt = SmallInt;
  16. {$else CPU16}
  17. type
  18. ObjpasInt = LongInt;
  19. {$endif CPU16}
  20. {****************************************************************************
  21. Local types
  22. ****************************************************************************}
  23. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  24. {$if High(errorcode)<>maxExitCode}
  25. {$define FPC_LIMITED_EXITCODE}
  26. {$endif}
  27. {$endif FPC_HAS_FEATURE_EXITCODE}
  28. Procedure HandleError (Errno : TExitCode); external name 'FPC_HANDLEERROR';
  29. Procedure HandleErrorFrame (Errno : TExitCode;frame : Pointer); forward;
  30. Procedure HandleErrorAddrFrame (Errno : TExitCode;addr : CodePointer; frame : Pointer); forward;
  31. Procedure HandleErrorAddrFrameInd (Errno : TExitCode;addr : CodePointer; frame : Pointer); forward;
  32. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  33. type
  34. FileFunc = Procedure(var t : TextRec);
  35. {$endif FPC_HAS_FEATURE_TEXTIO}
  36. const
  37. {$if defined(CPUAVR)}
  38. STACK_MARGIN_MAX = 64; { Stack size margin for stack checking }
  39. {$elseif defined(CPUZ80)}
  40. STACK_MARGIN_MAX = 64; { Stack size margin for stack checking }
  41. {$elseif defined(CPULOONGARCH64)}
  42. STACK_MARGIN_MAX = 65536; { Stack size margin for stack checking }
  43. {$elseif defined(CPUX86_64)}
  44. STACK_MARGIN_MAX = 32768; { Stack size margin for stack checking }
  45. {$else}
  46. STACK_MARGIN_MAX = 16384; { Stack size margin for stack checking }
  47. {$endif}
  48. StackMargin: ptruint = STACK_MARGIN_MAX;
  49. { Random / Randomize constants }
  50. OldRandSeed : Cardinal = Cardinal(not Cardinal(0)); // see ReseedGlobalRNG and GlobalXsr128_32 initialization.
  51. { For Error Handling.}
  52. ErrorBase : Pointer = nil;public name 'FPC_ERRORBASE';
  53. { Used by the ansi/widestrings and maybe also other things in the future }
  54. var
  55. { widechar, because also used by widestring -> pwidechar conversions }
  56. emptychar : widechar;public name 'FPC_EMPTYCHAR';
  57. {$ifndef FPC_NO_GENERIC_STACK_CHECK}
  58. { if the OS does the stack checking, we don't need any stklen from the
  59. main program }
  60. initialstklen : SizeUint{$ifndef FPC_HAS_INDIRECT_ENTRY_INFORMATION}; external name '__stklen';{$else} = 0;{$endif}
  61. {$endif FPC_NO_GENERIC_STACK_CHECK}
  62. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  63. EntryInformation: TEntryInformation;
  64. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  65. var
  66. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  67. {$ifdef FPC_HAS_RESSTRINITS}
  68. FPCResStrInitTables : Pointer;public name '_FPC_ResStrInitTables';
  69. {$endif FPC_HAS_RESSTRINITS}
  70. FPCResourceStringTables : Pointer;public name '_FPC_ResourceStringTables';
  71. FPCResLocation : Pointer;public name'_FPC_ResLocation';
  72. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  73. {$ifdef FPC_HAS_RESSTRINITS}
  74. FPCResStrInitTablesVar : record end; external name 'FPC_RESSTRINITTABLES';
  75. FPCResStrInitTables : Pointer = @FPCResStrInitTablesVar;public name '_FPC_ResStrInitTables';
  76. {$endif FPC_HAS_RESSTRINITS}
  77. FPCResourceStringTablesVar : record end; External Name 'FPC_RESOURCESTRINGTABLES';
  78. FPCResourceStringTables : Pointer = @FPCResourceStringTablesVar;public name '_FPC_ResourceStringTables';
  79. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  80. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  81. procedure SetupEntryInformation(constref info: TEntryInformation);[public,alias:'_FPC_SetupEntryInformation'];
  82. begin
  83. EntryInformation := info;
  84. FPCResStrInitTables := info.ResStrInitTables;
  85. FPCResourceStringTables := info.ResourceStringTables;
  86. FPCResLocation := info.ResLocation;
  87. {$ifdef FPC_SYSTEM_HAS_OSSETUPENTRYINFORMATION}
  88. OSSetupEntryInformation(info);
  89. {$endif FPC_SYSTEM_HAS_OSSETUPENTRYINFORMATION}
  90. end;
  91. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  92. {$if not defined(FPC_SYSTEM_FPU_CUSTOM_CONTROL_WORD) and not defined(FPUNONE) and not defined(FPC_SYSTEM_FPUCW_IMMUTABLE)}
  93. var
  94. { Control word of the fpu that determes which exceptions will be thrown and
  95. potentially other flags (precision, exception-happened flags, ... Used to
  96. initialise the FPU when starting a new thread (in SysResetFPU).
  97. Some platforms already have a legacy/existing global variable holding this
  98. information (FPC_SYSTEM_FPU_CUSTOM_CONTROL_WORD). In case of FPU_NONE,
  99. we don't support floating point at all. And in case of
  100. FPC_SYSTEM_FPUCW_IMMUTABLE, either the control word cannot be changed
  101. (e.g. wasm), or FPU operations are supported by only as softfloat }
  102. DefaultFPUControlWord: TNativeFPUControlWord;
  103. {$endif}
  104. { checks whether the given suggested size for the stack of the current
  105. thread is acceptable. If this is the case, returns it unaltered.
  106. Otherwise it should return an acceptable value.
  107. Operating systems that automatically expand their stack on demand, should
  108. simply return a very large value.
  109. Operating systems which do not have a possibility to retrieve stack size
  110. information, should simply return the given stklen value (This is the default
  111. implementation).
  112. }
  113. {$ifdef FPC_HAS_FEATURE_STACKCHECK}
  114. function CheckInitialStkLen(stklen : SizeUInt) : SizeUInt; forward;
  115. {$endif FPC_HAS_FEATURE_STACKCHECK}
  116. {*****************************************************************************
  117. OS dependent Helpers/Syscalls
  118. *****************************************************************************}
  119. { for some OSes do_isdevice is defined in sysos.inc, but for others (win32)
  120. it isn't, and is used before the actual definition is encountered }
  121. {$ifdef FPC_HAS_FEATURE_FILEIO}
  122. function do_isdevice(handle:thandle):boolean;forward;
  123. {$endif FPC_HAS_FEATURE_FILEIO}
  124. {$i sysos.inc}
  125. {****************************************************************************
  126. Include processor specific routines
  127. ****************************************************************************}
  128. {$ifdef FPC_USE_LIBC}
  129. {$ifdef USE_CPU_MOVE}
  130. { Avoid use of generic C code for move procedure }
  131. {$define FPC_SYSTEM_HAS_MOVE}
  132. {$endif}
  133. { Under Haiku, bcopy cause a problem when searching for include file
  134. in the compiler. So, we use the internal implementation for now
  135. under BeOS and Haiku. }
  136. {$ifndef BEOS}
  137. { prefer libc implementations over our own, as they're most likely faster }
  138. {$i cgeneric.inc}
  139. { is now declared as external reference to another routine in the interface }
  140. {$i cgenstr.inc}
  141. {$endif}
  142. {$ifdef USE_CPU_MOVE}
  143. { Avoid use of generic C code for move procedure }
  144. {$undef FPC_SYSTEM_HAS_MOVE}
  145. {$endif}
  146. {$endif FPC_USE_LIBC}
  147. {$ifdef cpui386}
  148. {$ifdef SYSPROCDEFINED}
  149. {$Error Can't determine processor type !}
  150. {$endif}
  151. {$i i386.inc} { Case dependent, don't change }
  152. {$define SYSPROCDEFINED}
  153. {$endif cpui386}
  154. {$ifdef cpui8086}
  155. {$ifdef SYSPROCDEFINED}
  156. {$Error Can't determine processor type !}
  157. {$endif}
  158. {$i i8086.inc} { Case dependent, don't change }
  159. {$define SYSPROCDEFINED}
  160. {$endif cpui8086}
  161. {$ifdef cpum68k}
  162. {$ifdef SYSPROCDEFINED}
  163. {$Error Can't determine processor type !}
  164. {$endif}
  165. {$i m68k.inc} { Case dependent, don't change }
  166. {$define SYSPROCDEFINED}
  167. {$endif cpum68k}
  168. {$ifdef cpux86_64}
  169. {$ifdef SYSPROCDEFINED}
  170. {$Error Can't determine processor type !}
  171. {$endif}
  172. {$i x86_64.inc} { Case dependent, don't change }
  173. {$define SYSPROCDEFINED}
  174. {$endif cpux86_64}
  175. {$ifdef cpupowerpc32}
  176. {$ifdef SYSPROCDEFINED}
  177. {$Error Can't determine processor type !}
  178. {$endif}
  179. {$i powerpc.inc} { Case dependent, don't change }
  180. {$define SYSPROCDEFINED}
  181. {$endif cpupowerpc32}
  182. {$ifdef cpupowerpc64}
  183. {$ifdef SYSPROCDEFINED}
  184. {$Error Can't determine processor type !}
  185. {$endif}
  186. {$i powerpc64.inc} { Case dependent, don't change }
  187. {$define SYSPROCDEFINED}
  188. {$endif cpupowerpc64}
  189. {$ifdef cpualpha}
  190. {$ifdef SYSPROCDEFINED}
  191. {$Error Can't determine processor type !}
  192. {$endif}
  193. {$i alpha.inc} { Case dependent, don't change }
  194. {$define SYSPROCDEFINED}
  195. {$endif cpualpha}
  196. {$ifdef cpuiA64}
  197. {$ifdef SYSPROCDEFINED}
  198. {$Error Can't determine processor type !}
  199. {$endif}
  200. {$i ia64.inc} { Case dependent, don't change }
  201. {$define SYSPROCDEFINED}
  202. {$endif cpuiA64}
  203. {$ifdef cpusparc}
  204. {$ifdef SYSPROCDEFINED}
  205. {$Error Can't determine processor type !}
  206. {$endif}
  207. {$i sparc.inc} { Case dependent, don't change }
  208. {$define SYSPROCDEFINED}
  209. {$endif cpusparc}
  210. {$ifdef cpusparc64}
  211. {$ifdef SYSPROCDEFINED}
  212. {$Error Can't determine processor type !}
  213. {$endif}
  214. {$i sparc64.inc} { Case dependent, don't change }
  215. {$define SYSPROCDEFINED}
  216. {$endif cpusparc64}
  217. {$ifdef cpuarm}
  218. {$ifdef SYSPROCDEFINED}
  219. {$Error Can't determine processor type !}
  220. {$endif}
  221. {$i armdefines.inc}
  222. {$if defined(CPUTHUMB2)}
  223. {$i thumb2.inc} { Case dependent, don't change }
  224. {$else}
  225. {$if defined(CPUTHUMB)}
  226. {$i thumb.inc} { Case dependent, don't change }
  227. {$else}
  228. {$i arm.inc} { Case dependent, don't change }
  229. {$endif}
  230. {$endif}
  231. {$define SYSPROCDEFINED}
  232. {$endif cpuarm}
  233. {$ifdef cpuavr}
  234. {$ifdef SYSPROCDEFINED}
  235. {$Error Can't determine processor type !}
  236. {$endif}
  237. {$i avr.inc} { Case dependent, don't change }
  238. {$define SYSPROCDEFINED}
  239. {$endif cpuavr}
  240. {$ifdef cpumipsel}
  241. {$ifdef SYSPROCDEFINED}
  242. {$Error Can't determine processor type !}
  243. {$endif}
  244. { there is no mipsel.inc, we use mips.inc instead }
  245. {$i mips.inc} { Case dependent, don't change }
  246. {$define SYSPROCDEFINED}
  247. {$endif cpumipsel}
  248. {$ifdef cpumipseb}
  249. {$ifdef SYSPROCDEFINED}
  250. {$Error Can't determine processor type !}
  251. {$endif}
  252. {$i mips.inc} { Case dependent, don't change }
  253. {$define SYSPROCDEFINED}
  254. {$endif cpumipseb}
  255. {$ifdef cpumips64el}
  256. {$ifdef SYSPROCDEFINED}
  257. {$Error Can't determine processor type !}
  258. {$endif}
  259. {$i mips64el.inc} { Case dependent, don't change }
  260. {$define SYSPROCDEFINED}
  261. {$endif cpumips64el}
  262. {$ifdef cpumips64eb}
  263. {$ifdef SYSPROCDEFINED}
  264. {$Error Can't determine processor type !}
  265. {$endif}
  266. {$i mips64.inc} { Case dependent, don't change }
  267. {$define SYSPROCDEFINED}
  268. {$endif cpumips64eb}
  269. {$ifdef cpuaarch64}
  270. {$ifdef SYSPROCDEFINED}
  271. {$Error Can't determine processor type !}
  272. {$endif}
  273. {$i aarch64.inc} { Case dependent, don't change }
  274. {$define SYSPROCDEFINED}
  275. {$endif cpuaarch64}
  276. {$ifdef cpuriscv32}
  277. {$ifdef SYSPROCDEFINED}
  278. {$Error Can't determine processor type !}
  279. {$endif}
  280. {$i riscv32.inc} { Case dependent, don't change }
  281. {$define SYSPROCDEFINED}
  282. {$endif cpuriscv32}
  283. {$ifdef cpuriscv64}
  284. {$ifdef SYSPROCDEFINED}
  285. {$Error Can't determine processor type !}
  286. {$endif}
  287. {$i riscv64.inc} { Case dependent, don't change }
  288. {$define SYSPROCDEFINED}
  289. {$endif cpuriscv64}
  290. {$ifdef cpuxtensa}
  291. {$ifdef SYSPROCDEFINED}
  292. {$Error Can't determine processor type !}
  293. {$endif}
  294. {$i xtensa.inc} { Case dependent, don't change }
  295. {$define SYSPROCDEFINED}
  296. {$endif cpuxtensa}
  297. {$ifdef cpuz80}
  298. {$ifdef SYSPROCDEFINED}
  299. {$Error Can't determine processor type !}
  300. {$endif}
  301. {$i z80.inc} { Case dependent, don't change }
  302. {$define SYSPROCDEFINED}
  303. {$endif cpuz80}
  304. {$ifdef cpuwasm32}
  305. {$ifdef SYSPROCDEFINED}
  306. {$Error Can't determine processor type !}
  307. {$endif}
  308. {$i wasm32.inc} { Case dependent, don't change }
  309. {$define SYSPROCDEFINED}
  310. {$endif cpuwasm32}
  311. {$ifdef cpuloongarch64}
  312. {$ifdef SYSPROCDEFINED}
  313. {$Error Can't determine processor type !}
  314. {$endif}
  315. {$i loongarch64.inc} { Case dependent, don't change }
  316. {$define SYSPROCDEFINED}
  317. {$endif cpuloongarch64}
  318. {$ifdef cpumos6502}
  319. {$ifdef SYSPROCDEFINED}
  320. {$Error Can't determine processor type !}
  321. {$endif}
  322. {$i mos6502.inc} { Case dependent, don't change }
  323. {$define SYSPROCDEFINED}
  324. {$endif cpumos6502}
  325. {$ifndef SYSPROCDEFINED}
  326. {$Error Can't determine processor type !}
  327. {$endif}
  328. procedure fillchar(var x;count : {$ifdef FILLCHAR_HAS_SIZEUINT_COUNT}SizeUInt{$else}SizeInt{$endif};value : boolean);
  329. begin
  330. fillchar(x,count,byte(value));
  331. end;
  332. procedure fillchar(var x;count : {$ifdef FILLCHAR_HAS_SIZEUINT_COUNT}SizeUInt{$else}SizeInt{$endif};value : AnsiChar);
  333. begin
  334. fillchar(x,count,byte(value));
  335. end;
  336. procedure FillByte (var x;count : {$ifdef FILLCHAR_HAS_SIZEUINT_COUNT}SizeUInt{$else}SizeInt{$endif};value : byte );
  337. begin
  338. FillChar (X,Count,VALUE);
  339. end;
  340. function IndexChar(Const buf;len:SizeInt;b:AnsiChar):SizeInt;
  341. begin
  342. IndexChar:=IndexByte(Buf,Len,byte(B));
  343. end;
  344. function IndexChar(const buf; len: SizeInt; b: widechar): SizeInt;
  345. begin
  346. IndexChar:=IndexWord(buf,len,Word(b));
  347. end;
  348. function CompareChar(Const buf1,buf2;len:SizeInt):SizeInt;
  349. begin
  350. CompareChar:=CompareByte(buf1,buf2,len);
  351. end;
  352. procedure fpc_zeromem(p:pointer;len:sizeuint);
  353. begin
  354. FillChar(p^,len,0);
  355. end;
  356. procedure fpc_fillmem(out data;len:sizeuint;b : byte);
  357. begin
  358. FillChar(data,len,AnsiChar(b));
  359. end;
  360. { Include generic pascal only routines which are not defined in the processor
  361. specific include file }
  362. {$I generic.inc}
  363. {****************************************************************************
  364. Set Handling
  365. ****************************************************************************}
  366. { Include set support which is processor specific}
  367. {$i set.inc}
  368. { Include generic pascal routines for sets if the processor }
  369. { specific routines are not available. }
  370. {$i genset.inc}
  371. {****************************************************************************
  372. Math Routines
  373. ****************************************************************************}
  374. function Hi(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  375. begin
  376. Hi := b shr 4
  377. end;
  378. function Lo(b : byte): byte;{$ifdef SYSTEMINLINE}inline;{$endif}
  379. begin
  380. Lo := b and $0f
  381. end;
  382. Function Swap (X : Word) : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  383. Begin
  384. Swap := SwapEndian(X);
  385. End;
  386. Function Swap (X : Integer) : Integer;{$ifdef SYSTEMINLINE}inline;{$endif}
  387. Begin
  388. Swap := SwapEndian(X);
  389. End;
  390. Function Swap (X : Longint) : Longint;{$ifdef SYSTEMINLINE}inline;{$endif}
  391. Begin
  392. Swap:=(X shl 16) + (X shr 16);
  393. End;
  394. Function Swap (X : Cardinal) : Cardinal;{$ifdef SYSTEMINLINE}inline;{$endif}
  395. Begin
  396. Swap:=(X shl 16) + (X shr 16);
  397. End;
  398. Function Swap (X : QWord) : QWord;{$ifdef SYSTEMINLINE}inline;{$endif}
  399. Begin
  400. Swap:=(X shl 32) + (X shr 32);
  401. End;
  402. Function Swap (X : Int64) : Int64;{$ifdef SYSTEMINLINE}inline;{$endif}
  403. Begin
  404. Swap:=(X shl 32) + (X shr 32);
  405. End;
  406. {$ifdef SUPPORT_DOUBLE}
  407. operator := (b:real48) d:double;{$ifdef SYSTEMINLINE}inline;{$endif}
  408. begin
  409. D:=real2double(b);
  410. end;
  411. {$endif SUPPORT_DOUBLE}
  412. {$ifdef SUPPORT_EXTENDED}
  413. operator := (b:real48) e:extended;{$ifdef SYSTEMINLINE}inline;{$endif}
  414. begin
  415. e:=real2double(b);
  416. end;
  417. {$endif SUPPORT_EXTENDED}
  418. {$ifndef FPUNONE}
  419. {$ifdef FPC_USE_LIBC}
  420. { Include libc versions }
  421. {$i cgenmath.inc}
  422. {$endif FPC_USE_LIBC}
  423. { Include processor specific routines }
  424. {$I math.inc}
  425. { Include generic version }
  426. {$I genmath.inc}
  427. {$endif}
  428. {$i gencurr.inc}
  429. function aligntoptr(p : pointer) : pointer;inline;
  430. begin
  431. {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT}
  432. result:=align(p,sizeof(p));
  433. {$else FPC_REQUIRES_PROPER_ALIGNMENT}
  434. result:=p;
  435. {$endif FPC_REQUIRES_PROPER_ALIGNMENT}
  436. end;
  437. function aligntoqword(p : pointer) : pointer;inline;
  438. {$push}
  439. {$packrecords c}
  440. type
  441. TAlignCheck = record
  442. b : byte;
  443. q : qword;
  444. end;
  445. {$pop}
  446. begin
  447. {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT}
  448. result:=align(p,PtrInt(@TAlignCheck(nil^).q))
  449. {$else FPC_REQUIRES_PROPER_ALIGNMENT}
  450. result:=p;
  451. {$endif FPC_REQUIRES_PROPER_ALIGNMENT}
  452. end;
  453. function AlignTypeData(p : pointer) : pointer; inline;
  454. begin
  455. {$if defined(CPUM68K)}
  456. result := aligntoqword(p);
  457. {$else CPUM68K}
  458. result := aligntoptr(p);
  459. {$endif CPUM68K}
  460. end;
  461. {$if not defined(VER3_2)}
  462. type
  463. TRttiDataCommon =
  464. {$ifdef FPC_REQUIRES_PROPER_ALIGNMENT}
  465. packed
  466. {$endif}
  467. record
  468. Attrs: Pointer;
  469. end;
  470. {$endif not VER3_2}
  471. {****************************************************************************
  472. Subroutines for String handling
  473. ****************************************************************************}
  474. { Needs to be before RTTI handling }
  475. {$i sstrings.inc}
  476. { requires sstrings.inc for initval }
  477. {$I int64p.inc}
  478. {$I int64.inc}
  479. {Requires int64.inc, since that contains the VAL functions for int64 and qword}
  480. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  481. {$i astrings.inc}
  482. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  483. {$ifdef FPC_HAS_FEATURE_WIDESTRINGS}
  484. {$ifndef FPC_WIDESTRING_EQUAL_UNICODESTRING}
  485. {$i wstrings.inc}
  486. {$endif FPC_WIDESTRING_EQUAL_UNICODESTRING}
  487. {$i ustrings.inc}
  488. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  489. {****************************************************************************
  490. Run-Time Type Information (RTTI) declarations
  491. ****************************************************************************}
  492. {$ifdef FPC_HAS_FEATURE_RTTI}
  493. {$i rttidecl.inc}
  494. {$endif FPC_HAS_FEATURE_RTTI}
  495. {$i aliases.inc}
  496. {*****************************************************************************
  497. Dynamic Array support
  498. *****************************************************************************}
  499. {$ifdef FPC_HAS_FEATURE_DYNARRAYS}
  500. {$i dynarr.inc}
  501. {$endif FPC_HAS_FEATURE_DYNARRAYS}
  502. {*****************************************************************************
  503. Object Pascal support
  504. *****************************************************************************}
  505. {$ifdef FPC_HAS_FEATURE_CLASSES}
  506. {$i objpas.inc}
  507. {$endif FPC_HAS_FEATURE_CLASSES}
  508. {*****************************************************************************
  509. Variant support
  510. *****************************************************************************}
  511. {$ifdef FPC_HAS_FEATURE_VARIANTS}
  512. {$i variant.inc}
  513. {$endif FPC_HAS_FEATURE_VARIANTS}
  514. {****************************************************************************
  515. Run-Time Type Information (RTTI)
  516. ****************************************************************************}
  517. {$ifdef FPC_HAS_FEATURE_RTTI}
  518. {$i rtti.inc}
  519. {$endif FPC_HAS_FEATURE_RTTI}
  520. {$if defined(FPC_HAS_FEATURE_RANDOM)}
  521. {$ifndef FPC_USE_SIMPLE_RANDOM}
  522. {$push} // random
  523. {$r-,q-}
  524. // SplitMix64, being a generator of fundamentally different nature,
  525. // is a good (recommended by the author) way to seed Xoshiro.
  526. //
  527. // https://xoroshiro.di.unimi.it/splitmix64.c
  528. //
  529. // This is a generator with 64-bit state, 64-bit output, and 2^64 period.
  530. type
  531. SplitMix64 = object
  532. procedure Setup(const seed: uint64); inline;
  533. function Next: uint64;
  534. private
  535. state: uint64;
  536. end;
  537. procedure SplitMix64.Setup(const seed: uint64);
  538. begin
  539. state := seed;
  540. end;
  541. function SplitMix64.Next: uint64;
  542. var
  543. z: uint64;
  544. begin
  545. z := state + $9e3779b97f4a7c15;
  546. state := z;
  547. z := (z xor (z shr 30)) * $bf58476d1ce4e5b9;
  548. z := (z xor (z shr 27)) * $94d049bb133111eb;
  549. result := z xor (z shr 31);
  550. end;
  551. // Xoshiro128** is an all-purpose RNG.
  552. // http://prng.di.unimi.it/xoshiro128starstar.c
  553. //
  554. // State must not be everywhere zero. With SplitMix64 initialization, it won't. :)
  555. // 128-bit state, 32-bit output, 2^128-1 period.
  556. type
  557. Xoshiro128ss_32 = object
  558. procedure Setup(const seed: uint64);
  559. function Next: uint32; inline; // inlined as it is actually internal and called only through xsr128_32_u32rand
  560. private
  561. state: array[0 .. 3] of longword;
  562. end;
  563. procedure Xoshiro128ss_32.Setup(const seed: uint64);
  564. var
  565. sm: SplitMix64;
  566. x: uint64;
  567. begin
  568. sm.Setup(seed);
  569. x := sm.Next;
  570. state[0] := Lo(x); state[1] := Hi(x);
  571. x := sm.Next;
  572. state[2] := Lo(x); state[3] := Hi(x);
  573. end;
  574. function Xoshiro128ss_32.Next: uint32;
  575. var
  576. s0, s1, s2, s3: uint32;
  577. begin
  578. s0 := state[0];
  579. s1 := state[1];
  580. s2 := state[2] xor s0;
  581. s3 := state[3] xor s1;
  582. result := RolDWord(s1 * 5, 7) * 9;
  583. state[0] := s0 xor s3;
  584. state[1] := s1 xor s2;
  585. state[2] := s2 xor (s1 shl 9);
  586. state[3] := RolDWord(s3, 11);
  587. end;
  588. var
  589. // Just in case user sets RandSeed := not Cardinal(0) (RandSeed := $FFFFFFFF) from the start,
  590. // thus bypassing first-time RandSeed <> OldRandSeed check,
  591. // there will still be a precomputed initialization for RandSeed = $FFFFFFFF.
  592. GlobalXsr128_32: Xoshiro128ss_32 = (state: ($AFF181C0, $73B13BA2, $1340D3B4, $61204305));
  593. procedure ReseedGlobalRNG;
  594. begin
  595. { Detect resets of randseed
  596. This will break if someone coincidentally uses not(randseed) as the
  597. next randseed, but it's much more common that you will reset randseed
  598. to the same value as before to regenerate the same sequence of numbers
  599. }
  600. GlobalXsr128_32.Setup(RandSeed);
  601. RandSeed := not RandSeed;
  602. OldRandSeed := RandSeed;
  603. end;
  604. function xsr128_32_u32rand: uint32;
  605. begin
  606. if RandSeed <> OldRandSeed then ReseedGlobalRNG;
  607. result := GlobalXsr128_32.Next;
  608. end;
  609. // There's still a flaw: repeated assignments of RandSeed := $FFFFFFFF from the start, i.e.
  610. // RandSeed := $FFFFFFFF;
  611. // writeln(random(10));
  612. // RandSeed := $FFFFFFFF;
  613. // writeln(random(10));
  614. // won't reset RNG.
  615. //
  616. // But this is already the case with carefully crafted RandSeeds,
  617. // so I doubt an additional check like "if (RandSeed <> OldRandSeed) or not RngInitialized" is justified.
  618. function random(l:longint): longint;
  619. var
  620. t: uint32;
  621. m: uint64;
  622. begin
  623. result:=l;
  624. if l<0 then
  625. result:=-result-1; { from now on, uint32(result) is a bound. }
  626. { https://lemire.me/blog/2019/06/06/nearly-divisionless-random-integer-generation-on-various-systems/ }
  627. m:=uint64(xsr128_32_u32rand)*uint32(result);
  628. if Lo(m)<uint32(result) then
  629. begin
  630. t:=uint32(-result) mod uint32(result);
  631. while Lo(m)<t do
  632. m:=uint64(xsr128_32_u32rand)*uint32(result);
  633. end;
  634. result:=Hi(m);
  635. if l<-1 then
  636. result:=-result-1;
  637. end;
  638. function random(l:int64): int64;
  639. var
  640. t, ul, mLo: uint64;
  641. a: uint32;
  642. begin
  643. if l=int32(l) then
  644. { This makes random(NativeType) on 64-bit platforms match 32-bit when possible. }
  645. exit(random(longint(l)));
  646. ul:=l;
  647. if l<0 then
  648. ul:=-ul-1;
  649. a:=xsr128_32_u32rand;
  650. mLo:=UMul64x64_128(uint64(a) shl 32 or xsr128_32_u32rand,ul,uint64(result));
  651. if mLo<ul then
  652. begin
  653. t:=uint64(-ul) mod ul;
  654. while mLo<t do
  655. begin
  656. a:=xsr128_32_u32rand;
  657. mLo:=UMul64x64_128(uint64(a) shl 32 or xsr128_32_u32rand,ul,uint64(result));
  658. end;
  659. end;
  660. if l<-1 then
  661. result:=-result-1;
  662. end;
  663. {$ifndef FPUNONE}
  664. function random: extended;
  665. var
  666. res: double;
  667. r0, exponent: uint32;
  668. begin
  669. { There are
  670. - 2⁵² floats uniformly distributed over the range [0.5; 1): exponent = 2⁻¹, mantissa = (1.)all 52-bit values from 00...0 to 11...1,
  671. - another 2⁵² in the range [0.25; 0.5): exponent = 2⁻²,
  672. - another 2⁵² in the range [0.125; 0.25): exponent = 2⁻³,
  673. and so on. Each next range is 0.5× the size of the previous one ⇒ 0.5× probability.
  674. So we determine the range by flipping a coin until we get heads (exponent = 2^(−1 − BSF(infinite stream of random bits)),
  675. and select one of 2⁵² values in that range.
  676. Compared to this, random_52_bits / 2⁵² value loses N bits of precision when it falls in the Nth range; as a consequence,
  677. minimum of 2^N random values has around N trailing zeros in its mantissa. }
  678. { 52 bits (double precision) go to mantissa: r0[0:19] + one_more_u32rand[0:31]. }
  679. r0:=xsr128_32_u32rand;
  680. PUint64(@res)^:=uint64(r0 and (1 shl 20-1)) shl 32 or xsr128_32_u32rand;
  681. { Exponent = −1 − (count of zeros in the stream of random bits). There are 12 bits left in r0. }
  682. exponent:=1023-1-31; { Biased exponent, - 31 for Bsr(r0). }
  683. if r0 shr 20=0 then
  684. begin
  685. inc(exponent,20); { Subtract 12 bits the first time and 32 on subsequent iterations. }
  686. repeat
  687. dec(exponent,32);
  688. r0:=xsr128_32_u32rand;
  689. until r0<>0;
  690. end;
  691. PUint64(@res)^:=PUint64(@res)^ or uint64(exponent+BsrDWord(r0)) shl 52;
  692. result:=res;
  693. end;
  694. {$endif}
  695. {$pop} // random
  696. {$else FPC_USE_SIMPLE_RANDOM}
  697. { A simple implementation of random. TP/Delphi compatible. }
  698. const
  699. QRAN_A = 134775813;
  700. QRAN_C = 1;
  701. function rand_next: cardinal;
  702. var
  703. s: cardinal;
  704. begin
  705. s:=RandSeed*QRAN_A+QRAN_C;
  706. RandSeed:=s;
  707. rand_next:=s;
  708. end;
  709. function random(l: word): word;
  710. var
  711. s,ss: cardinal;
  712. begin
  713. s:=rand_next;
  714. { use 32-bit multiplications here }
  715. ss:=(s shr 16)*l;
  716. s:=(s and $FFFF)*l shr 16;
  717. random:=(ss + s) shr 16;
  718. end;
  719. function random(l: longint): longint;
  720. begin
  721. random:=int64(rand_next)*l shr 32;
  722. end;
  723. function random(l:int64):int64;
  724. begin
  725. random:=random(longint(l));
  726. end;
  727. {$ifndef FPUNONE}
  728. function random: extended;
  729. const
  730. c = 1.0/$10000/$10000;
  731. begin
  732. random:=rand_next*c;
  733. end;
  734. {$endif}
  735. {$endif FPC_USE_SIMPLE_RANDOM}
  736. {$endif FPC_HAS_FEATURE_RANDOM}
  737. {****************************************************************************
  738. Memory Management
  739. ****************************************************************************}
  740. {$ifndef FPC_SYSTEM_HAS_PTR}
  741. Function Ptr(sel,off : {$ifdef CPU16}Word{$else}Longint{$endif}) : farpointer;{$ifdef SYSTEMINLINE}inline;{$endif}
  742. Begin
  743. ptr:=farpointer((sel shl 4)+off);
  744. End;
  745. {$endif not FPC_SYSTEM_HAS_PTR}
  746. {$ifndef FPC_SYSTEM_HAS_CSEG}
  747. Function CSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  748. Begin
  749. Cseg:=0;
  750. End;
  751. {$endif not FPC_SYSTEM_HAS_CSEG}
  752. {$ifndef FPC_SYSTEM_HAS_DSEG}
  753. Function DSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  754. Begin
  755. Dseg:=0;
  756. End;
  757. {$endif not FPC_SYSTEM_HAS_DSEG}
  758. {$ifndef FPC_SYSTEM_HAS_SSEG}
  759. Function SSeg : Word;{$ifdef SYSTEMINLINE}inline;{$endif}
  760. Begin
  761. Sseg:=0;
  762. End;
  763. {$endif not FPC_SYSTEM_HAS_SSEG}
  764. {$push}
  765. {$R-}
  766. {$I-}
  767. {$Q-}
  768. {*****************************************************************************
  769. Miscellaneous
  770. *****************************************************************************}
  771. {$ifndef FPC_SYSTEM_HAS_STACKTOP}
  772. function StackTop: pointer;
  773. begin
  774. { Avoid wrap to zero on 32-bit }
  775. if ptruint(StackBottom) > high(ptruint) - StackLength then
  776. result:=pointer(ptruint(high(ptruint)))
  777. else
  778. result:=StackBottom + StackLength;
  779. end;
  780. {$endif FPC_SYSTEM_HAS_STACKTOP}
  781. {$ifndef FPC_SYSTEM_HAS_GET_PC_ADDR}
  782. { This provides a dummy implementation
  783. of get_pc_addr function, for CPU's that don't need
  784. the instruction address to walk the stack. }
  785. function get_pc_addr : codepointer;inline;
  786. begin
  787. get_pc_addr:=nil;
  788. end;
  789. {$endif ndef FPC_SYSTEM_HAS_GET_PC_ADDR}
  790. {$ifndef FPC_SYSTEM_HAS_GET_CALLER_STACKINFO}
  791. { This provides a simple implementation
  792. of get_caller_stackinfo procedure,
  793. using get_caller_addr and get_caller_frame
  794. functions. }
  795. procedure get_caller_stackinfo(var framebp : pointer; var addr : codepointer);
  796. var
  797. nextbp : pointer;
  798. nextaddr : codepointer;
  799. begin
  800. nextbp:=get_caller_frame(framebp,addr);
  801. nextaddr:=get_caller_addr(framebp,addr);
  802. framebp:=nextbp;
  803. addr:=nextaddr;
  804. end;
  805. {$endif ndef FPC_SYSTEM_HAS_GET_CALLER_STACKINFO}
  806. {$ifdef FPC_HAS_EXPLICIT_INTERLOCKED_POINTER}
  807. {$ifndef FPC_SYSTEM_HAS_EXPLICIT_INTERLOCKED_POINTER}
  808. function InterLockedDecrement (var Target: pointer) : pointer;
  809. begin
  810. Result := Pointer(InterLockedDecrement(PtrInt(Target)));
  811. end;
  812. function InterLockedIncrement (var Target: pointer) : pointer;
  813. begin
  814. Result := Pointer(InterLockedIncrement(PtrInt(Target)));
  815. end;
  816. function InterLockedExchange (var Target: pointer; Source : pointer) : pointer;
  817. begin
  818. Result := Pointer(InterLockedExchange(PtrInt(Target), PtrInt(Source)));
  819. end;
  820. function InterLockedExchangeAdd (var Target: pointer; Source : pointer) : pointer;
  821. begin
  822. Result := Pointer(InterLockedExchangeAdd(PtrInt(Target), PtrInt(Source)));
  823. end;
  824. function InterLockedCompareExchange (var Target: pointer; NewValue: pointer; Comperand: pointer): pointer;
  825. begin
  826. Result := Pointer(InterLockedCompareExchange(PtrInt(Target), PtrInt(NewValue), PtrInt(Comperand)));
  827. end;
  828. function InterLockedCompareExchangePointer (var Target: pointer; NewValue: pointer; Comperand: pointer): pointer;
  829. begin
  830. Result := Pointer(InterLockedCompareExchange(PtrInt(Target), PtrInt(NewValue), PtrInt(Comperand)));
  831. end;
  832. {$endif FPC_SYSTEM_HAS_EXPLICIT_INTERLOCKED_POINTER}
  833. {$endif FPC_HAS_EXPLICIT_INTERLOCKED_POINTER}
  834. procedure fpc_objecterror; compilerproc;
  835. begin
  836. HandleErrorAddrFrameInd(210,get_pc_addr,get_frame);
  837. end;
  838. procedure fpc_rangeerror;[public,alias:'FPC_RANGEERROR']; compilerproc;
  839. begin
  840. HandleErrorAddrFrameInd(201,get_pc_addr,get_frame);
  841. end;
  842. procedure fpc_divbyzero;[public,alias:'FPC_DIVBYZERO']; compilerproc;
  843. begin
  844. HandleErrorAddrFrameInd(200,get_pc_addr,get_frame);
  845. end;
  846. procedure fpc_overflow;[public,alias:'FPC_OVERFLOW']; compilerproc;
  847. begin
  848. HandleErrorAddrFrameInd(215,get_pc_addr,get_frame);
  849. end;
  850. procedure fpc_threaderror; [public,alias:'FPC_THREADERROR'];
  851. begin
  852. HandleErrorAddrFrameInd(236{RuntimeErrorExitCodes[reThreadError]},get_pc_addr,get_frame);
  853. end;
  854. procedure fpc_invalidpointer; [public,alias:'FPC_INVALIDPOINTER']; compilerproc;
  855. begin
  856. HandleErrorAddrFrameInd(216,get_pc_addr,get_frame);
  857. end;
  858. procedure fpc_iocheck;[public,alias:'FPC_IOCHECK']; compilerproc;
  859. var
  860. l : longint;
  861. HInoutRes : PWord;
  862. begin
  863. HInOutRes:=@InoutRes;
  864. if HInOutRes^<>0 then
  865. begin
  866. l:=HInOutRes^;
  867. HInOutRes^:=0;
  868. HandleErrorAddrFrameInd(l,get_pc_addr,get_frame);
  869. end;
  870. end;
  871. Function IOResult:Word;
  872. var
  873. HInoutRes : PWord;
  874. Begin
  875. HInoutRes:=@InoutRes;
  876. IOResult:=HInOutRes^;
  877. HInOutRes^:=0;
  878. End;
  879. Function GetThreadID:TThreadID;{$ifdef SYSTEMINLINE}inline;{$endif}
  880. begin
  881. (* ThreadID is stored in a threadvar and made available in interface *)
  882. (* to allow setup of this value during thread initialization. *)
  883. GetThreadID := ThreadID;
  884. end;
  885. function fpc_safecallcheck(res : hresult) : hresult;[public,alias:'FPC_SAFECALLCHECK']; compilerproc; {$ifdef CPU86} register; {$endif}
  886. begin
  887. if res<0 then
  888. begin
  889. if assigned(SafeCallErrorProc) then
  890. SafeCallErrorProc(res,get_frame);
  891. HandleErrorAddrFrameInd(229,get_pc_addr,get_frame);
  892. end;
  893. result:=res;
  894. end;
  895. {*****************************************************************************
  896. Stack check code
  897. *****************************************************************************}
  898. { be compatible with old code }
  899. {$ifdef FPC_NO_GENERIC_STACK_CHECK}
  900. {$define NO_GENERIC_STACK_CHECK}
  901. {$endif FPC_NO_GENERIC_STACK_CHECK}
  902. {$IFNDEF NO_GENERIC_STACK_CHECK}
  903. {$PUSH}
  904. {$S-}
  905. procedure fpc_stackcheck(stack_size:SizeUInt);[public,alias:'FPC_STACKCHECK']; compilerproc;
  906. var
  907. c : Pointer;
  908. begin
  909. { Avoid recursive calls when called from the exit routines }
  910. if StackError then
  911. exit;
  912. { check stack alignment }
  913. {$ifdef CPUI386}
  914. {$ifdef FPC_STACKALIGNMENT}
  915. {$if FPC_STACKALIGNMENT=16}
  916. if ((PtrUInt(Sptr)+4) mod 16)<>0 then
  917. begin
  918. StackError:=true;
  919. HandleError(202);
  920. end;
  921. {$endif FPC_STACKALIGNMENT=16}
  922. {$endif FPC_STACKALIGNMENT}
  923. {$endif CPUI386}
  924. { don't use stack_size, since the stack pointer has already been
  925. decreased when this routine is called
  926. }
  927. c := Sptr - StackMargin;
  928. if (c <= StackBottom) then
  929. begin
  930. StackError:=true;
  931. HandleError(202);
  932. end;
  933. end;
  934. {$POP}
  935. {$ENDIF NO_GENERIC_STACK_CHECK}
  936. {*****************************************************************************
  937. Initialization / Finalization
  938. *****************************************************************************}
  939. const
  940. maxunits=1024; { See also files.pas of the compiler source }
  941. type
  942. TInitFinalRec=record
  943. InitProc,
  944. FinalProc : TProcedure;
  945. end;
  946. TInitFinalTable = record
  947. TableCount,
  948. InitCount : ALUUInt;
  949. Procs : array[1..maxunits] of TInitFinalRec;
  950. end;
  951. PInitFinalTable = ^TInitFinalTable;
  952. {$ifndef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  953. var
  954. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  955. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  956. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  957. var
  958. i : ALUUInt;
  959. pt : PInitFinalTable;
  960. begin
  961. { call cpu/fpu initialisation routine }
  962. fpc_cpuinit;
  963. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  964. pt := PInitFinalTable(EntryInformation.InitFinalTable);
  965. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  966. pt := @InitFinalTable;
  967. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  968. with pt^ do
  969. begin
  970. for i:=1 to ALUUInt(TableCount) do
  971. begin
  972. if assigned(Procs[i].InitProc) then
  973. Procs[i].InitProc();
  974. InitCount:=i;
  975. end;
  976. end;
  977. if assigned(InitProc) then
  978. TProcedure(InitProc)();
  979. end;
  980. procedure internal_initializeunits; external name 'FPC_INITIALIZEUNITS';
  981. procedure fpc_LibInitializeUnits;[public,alias:'FPC_LIBINITIALIZEUNITS'];compilerproc;
  982. begin
  983. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  984. IsLibrary:=true;
  985. { must also be set to true for packages when implemented }
  986. ModuleIsLib:=true;
  987. internal_initializeunits;
  988. {$endif FPC_HAS_FEATURE_DYNLIBS}
  989. end;
  990. {$ifdef FPC_INIT_FINAL_UNITS_BY_CALLS}
  991. procedure FinalizeUnits; external name 'FPC_FINALIZE_FUNC_TABLE';
  992. {$else FPC_INIT_FINAL_UNITS_BY_CALLS}
  993. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  994. begin
  995. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  996. with PInitFinalTable(EntryInformation.InitFinalTable)^ do
  997. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  998. with InitFinalTable do
  999. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  1000. begin
  1001. while (InitCount>0) do
  1002. begin
  1003. // we've to decrement the cound before calling the final. code
  1004. // else a halt in the final. code leads to a endless loop
  1005. dec(InitCount);
  1006. if assigned(Procs[InitCount+1].FinalProc) then
  1007. Procs[InitCount+1].FinalProc();
  1008. end;
  1009. end;
  1010. end;
  1011. {$endif FPC_INIT_FINAL_UNITS_BY_CALLS}
  1012. {*****************************************************************************
  1013. FPU Exceptions state
  1014. *****************************************************************************}
  1015. {$if defined(FPC_SYSTEM_FPUCW_IMMUTABLE) or defined(FPU_NONE)}
  1016. function GetNativeFPUControlWord: TNativeFPUControlWord; {$if defined(SYSTEMINLINE)}inline;{$endif}
  1017. begin
  1018. result:=default(TNativeFPUControlWord);
  1019. end;
  1020. procedure SetNativeFPUControlWord(const cw: TNativeFPUControlWord); {$if defined(SYSTEMINLINE)}inline;{$endif}
  1021. begin
  1022. end;
  1023. {$endif}
  1024. {*****************************************************************************
  1025. Error / Exit / ExitProc
  1026. *****************************************************************************}
  1027. Procedure system_exit;forward;{$ifdef FPC_SYSTEM_EXIT_NO_RETURN}noreturn;{$endif}
  1028. {$if defined(FPC_HAS_FEATURE_HEAP) and not defined(HAS_MEMORYMANAGER)}
  1029. //not needed if independant memory manager
  1030. Procedure FinalizeHeap;forward;
  1031. {$endif FPC_HAS_FEATURE_HEAP and not HAS_MEMORYMANAGER}
  1032. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1033. procedure SysFlushStdIO;
  1034. begin
  1035. { Make sure that all output is written to the redirected file }
  1036. if Textrec(Output).Mode=fmOutput then
  1037. Flush(Output);
  1038. if Textrec(ErrOutput).Mode=fmOutput then
  1039. Flush(ErrOutput);
  1040. {$ifndef FPC_STDOUT_TRUE_ALIAS}
  1041. if Textrec(stdout).Mode=fmOutput then
  1042. Flush(stdout);
  1043. if Textrec(StdErr).Mode=fmOutput then
  1044. Flush(StdErr);
  1045. {$endif FPC_STDOUT_TRUE_ALIAS}
  1046. end;
  1047. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1048. Procedure InternalExit;
  1049. var
  1050. current_exit : Procedure;
  1051. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1052. pstdout : ^Text;
  1053. {$endif}
  1054. {$if defined(MSWINDOWS) or defined(OS2)}
  1055. i : longint;
  1056. {$endif}
  1057. Begin
  1058. {$ifdef SYSTEMDEBUG}
  1059. writeln('InternalExit');
  1060. {$endif SYSTEMDEBUG}
  1061. {$ifndef CPUAVR}
  1062. while exitProc<>nil Do
  1063. Begin
  1064. InOutRes:=0;
  1065. current_exit:=tProcedure(exitProc);
  1066. exitProc:=nil;
  1067. current_exit();
  1068. End;
  1069. {$endif CPUAVR}
  1070. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1071. { the embedded system unit itself contains no routines for console i/o
  1072. console i/o is done by the Consoleio unit which can do things like
  1073. redirection to seriell i/o }
  1074. {$ifndef EMBEDDED}
  1075. { Show runtime error and exit }
  1076. if WriteErrorsToStdErr then
  1077. pstdout:=@stderr
  1078. else
  1079. pstdout:=@stdout;
  1080. If erroraddr<>nil Then
  1081. Begin
  1082. Writeln(pstdout^,'Runtime error ',Errorcode,' at $',hexstr(erroraddr));
  1083. { to get a nice symify }
  1084. Writeln(pstdout^,BackTraceStrFunc(Erroraddr));
  1085. dump_stack(pstdout^,ErrorBase,ErrorAddr);
  1086. Writeln(pstdout^,'');
  1087. End;
  1088. SysFlushStdIO;
  1089. {$endif EMBEDDED}
  1090. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1091. { Finalize units }
  1092. FinalizeUnits;
  1093. {$if defined(OS2)}
  1094. { finally release the heap if possible, especially
  1095. important for DLLs.
  1096. Reset the array to nil, and finally also argv itself to
  1097. avoid double freeing problem in case this function gets called twice. }
  1098. if assigned(argv) then
  1099. begin
  1100. for i:=0 to argc-1 do
  1101. if assigned(argv[i]) then
  1102. begin
  1103. sysfreemem(argv[i]);
  1104. argv[i]:=nil;
  1105. end;
  1106. sysfreemem(argv);
  1107. argv:=nil;
  1108. end;
  1109. {$endif}
  1110. {$ifdef LINUX}
  1111. {sysfreemem already checks for nil}
  1112. { Do not try to do anything if the heap manager already reported an error }
  1113. if (errorcode<>203) and (errorcode<>204) then
  1114. sysfreemem(calculated_cmdline);
  1115. {$endif}
  1116. {$ifdef BSD}
  1117. { Do not try to do anything if the heap manager already reported an error }
  1118. if (errorcode<>203) and (errorcode<>204) then
  1119. sysfreemem(cmdline);
  1120. {$endif}
  1121. {$if defined(FPC_HAS_FEATURE_HEAP) and not defined(HAS_MEMORYMANAGER)}
  1122. FinalizeHeap;
  1123. {$endif FPC_HAS_FEATURE_HEAP and not HAS_MEMORYMANAGER}
  1124. End;
  1125. Procedure fpc_do_exit;[Public,Alias:'FPC_DO_EXIT']; compilerproc;
  1126. begin
  1127. InternalExit;
  1128. System_exit;
  1129. end;
  1130. procedure internal_do_exit; external name 'FPC_DO_EXIT';
  1131. Procedure fpc_lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  1132. begin
  1133. InternalExit;
  1134. end;
  1135. Procedure Halt(ErrNum: TExitCode);noreturn;
  1136. Begin
  1137. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  1138. {$ifdef FPC_LIMITED_EXITCODE}
  1139. if ErrNum > maxExitCode then
  1140. ExitCode:=255
  1141. else
  1142. {$endif FPC_LIMITED_EXITCODE}
  1143. ExitCode:=ErrNum;
  1144. {$endif FPC_HAS_FEATURE_EXITCODE}
  1145. internal_do_exit;
  1146. end;
  1147. {$ifndef FPC_SYSTEM_HAS_BACKTRACESTR}
  1148. function SysBackTraceStr (Addr: CodePointer): ShortString;
  1149. begin
  1150. SysBackTraceStr:=' $'+hexstr(addr);
  1151. end;
  1152. {$endif FPC_SYSTEM_HAS_BACKTRACESTR}
  1153. {$ifndef FPC_SYSTEM_HAS_CAPTUREBACKTRACE}
  1154. function CaptureBacktrace(skipframes,count:sizeint;frames:PCodePointer):sizeint;
  1155. var
  1156. curr_frame,prev_frame: pointer;
  1157. curr_addr: codepointer;
  1158. i: sizeint;
  1159. begin
  1160. curr_frame:=get_frame;
  1161. curr_addr:=get_pc_addr;
  1162. prev_frame:=curr_frame;
  1163. get_caller_stackinfo(curr_frame,curr_addr);
  1164. i:=-skipframes;
  1165. while (i<count) and (curr_frame>prev_frame) and
  1166. (curr_frame<StackTop) do
  1167. begin
  1168. if (curr_addr=nil) or
  1169. (curr_frame=nil) then
  1170. break;
  1171. if (i>=0) then
  1172. frames[i]:=curr_addr;
  1173. inc(i);
  1174. prev_frame:=curr_frame;
  1175. get_caller_stackinfo(curr_frame,curr_addr);
  1176. end;
  1177. if i<0 then
  1178. result:=0
  1179. else
  1180. result:=i;
  1181. end;
  1182. {$endif FPC_SYSTEM_HAS_CAPTUREBACKTRACE}
  1183. Procedure HandleErrorAddrFrame (Errno : TExitCode;addr : CodePointer; frame : Pointer);[public,alias:'FPC_BREAK_ERROR']; {$ifdef CPUI386} register; {$endif}
  1184. begin
  1185. If codepointer(ErrorProc)<>Nil then
  1186. ErrorProc(Errno,addr,frame);
  1187. errorcode:=word(Errno);
  1188. erroraddr:=addr;
  1189. errorbase:=frame;
  1190. Halt(errorcode);
  1191. end;
  1192. { This is used internally by system skip first level,
  1193. and generated the same output as before, when
  1194. HandleErrorFrame function was used internally. }
  1195. Procedure HandleErrorAddrFrameInd (Errno : TExitCode;addr : CodePointer; frame : Pointer);
  1196. begin
  1197. get_caller_stackinfo (frame, addr);
  1198. HandleErrorAddrFrame (Errno,addr,frame);
  1199. end;
  1200. Procedure HandleErrorFrame (Errno : TExitCode;frame : Pointer);
  1201. {
  1202. Procedure to handle internal errors, i.e. not user-invoked errors
  1203. Internal function should ALWAYS call HandleError instead of RunError.
  1204. Can be used for exception handlers to specify the frame
  1205. }
  1206. begin
  1207. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  1208. end;
  1209. procedure fpc_handleerror (Errno : TExitCode); compilerproc; [public,alias : 'FPC_HANDLEERROR'];
  1210. {
  1211. Procedure to handle internal errors, i.e. not user-invoked errors
  1212. Internal function should ALWAYS call HandleError instead of RunError.
  1213. }
  1214. begin
  1215. HandleErrorAddrFrameInd(Errno,get_pc_addr,get_frame);
  1216. end;
  1217. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];noreturn;
  1218. var
  1219. bp : pointer;
  1220. pcaddr : codepointer;
  1221. begin
  1222. errorcode:=w;
  1223. pcaddr:=get_pc_addr;
  1224. bp:=get_frame;
  1225. get_caller_stackinfo(bp,pcaddr);
  1226. erroraddr:=pcaddr;
  1227. errorbase:=bp;
  1228. Halt(errorcode);
  1229. end;
  1230. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}noreturn;
  1231. Begin
  1232. RunError (0);
  1233. End;
  1234. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}noreturn;
  1235. Begin
  1236. Halt(0);
  1237. End;
  1238. Procedure Error(RunTimeError : TRunTimeError);
  1239. begin
  1240. RunError(RuntimeErrorExitCodes[RunTimeError]);
  1241. end;
  1242. Procedure dump_stack(var f : text;fp : Pointer; addr : CodePointer);
  1243. var
  1244. i : ObjpasInt;
  1245. prevfp : Pointer;
  1246. is_dev : boolean;
  1247. Begin
  1248. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1249. try
  1250. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1251. { Frame of this procedure acts as StackBottom, fp values below that are invalid. }
  1252. prevfp:=get_frame;
  1253. i:=0;
  1254. is_dev:=do_isdevice(textrec(f).Handle);
  1255. { sanity checks, new frame pointer must be always greater than the old one, further
  1256. it must point into the stack area, else something went wrong }
  1257. while (fp>prevfp) and (fp<StackTop) do
  1258. Begin
  1259. prevfp:=fp;
  1260. get_caller_stackinfo(fp,addr);
  1261. if (addr=nil) then
  1262. break;
  1263. Writeln(f,BackTraceStrFunc(addr));
  1264. if (fp=nil) then
  1265. break;
  1266. Inc(i);
  1267. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  1268. break;
  1269. End;
  1270. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1271. except
  1272. { prevent endless dump if an exception occurred }
  1273. end;
  1274. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1275. End;
  1276. procedure dump_stack(var f: text; skipframes: longint);
  1277. var
  1278. i,count: ObjpasInt;
  1279. frames: array [0..255] of codepointer;
  1280. begin
  1281. if do_isdevice(textrec(f).handle) then
  1282. count:=max_frame_dump
  1283. else
  1284. count:=255;
  1285. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1286. try
  1287. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1288. count:=CaptureBacktrace(skipframes+1,count,@frames[0]);
  1289. for i:=0 to count-1 do
  1290. writeln(f,BackTraceStrFunc(frames[i]));
  1291. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1292. except
  1293. end;
  1294. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1295. end;
  1296. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1297. procedure DumpExceptionBackTrace(var f:text);
  1298. var
  1299. FrameNumber,
  1300. FrameCount : ObjpasInt;
  1301. Frames : PCodePointer;
  1302. begin
  1303. if RaiseList=nil then
  1304. exit;
  1305. WriteLn(f,BackTraceStrFunc(RaiseList^.Addr));
  1306. FrameCount:=RaiseList^.Framecount;
  1307. Frames:=RaiseList^.Frames;
  1308. for FrameNumber := 0 to FrameCount-1 do
  1309. WriteLn(f,BackTraceStrFunc(Frames[FrameNumber]));
  1310. end;
  1311. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1312. {$ifdef FPC_HAS_FEATURE_HEAP}
  1313. Type
  1314. PExitProcInfo = ^TExitProcInfo;
  1315. TExitProcInfo = Record
  1316. Next : PExitProcInfo;
  1317. SaveExit : CodePointer;
  1318. Proc : TProcedure;
  1319. End;
  1320. const
  1321. ExitProcList: PExitProcInfo = nil;
  1322. Procedure DoExitProc;
  1323. var
  1324. P : PExitProcInfo;
  1325. Proc : TProcedure;
  1326. Begin
  1327. P:=ExitProcList;
  1328. ExitProcList:=P^.Next;
  1329. ExitProc:=P^.SaveExit;
  1330. Proc:=P^.Proc;
  1331. DisPose(P);
  1332. Proc();
  1333. End;
  1334. Procedure AddExitProc(Proc: TProcedure);
  1335. var
  1336. P : PExitProcInfo;
  1337. Begin
  1338. New(P);
  1339. P^.Next:=ExitProcList;
  1340. P^.SaveExit:=ExitProc;
  1341. P^.Proc:=Proc;
  1342. ExitProcList:=P;
  1343. ExitProc:=@DoExitProc;
  1344. End;
  1345. {$endif FPC_HAS_FEATURE_HEAP}
  1346. {$ifdef FPC_HAS_FEATURE_HEAP}
  1347. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1348. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppansichar; // const ?
  1349. {$ifdef EXCLUDE_COMPLEX_PROCS}
  1350. begin
  1351. runerror(217);
  1352. end;
  1353. {$else EXCLUDE_COMPLEX_PROCS}
  1354. // Extra allocate reserveentries pansichar's at the beginning (default param=0 after 1.0.x ?)
  1355. // Note: for internal use by skilled programmers only
  1356. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  1357. var p : ppansichar;
  1358. i : ObjpasInt;
  1359. begin
  1360. if High(s)<Low(s) Then Exit(NIL);
  1361. Getmem(p,sizeof(pansichar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  1362. // for cmd
  1363. if p=nil then
  1364. begin
  1365. {$ifdef xunix}
  1366. fpseterrno(ESysEnomem);
  1367. {$endif}
  1368. exit(NIL);
  1369. end;
  1370. for i:=low(s) to high(s) do
  1371. p[i+Reserveentries]:=pansichar(s[i]);
  1372. p[high(s)+1+Reserveentries]:=nil;
  1373. ArrayStringToPPchar:=p;
  1374. end;
  1375. {$endif EXCLUDE_COMPLEX_PROCS}
  1376. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppansichar;
  1377. {
  1378. Create a PPAnsiChar to structure of pchars which are the arguments specified
  1379. in the string S. Especially useful for creating an ArgV for Exec-calls
  1380. }
  1381. begin
  1382. StringToPPChar:=StringToPPChar(PAnsiChar(S),ReserveEntries);
  1383. end;
  1384. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1385. Function StringToPPChar(S: PAnsiChar;ReserveEntries:integer):ppansichar;
  1386. var
  1387. i,nr : ObjpasInt;
  1388. Buf : ^ansichar;
  1389. p : ppansichar;
  1390. begin
  1391. buf:=s;
  1392. nr:=1;
  1393. while (buf^<>#0) do // count nr of args
  1394. begin
  1395. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1396. inc(buf);
  1397. inc(nr);
  1398. if buf^='"' Then // quotes argument?
  1399. begin
  1400. inc(buf);
  1401. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1402. inc(buf);
  1403. if buf^='"' then // skip closing quote.
  1404. inc(buf);
  1405. end
  1406. else
  1407. begin // else std
  1408. while not (buf^ in [' ',#0,#9,#10]) do
  1409. inc(buf);
  1410. end;
  1411. end;
  1412. getmem(p,(ReserveEntries+nr)*sizeof(pansichar));
  1413. StringToPPChar:=p;
  1414. if p=nil then
  1415. begin
  1416. {$ifdef xunix}
  1417. fpseterrno(ESysEnomem);
  1418. {$endif}
  1419. exit;
  1420. end;
  1421. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  1422. buf:=s;
  1423. while (buf^<>#0) do
  1424. begin
  1425. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1426. begin
  1427. buf^:=#0;
  1428. inc(buf);
  1429. end;
  1430. if buf^='"' Then // quotes argument?
  1431. begin
  1432. inc(buf);
  1433. p^:=buf;
  1434. inc(p);
  1435. p^:=nil;
  1436. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1437. inc(buf);
  1438. if buf^='"' then // skip closing quote.
  1439. begin
  1440. buf^:=#0;
  1441. inc(buf);
  1442. end;
  1443. end
  1444. else
  1445. begin
  1446. p^:=buf;
  1447. inc(p);
  1448. p^:=nil;
  1449. while not (buf^ in [' ',#0,#9,#10]) do
  1450. inc(buf);
  1451. end;
  1452. end;
  1453. end;
  1454. {$endif FPC_HAS_FEATURE_HEAP}
  1455. {*****************************************************************************
  1456. Abstract/Assert support.
  1457. *****************************************************************************}
  1458. procedure fpc_emptymethod;[public,alias : 'FPC_EMPTYMETHOD'];
  1459. begin
  1460. end;
  1461. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  1462. begin
  1463. If codepointer(AbstractErrorProc)<>nil then
  1464. AbstractErrorProc();
  1465. HandleErrorAddrFrameInd(211,get_pc_addr,get_frame);
  1466. end;
  1467. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;
  1468. ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  1469. begin
  1470. if codepointer(AssertErrorProc)<>nil then
  1471. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  1472. else
  1473. HandleErrorAddrFrameInd(227,get_pc_addr,get_frame);
  1474. end;
  1475. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  1476. begin
  1477. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1478. If Length(msg)=0 then
  1479. write(stderr,'Assertion failed')
  1480. else
  1481. write(stderr,msg);
  1482. Writeln(stderr,' (',FName,', line ',LineNo,').');
  1483. Writeln(stderr,'');
  1484. Halt(227);
  1485. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1486. end;
  1487. {*****************************************************************************
  1488. SetJmp/LongJmp support.
  1489. *****************************************************************************}
  1490. {$i setjump.inc}
  1491. {$pop} //{$I-,R-,Q-} before 'procedure fpc_rangeerror'
  1492. {*****************************************************************************
  1493. Heap
  1494. *****************************************************************************}
  1495. {$i sysheap.inc}
  1496. {$IFDEF LEGACYHEAP}
  1497. {$i oldheap.inc}
  1498. {$ELSE}
  1499. {$i heap.inc}
  1500. {$ENDIF LEGACYHEAP}
  1501. {*****************************************************************************
  1502. Thread support
  1503. *****************************************************************************}
  1504. {$ifdef FPC_HAS_FEATURE_THREADING}
  1505. { Generic threadmanager }
  1506. {$i thread.inc}
  1507. { Generic threadvar support }
  1508. {$i threadvr.inc}
  1509. {$ifdef DISABLE_NO_THREAD_MANAGER}
  1510. { OS Dependent implementation }
  1511. {$i systhrd.inc}
  1512. {$endif DISABLE_NO_THREAD_MANAGER}
  1513. {$endif FPC_HAS_FEATURE_THREADING}
  1514. {*****************************************************************************
  1515. Dynamic library support
  1516. *****************************************************************************}
  1517. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  1518. {$i dynlib.inc}
  1519. {$ifdef DISABLE_NO_DYNLIBS_MANAGER}
  1520. { OS Dependant implementation }
  1521. {$i sysdl.inc}
  1522. {$endif DISABLE_NO_DYNLIBS_MANAGER}
  1523. {$endif FPC_HAS_FEATURE_DYNLIBS}
  1524. {*****************************************************************************
  1525. File Handling
  1526. *****************************************************************************}
  1527. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1528. { Allow slash and backslash as separators }
  1529. procedure DoDirSeparators(var p: pansichar; inplace: boolean = true);
  1530. var
  1531. i : ObjpasInt;
  1532. len : sizeint;
  1533. newp : pansichar;
  1534. begin
  1535. len:=length(p);
  1536. newp:=nil;
  1537. for i:=0 to len do
  1538. if p[i] in AllowDirectorySeparators then
  1539. begin
  1540. if not inplace and
  1541. not assigned(newp) then
  1542. begin
  1543. getmem(newp,len+1);
  1544. move(p^,newp^,len+1);
  1545. p:=newp;
  1546. end;
  1547. p[i]:=DirectorySeparator;
  1548. end;
  1549. end;
  1550. procedure DoDirSeparators(var p: pwidechar; inplace: boolean = true);
  1551. var
  1552. i : ObjpasInt;
  1553. len : sizeint;
  1554. newp : pwidechar;
  1555. begin
  1556. len:=length(p);
  1557. newp:=nil;
  1558. for i:=0 to len do
  1559. if (ord(p[i])<255) and
  1560. (ansichar(ord(p[i])) in AllowDirectorySeparators) then
  1561. begin
  1562. if not inplace and
  1563. not assigned(newp) then
  1564. begin
  1565. getmem(newp,(len+1)*2);
  1566. move(p^,newp^,(len+1)*2);
  1567. p:=newp;
  1568. end;
  1569. p[i]:=DirectorySeparator;
  1570. end;
  1571. end;
  1572. procedure DoDirSeparators(var p:shortstring);
  1573. var
  1574. i : ObjpasInt;
  1575. begin
  1576. for i:=1 to length(p) do
  1577. if p[i] in AllowDirectorySeparators then
  1578. p[i]:=DirectorySeparator;
  1579. end;
  1580. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1581. procedure DoDirSeparators(var ps:RawByteString);
  1582. var
  1583. i : ObjpasInt;
  1584. p : pansichar;
  1585. unique : boolean;
  1586. begin
  1587. unique:=false;
  1588. for i:=1 to length(ps) do
  1589. if ps[i] in AllowDirectorySeparators then
  1590. begin
  1591. if not unique then
  1592. begin
  1593. uniquestring(ps);
  1594. p:=pansichar(ps);
  1595. unique:=true;
  1596. end;
  1597. p[i-1]:=DirectorySeparator;
  1598. end;
  1599. end;
  1600. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1601. {$ifdef FPC_HAS_FEATURE_UNICODESTRINGS}
  1602. procedure DoDirSeparators(var ps:UnicodeString);
  1603. var
  1604. i : ObjpasInt;
  1605. p : pwidechar;
  1606. unique : boolean;
  1607. begin
  1608. unique:=false;
  1609. for i:=1 to length(ps) do
  1610. if ps[i] in AllowDirectorySeparators then
  1611. begin
  1612. if not unique then
  1613. begin
  1614. uniquestring(ps);
  1615. p:=pwidechar(ps);
  1616. unique:=true;
  1617. end;
  1618. p[i-1]:=DirectorySeparator;
  1619. end;
  1620. end;
  1621. {$endif FPC_HAS_FEATURE_UNICODESTRINGS}
  1622. {$endif FPC_HAS_FEATURE_FILEIO}
  1623. { OS dependent low level file functions }
  1624. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1625. {$i sysfile.inc}
  1626. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1627. {$ifdef FPC_ANSI_TEXTFILEREC}
  1628. procedure do_open(var f; p: pansichar; flags: longint; pchangeable: boolean);
  1629. var
  1630. u: UnicodeString;
  1631. begin
  1632. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1633. do_open(f,pwidechar(u),flags,true);
  1634. end;
  1635. procedure do_erase(p: pansichar; pchangeable: boolean);
  1636. var
  1637. u: UnicodeString;
  1638. begin
  1639. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1640. do_erase(pwidechar(u),true);
  1641. end;
  1642. procedure do_rename(src, dst: pansichar; srcchangeable, dstchangeable: boolean);
  1643. var
  1644. usrc, udst: UnicodeString;
  1645. begin
  1646. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1647. widestringmanager.Ansi2UnicodeMoveProc(dst,DefaultFileSystemCodePage,udst,length(dst));
  1648. do_rename(pwidechar(usrc),pwidechar(udst),true,true);
  1649. end;
  1650. procedure do_rename(src: pansichar; dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1651. var
  1652. usrc: UnicodeString;
  1653. begin
  1654. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1655. do_rename(pwidechar(usrc),dst,true,dstchangeable);
  1656. end;
  1657. {$endif FPC_ANSI_TEXTFILEREC}
  1658. {$endif not FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1659. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1660. {$ifndef FPC_ANSI_TEXTFILEREC}
  1661. procedure do_open(var f; p: pwidechar; flags: longint; pchangeable: boolean);
  1662. var
  1663. s: RawByteString;
  1664. begin
  1665. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1666. do_open(f,pansichar(s),flags,true);
  1667. end;
  1668. procedure do_erase(p: pwidechar; pchangeable: boolean);
  1669. var
  1670. s: RawByteString;
  1671. begin
  1672. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1673. do_erase(pansichar(s),true);
  1674. end;
  1675. procedure do_rename(src, dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1676. var
  1677. rsrc, rdst: RawByteString;
  1678. begin
  1679. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1680. widestringmanager.Unicode2AnsiMoveProc(dst,rdst,DefaultFileSystemCodePage,length(dst));
  1681. do_rename(pansichar(rsrc),pansichar(rdst),true,true);
  1682. end;
  1683. procedure do_rename(src: pwidechar; dst: pansichar; srcchangeable, dstchangeable: boolean);
  1684. var
  1685. rsrc: RawByteString;
  1686. begin
  1687. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1688. do_rename(pansichar(rsrc),dst,true,dstchangeable);
  1689. end;
  1690. {$endif not FPC_ANSI_TEXTFILEREC}
  1691. {$endif not FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1692. {$endif FPC_HAS_FEATURE_FILEIO}
  1693. { helper for targets supporting no ansistrings, it is used
  1694. by non-ansistring code }
  1695. function min(v1,v2 : SizeInt) : SizeInt;
  1696. begin
  1697. if v1<v2 then
  1698. result:=v1
  1699. else
  1700. result:=v2;
  1701. end;
  1702. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  1703. { Text file }
  1704. {$i text.inc}
  1705. {$endif FPC_HAS_FEATURE_TEXTIO}
  1706. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1707. { Untyped file }
  1708. {$i file.inc}
  1709. { Typed file }
  1710. {$i typefile.inc}
  1711. {$endif FPC_HAS_FEATURE_FILEIO}
  1712. {*****************************************************************************
  1713. Directory Handling
  1714. *****************************************************************************}
  1715. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1716. { OS dependent dir functions }
  1717. {$i sysdir.inc}
  1718. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1719. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1720. procedure do_getdir(drivenr : byte;var dir : rawbytestring);
  1721. var
  1722. u: unicodestring;
  1723. begin
  1724. Do_getdir(drivenr,u);
  1725. widestringmanager.Unicode2AnsiMoveProc(pwidechar(u),dir,DefaultRTLFileSystemCodePage,length(u));
  1726. end;
  1727. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1728. Procedure MkDir(Const s: RawByteString);[IOCheck];
  1729. Begin
  1730. If (Length(s)=0) or (InOutRes <> 0) then
  1731. exit;
  1732. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1733. Do_mkdir(ToSingleByteFileSystemEncodedFileName(S));
  1734. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1735. Do_mkdir(S);
  1736. {$endif}
  1737. end;
  1738. Procedure RmDir(Const s: RawByteString);[IOCheck];
  1739. Begin
  1740. If (Length(s)=0) or (InOutRes <> 0) then
  1741. exit;
  1742. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1743. Do_rmdir(ToSingleByteFileSystemEncodedFileName(S));
  1744. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1745. Do_rmdir(S);
  1746. {$endif}
  1747. End;
  1748. Procedure ChDir(Const s: RawByteString);[IOCheck];
  1749. Begin
  1750. If (Length(s)=0) or (InOutRes <> 0) then
  1751. exit;
  1752. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1753. Do_chdir(ToSingleByteFileSystemEncodedFileName(S));
  1754. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1755. Do_chdir(S);
  1756. {$endif}
  1757. End;
  1758. Procedure getdir(drivenr:byte;Var dir:rawbytestring);
  1759. begin
  1760. Do_getdir(drivenr,dir);
  1761. { we should return results in the DefaultRTLFileSystemCodePage -> convert if
  1762. necessary }
  1763. setcodepage(dir,DefaultRTLFileSystemCodePage,true);
  1764. end;
  1765. { the generic shortstring ones are only implemented elsewhere for systems *not*
  1766. supporting ansi/unicodestrings; for now assume there are no systems that
  1767. support unicodestrings but not ansistrings }
  1768. { avoid double string conversions }
  1769. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1770. function GetDirStrFromShortstring(const s: shortstring): RawByteString;
  1771. begin
  1772. GetDirStrFromShortstring:=ToSingleByteFileSystemEncodedFileName(ansistring(s));
  1773. end;
  1774. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1775. function GetDirStrFromShortstring(const s: shortstring): UnicodeString;
  1776. begin
  1777. GetDirStrFromShortstring:=s;
  1778. end;
  1779. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1780. Procedure MkDir(Const s: shortstring);[IOCheck];
  1781. Begin
  1782. If (Length(s)=0) or (InOutRes <> 0) then
  1783. exit;
  1784. Do_mkdir(GetDirStrFromShortstring(S));
  1785. End;
  1786. Procedure RmDir(Const s: shortstring);[IOCheck];
  1787. Begin
  1788. If (Length(s)=0) or (InOutRes <> 0) then
  1789. exit;
  1790. Do_rmdir(GetDirStrFromShortstring(S));
  1791. End;
  1792. Procedure ChDir(Const s: shortstring);[IOCheck];
  1793. Begin
  1794. If (Length(S)=0) or (InOutRes <> 0) then
  1795. exit;
  1796. Do_chdir(GetDirStrFromShortstring(S));
  1797. End;
  1798. Procedure getdir(drivenr:byte;Var dir:shortstring);
  1799. var
  1800. s: rawbytestring;
  1801. begin
  1802. Do_getdir(drivenr,s);
  1803. if length(s)<=high(dir) then
  1804. dir:=s
  1805. else
  1806. inoutres:=3;
  1807. end;
  1808. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1809. {$if defined(FPC_HAS_FEATURE_WIDESTRINGS)}
  1810. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1811. { overloads required for mkdir/rmdir/chdir to ensure that the string is
  1812. converted to the right code page }
  1813. procedure do_mkdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1814. begin
  1815. do_mkdir(ToSingleByteFileSystemEncodedFileName(s));
  1816. end;
  1817. procedure do_rmdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1818. begin
  1819. do_rmdir(ToSingleByteFileSystemEncodedFileName(s));
  1820. end;
  1821. procedure do_chdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1822. begin
  1823. do_chdir(ToSingleByteFileSystemEncodedFileName(s));
  1824. end;
  1825. procedure do_getdir(drivenr : byte;var dir : unicodestring);
  1826. var
  1827. s: rawbytestring;
  1828. begin
  1829. Do_getdir(drivenr,s);
  1830. dir:=unicodestring(s);
  1831. end;
  1832. {$endif FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1833. Procedure MkDir(Const s: UnicodeString);[IOCheck];
  1834. Begin
  1835. if (Length(s)=0) or (InOutRes <> 0) then
  1836. exit;
  1837. Do_mkdir(S);
  1838. End;
  1839. Procedure RmDir(Const s: UnicodeString);[IOCheck];
  1840. Begin
  1841. if (Length(s)=0) or (InOutRes <> 0) then
  1842. exit;
  1843. Do_rmdir(S);
  1844. End;
  1845. Procedure ChDir(Const s: UnicodeString);[IOCheck];
  1846. Begin
  1847. if (Length(s)=0) or (InOutRes <> 0) then
  1848. exit;
  1849. Do_chdir(S);
  1850. End;
  1851. Procedure getdir(drivenr:byte;Var dir:unicodestring);
  1852. begin
  1853. Do_getdir(drivenr,dir);
  1854. end;
  1855. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  1856. {$endif FPC_HAS_FEATURE_FILEIO}
  1857. {*****************************************************************************
  1858. Resources support
  1859. *****************************************************************************}
  1860. {$i sysres.inc}
  1861. const
  1862. CtrlBreakHandler: TCtrlBreakHandler = nil;
  1863. {$IFNDEF FPC_HAS_SETCTRLBREAKHANDLER}
  1864. (* It is possible to provide platform specific implementation performing *)
  1865. (* special initialization; default implementation just sets the procedural *)
  1866. (* variable to make it available for use from the exception handler. *)
  1867. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  1868. begin
  1869. (* Return either nil or previous handler *)
  1870. SysSetCtrlBreakHandler := CtrlBreakHandler;
  1871. CtrlBreakHandler := Handler;
  1872. end;
  1873. {$ENDIF FPC_HAS_SETCTRLBREAKHANDLER}