system.inc 59 KB

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