system.inc 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239
  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. {$IFDEF FPC_INITFINAL_HASUNITNAME}
  939. unitname : ^shortstring;
  940. {$ENDIF}
  941. end;
  942. TInitFinalTable = record
  943. TableCount,
  944. InitCount : ALUUInt;
  945. Procs : array[1..maxunits] of TInitFinalRec;
  946. end;
  947. PInitFinalTable = ^TInitFinalTable;
  948. {$ifndef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  949. var
  950. InitFinalTable : TInitFinalTable;external name 'INITFINAL';
  951. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  952. procedure fpc_InitializeUnits;[public,alias:'FPC_INITIALIZEUNITS']; compilerproc;
  953. var
  954. i : ALUUInt;
  955. pt : PInitFinalTable;
  956. begin
  957. { call cpu/fpu initialisation routine }
  958. fpc_cpuinit;
  959. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  960. pt := PInitFinalTable(EntryInformation.InitFinalTable);
  961. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  962. pt := @InitFinalTable;
  963. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  964. with pt^ do
  965. begin
  966. for i:=1 to ALUUInt(TableCount) do
  967. begin
  968. if assigned(Procs[i].InitProc) then
  969. Procs[i].InitProc();
  970. {$ifdef FPC_INITFINAL_HASUNITNAME}
  971. {$ifdef ENABLE_UNIT_INIT_TRACKING}
  972. if assigned(UnitInitTrackingProc) then
  973. UnitInitTrackingProc(i,Procs[i].unitname^);
  974. {$endif ENABLE_UNIT_INIT_TRACKING}
  975. {$endif FPC_INITFINAL_HASUNITNAME}
  976. InitCount:=i;
  977. end;
  978. end;
  979. if assigned(InitProc) then
  980. TProcedure(InitProc)();
  981. end;
  982. procedure internal_initializeunits; external name 'FPC_INITIALIZEUNITS';
  983. procedure fpc_LibInitializeUnits;[public,alias:'FPC_LIBINITIALIZEUNITS'];compilerproc;
  984. begin
  985. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  986. IsLibrary:=true;
  987. { must also be set to true for packages when implemented }
  988. ModuleIsLib:=true;
  989. internal_initializeunits;
  990. {$endif FPC_HAS_FEATURE_DYNLIBS}
  991. end;
  992. {$ifdef FPC_INIT_FINAL_UNITS_BY_CALLS}
  993. procedure FinalizeUnits; external name 'FPC_FINALIZE_FUNC_TABLE';
  994. {$else FPC_INIT_FINAL_UNITS_BY_CALLS}
  995. procedure FinalizeUnits;[public,alias:'FPC_FINALIZEUNITS'];
  996. begin
  997. {$ifdef FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  998. with PInitFinalTable(EntryInformation.InitFinalTable)^ do
  999. {$else FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  1000. with InitFinalTable do
  1001. {$endif FPC_HAS_INDIRECT_ENTRY_INFORMATION}
  1002. begin
  1003. while (InitCount>0) do
  1004. begin
  1005. // we've to decrement the cound before calling the final. code
  1006. // else a halt in the final. code leads to a endless loop
  1007. dec(InitCount);
  1008. if assigned(Procs[InitCount+1].FinalProc) then
  1009. Procs[InitCount+1].FinalProc();
  1010. end;
  1011. end;
  1012. end;
  1013. {$endif FPC_INIT_FINAL_UNITS_BY_CALLS}
  1014. {*****************************************************************************
  1015. FPU Exceptions state
  1016. *****************************************************************************}
  1017. {$if defined(FPC_SYSTEM_FPUCW_IMMUTABLE) or defined(FPU_NONE)}
  1018. function GetNativeFPUControlWord: TNativeFPUControlWord; {$if defined(SYSTEMINLINE)}inline;{$endif}
  1019. begin
  1020. result:=default(TNativeFPUControlWord);
  1021. end;
  1022. procedure SetNativeFPUControlWord(const cw: TNativeFPUControlWord); {$if defined(SYSTEMINLINE)}inline;{$endif}
  1023. begin
  1024. end;
  1025. {$endif}
  1026. {*****************************************************************************
  1027. Error / Exit / ExitProc
  1028. *****************************************************************************}
  1029. Procedure system_exit;forward;{$ifdef FPC_SYSTEM_EXIT_NO_RETURN}noreturn;{$endif}
  1030. {$if defined(FPC_HAS_FEATURE_HEAP) and not defined(HAS_MEMORYMANAGER)}
  1031. //not needed if independant memory manager
  1032. Procedure FinalizeHeap;forward;
  1033. {$endif FPC_HAS_FEATURE_HEAP and not HAS_MEMORYMANAGER}
  1034. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1035. procedure SysFlushStdIO;
  1036. begin
  1037. { Make sure that all output is written to the redirected file }
  1038. if Textrec(Output).Mode=fmOutput then
  1039. Flush(Output);
  1040. if Textrec(ErrOutput).Mode=fmOutput then
  1041. Flush(ErrOutput);
  1042. {$ifndef FPC_STDOUT_TRUE_ALIAS}
  1043. if Textrec(stdout).Mode=fmOutput then
  1044. Flush(stdout);
  1045. if Textrec(StdErr).Mode=fmOutput then
  1046. Flush(StdErr);
  1047. {$endif FPC_STDOUT_TRUE_ALIAS}
  1048. end;
  1049. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1050. Procedure InternalExit;
  1051. var
  1052. current_exit : Procedure;
  1053. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1054. pstdout : ^Text;
  1055. {$endif}
  1056. {$if defined(MSWINDOWS) or defined(OS2)}
  1057. i : longint;
  1058. {$endif}
  1059. Begin
  1060. {$ifdef SYSTEMDEBUG}
  1061. writeln('InternalExit');
  1062. {$endif SYSTEMDEBUG}
  1063. {$ifndef CPUAVR}
  1064. while exitProc<>nil Do
  1065. Begin
  1066. InOutRes:=0;
  1067. current_exit:=tProcedure(exitProc);
  1068. exitProc:=nil;
  1069. current_exit();
  1070. End;
  1071. {$endif CPUAVR}
  1072. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1073. { the embedded system unit itself contains no routines for console i/o
  1074. console i/o is done by the Consoleio unit which can do things like
  1075. redirection to seriell i/o }
  1076. {$ifndef EMBEDDED}
  1077. { Show runtime error and exit }
  1078. if WriteErrorsToStdErr then
  1079. pstdout:=@stderr
  1080. else
  1081. pstdout:=@stdout;
  1082. If erroraddr<>nil Then
  1083. Begin
  1084. Writeln(pstdout^,'Runtime error ',Errorcode,' at $',hexstr(erroraddr));
  1085. { to get a nice symify }
  1086. Writeln(pstdout^,BackTraceStrFunc(Erroraddr));
  1087. dump_stack(pstdout^,ErrorBase,ErrorAddr);
  1088. Writeln(pstdout^,'');
  1089. End;
  1090. SysFlushStdIO;
  1091. {$endif EMBEDDED}
  1092. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1093. { Finalize units }
  1094. FinalizeUnits;
  1095. {$if defined(OS2)}
  1096. { finally release the heap if possible, especially
  1097. important for DLLs.
  1098. Reset the array to nil, and finally also argv itself to
  1099. avoid double freeing problem in case this function gets called twice. }
  1100. if assigned(argv) then
  1101. begin
  1102. for i:=0 to argc-1 do
  1103. if assigned(argv[i]) then
  1104. begin
  1105. sysfreemem(argv[i]);
  1106. argv[i]:=nil;
  1107. end;
  1108. sysfreemem(argv);
  1109. argv:=nil;
  1110. end;
  1111. {$endif}
  1112. {$ifdef LINUX}
  1113. {sysfreemem already checks for nil}
  1114. { Do not try to do anything if the heap manager already reported an error }
  1115. if (errorcode<>203) and (errorcode<>204) then
  1116. sysfreemem(calculated_cmdline);
  1117. {$endif}
  1118. {$ifdef BSD}
  1119. { Do not try to do anything if the heap manager already reported an error }
  1120. if (errorcode<>203) and (errorcode<>204) then
  1121. sysfreemem(cmdline);
  1122. {$endif}
  1123. {$if defined(FPC_HAS_FEATURE_HEAP) and not defined(HAS_MEMORYMANAGER)}
  1124. FinalizeHeap;
  1125. {$endif FPC_HAS_FEATURE_HEAP and not HAS_MEMORYMANAGER}
  1126. End;
  1127. Procedure fpc_do_exit;[Public,Alias:'FPC_DO_EXIT']; compilerproc;
  1128. begin
  1129. InternalExit;
  1130. System_exit;
  1131. end;
  1132. procedure internal_do_exit; external name 'FPC_DO_EXIT';
  1133. Procedure fpc_lib_exit;[Public,Alias:'FPC_LIB_EXIT'];
  1134. begin
  1135. InternalExit;
  1136. end;
  1137. Procedure Halt(ErrNum: TExitCode);noreturn;
  1138. Begin
  1139. {$ifdef FPC_HAS_FEATURE_EXITCODE}
  1140. {$ifdef FPC_LIMITED_EXITCODE}
  1141. if ErrNum > maxExitCode then
  1142. ExitCode:=255
  1143. else
  1144. {$endif FPC_LIMITED_EXITCODE}
  1145. ExitCode:=ErrNum;
  1146. {$endif FPC_HAS_FEATURE_EXITCODE}
  1147. internal_do_exit;
  1148. end;
  1149. {$ifndef FPC_SYSTEM_HAS_BACKTRACESTR}
  1150. function SysBackTraceStr (Addr: CodePointer): ShortString;
  1151. begin
  1152. SysBackTraceStr:=' $'+hexstr(addr);
  1153. end;
  1154. {$endif FPC_SYSTEM_HAS_BACKTRACESTR}
  1155. {$ifndef FPC_SYSTEM_HAS_CAPTUREBACKTRACE}
  1156. function CaptureBacktrace(skipframes,count:sizeint;frames:PCodePointer):sizeint;
  1157. var
  1158. curr_frame,prev_frame: pointer;
  1159. curr_addr: codepointer;
  1160. i: sizeint;
  1161. begin
  1162. curr_frame:=get_frame;
  1163. curr_addr:=get_pc_addr;
  1164. prev_frame:=curr_frame;
  1165. get_caller_stackinfo(curr_frame,curr_addr);
  1166. i:=-skipframes;
  1167. while (i<count) and (curr_frame>prev_frame) and
  1168. (curr_frame<StackTop) do
  1169. begin
  1170. if (curr_addr=nil) or
  1171. (curr_frame=nil) then
  1172. break;
  1173. if (i>=0) then
  1174. frames[i]:=curr_addr;
  1175. inc(i);
  1176. prev_frame:=curr_frame;
  1177. get_caller_stackinfo(curr_frame,curr_addr);
  1178. end;
  1179. if i<0 then
  1180. result:=0
  1181. else
  1182. result:=i;
  1183. end;
  1184. {$endif FPC_SYSTEM_HAS_CAPTUREBACKTRACE}
  1185. Procedure HandleErrorAddrFrame (Errno : TExitCode;addr : CodePointer; frame : Pointer);[public,alias:'FPC_BREAK_ERROR']; {$ifdef CPUI386} register; {$endif}
  1186. begin
  1187. If codepointer(ErrorProc)<>Nil then
  1188. ErrorProc(Errno,addr,frame);
  1189. errorcode:=word(Errno);
  1190. erroraddr:=addr;
  1191. errorbase:=frame;
  1192. Halt(errorcode);
  1193. end;
  1194. { This is used internally by system skip first level,
  1195. and generated the same output as before, when
  1196. HandleErrorFrame function was used internally. }
  1197. Procedure HandleErrorAddrFrameInd (Errno : TExitCode;addr : CodePointer; frame : Pointer);
  1198. begin
  1199. get_caller_stackinfo (frame, addr);
  1200. HandleErrorAddrFrame (Errno,addr,frame);
  1201. end;
  1202. Procedure HandleErrorFrame (Errno : TExitCode;frame : Pointer);
  1203. {
  1204. Procedure to handle internal errors, i.e. not user-invoked errors
  1205. Internal function should ALWAYS call HandleError instead of RunError.
  1206. Can be used for exception handlers to specify the frame
  1207. }
  1208. begin
  1209. HandleErrorAddrFrame(Errno,get_caller_addr(frame),get_caller_frame(frame));
  1210. end;
  1211. procedure fpc_handleerror (Errno : TExitCode); compilerproc; [public,alias : 'FPC_HANDLEERROR'];
  1212. {
  1213. Procedure to handle internal errors, i.e. not user-invoked errors
  1214. Internal function should ALWAYS call HandleError instead of RunError.
  1215. }
  1216. begin
  1217. HandleErrorAddrFrameInd(Errno,get_pc_addr,get_frame);
  1218. end;
  1219. procedure RunError(w : word);[alias: 'FPC_RUNERROR'];noreturn;
  1220. var
  1221. bp : pointer;
  1222. pcaddr : codepointer;
  1223. begin
  1224. errorcode:=w;
  1225. pcaddr:=get_pc_addr;
  1226. bp:=get_frame;
  1227. get_caller_stackinfo(bp,pcaddr);
  1228. erroraddr:=pcaddr;
  1229. errorbase:=bp;
  1230. Halt(errorcode);
  1231. end;
  1232. Procedure RunError;{$ifdef SYSTEMINLINE}inline;{$endif}noreturn;
  1233. Begin
  1234. RunError (0);
  1235. End;
  1236. Procedure Halt;{$ifdef SYSTEMINLINE}inline;{$endif}noreturn;
  1237. Begin
  1238. Halt(0);
  1239. End;
  1240. Procedure Error(RunTimeError : TRunTimeError);
  1241. begin
  1242. RunError(RuntimeErrorExitCodes[RunTimeError]);
  1243. end;
  1244. Procedure dump_stack(var f : text;fp : Pointer; addr : CodePointer);
  1245. var
  1246. i : ObjpasInt;
  1247. prevfp : Pointer;
  1248. is_dev : boolean;
  1249. Begin
  1250. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1251. try
  1252. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1253. { Frame of this procedure acts as StackBottom, fp values below that are invalid. }
  1254. prevfp:=get_frame;
  1255. i:=0;
  1256. is_dev:=do_isdevice(textrec(f).Handle);
  1257. { sanity checks, new frame pointer must be always greater than the old one, further
  1258. it must point into the stack area, else something went wrong }
  1259. while (fp>prevfp) and (fp<StackTop) do
  1260. Begin
  1261. prevfp:=fp;
  1262. get_caller_stackinfo(fp,addr);
  1263. if (addr=nil) then
  1264. break;
  1265. Writeln(f,BackTraceStrFunc(addr));
  1266. if (fp=nil) then
  1267. break;
  1268. Inc(i);
  1269. If ((i>max_frame_dump) and is_dev) or (i>256) Then
  1270. break;
  1271. End;
  1272. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1273. except
  1274. { prevent endless dump if an exception occurred }
  1275. end;
  1276. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1277. End;
  1278. procedure dump_stack(var f: text; skipframes: longint);
  1279. var
  1280. i,count: ObjpasInt;
  1281. frames: array [0..255] of codepointer;
  1282. begin
  1283. if do_isdevice(textrec(f).handle) then
  1284. count:=max_frame_dump
  1285. else
  1286. count:=255;
  1287. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1288. try
  1289. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1290. count:=CaptureBacktrace(skipframes+1,count,@frames[0]);
  1291. for i:=0 to count-1 do
  1292. writeln(f,BackTraceStrFunc(frames[i]));
  1293. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1294. except
  1295. end;
  1296. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1297. end;
  1298. {$ifdef FPC_HAS_FEATURE_EXCEPTIONS}
  1299. procedure DumpExceptionBackTrace(var f:text);
  1300. var
  1301. FrameNumber,
  1302. FrameCount : ObjpasInt;
  1303. Frames : PCodePointer;
  1304. begin
  1305. if RaiseList=nil then
  1306. exit;
  1307. WriteLn(f,BackTraceStrFunc(RaiseList^.Addr));
  1308. FrameCount:=RaiseList^.Framecount;
  1309. Frames:=RaiseList^.Frames;
  1310. for FrameNumber := 0 to FrameCount-1 do
  1311. WriteLn(f,BackTraceStrFunc(Frames[FrameNumber]));
  1312. end;
  1313. {$endif FPC_HAS_FEATURE_EXCEPTIONS}
  1314. {$ifdef FPC_HAS_FEATURE_HEAP}
  1315. Type
  1316. PExitProcInfo = ^TExitProcInfo;
  1317. TExitProcInfo = Record
  1318. Next : PExitProcInfo;
  1319. SaveExit : CodePointer;
  1320. Proc : TProcedure;
  1321. End;
  1322. const
  1323. ExitProcList: PExitProcInfo = nil;
  1324. Procedure DoExitProc;
  1325. var
  1326. P : PExitProcInfo;
  1327. Proc : TProcedure;
  1328. Begin
  1329. P:=ExitProcList;
  1330. ExitProcList:=P^.Next;
  1331. ExitProc:=P^.SaveExit;
  1332. Proc:=P^.Proc;
  1333. DisPose(P);
  1334. Proc();
  1335. End;
  1336. Procedure AddExitProc(Proc: TProcedure);
  1337. var
  1338. P : PExitProcInfo;
  1339. Begin
  1340. New(P);
  1341. P^.Next:=ExitProcList;
  1342. P^.SaveExit:=ExitProc;
  1343. P^.Proc:=Proc;
  1344. ExitProcList:=P;
  1345. ExitProc:=@DoExitProc;
  1346. End;
  1347. {$endif FPC_HAS_FEATURE_HEAP}
  1348. {$ifdef FPC_HAS_FEATURE_HEAP}
  1349. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1350. function ArrayStringToPPchar(const S:Array of AnsiString;reserveentries:Longint):ppansichar; // const ?
  1351. {$ifdef EXCLUDE_COMPLEX_PROCS}
  1352. begin
  1353. runerror(217);
  1354. end;
  1355. {$else EXCLUDE_COMPLEX_PROCS}
  1356. // Extra allocate reserveentries pansichar's at the beginning (default param=0 after 1.0.x ?)
  1357. // Note: for internal use by skilled programmers only
  1358. // if "s" goes out of scope in the parent procedure, the pointer is dangling.
  1359. var p : ppansichar;
  1360. i : ObjpasInt;
  1361. begin
  1362. if High(s)<Low(s) Then Exit(NIL);
  1363. Getmem(p,sizeof(pansichar)*(high(s)-low(s)+ReserveEntries+2)); // one more for NIL, one more
  1364. // for cmd
  1365. if p=nil then
  1366. begin
  1367. {$ifdef xunix}
  1368. fpseterrno(ESysEnomem);
  1369. {$endif}
  1370. exit(NIL);
  1371. end;
  1372. for i:=low(s) to high(s) do
  1373. p[i+Reserveentries]:=pansichar(s[i]);
  1374. p[high(s)+1+Reserveentries]:=nil;
  1375. ArrayStringToPPchar:=p;
  1376. end;
  1377. {$endif EXCLUDE_COMPLEX_PROCS}
  1378. Function StringToPPChar(Var S:AnsiString;ReserveEntries:integer):ppansichar;
  1379. {
  1380. Create a PPAnsiChar to structure of pchars which are the arguments specified
  1381. in the string S. Especially useful for creating an ArgV for Exec-calls
  1382. }
  1383. begin
  1384. StringToPPChar:=StringToPPChar(PAnsiChar(S),ReserveEntries);
  1385. end;
  1386. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1387. Function StringToPPChar(S: PAnsiChar;ReserveEntries:integer):ppansichar;
  1388. var
  1389. i,nr : ObjpasInt;
  1390. Buf : ^ansichar;
  1391. p : ppansichar;
  1392. begin
  1393. buf:=s;
  1394. nr:=1;
  1395. while (buf^<>#0) do // count nr of args
  1396. begin
  1397. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1398. inc(buf);
  1399. inc(nr);
  1400. if buf^='"' Then // quotes argument?
  1401. begin
  1402. inc(buf);
  1403. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1404. inc(buf);
  1405. if buf^='"' then // skip closing quote.
  1406. inc(buf);
  1407. end
  1408. else
  1409. begin // else std
  1410. while not (buf^ in [' ',#0,#9,#10]) do
  1411. inc(buf);
  1412. end;
  1413. end;
  1414. getmem(p,(ReserveEntries+nr)*sizeof(pansichar));
  1415. StringToPPChar:=p;
  1416. if p=nil then
  1417. begin
  1418. {$ifdef xunix}
  1419. fpseterrno(ESysEnomem);
  1420. {$endif}
  1421. exit;
  1422. end;
  1423. for i:=1 to ReserveEntries do inc(p); // skip empty slots
  1424. buf:=s;
  1425. while (buf^<>#0) do
  1426. begin
  1427. while (buf^ in [' ',#9,#10]) do // Kill separators.
  1428. begin
  1429. buf^:=#0;
  1430. inc(buf);
  1431. end;
  1432. if buf^='"' Then // quotes argument?
  1433. begin
  1434. inc(buf);
  1435. p^:=buf;
  1436. inc(p);
  1437. p^:=nil;
  1438. while not (buf^ in [#0,'"']) do // then end of argument is end of string or next quote
  1439. inc(buf);
  1440. if buf^='"' then // skip closing quote.
  1441. begin
  1442. buf^:=#0;
  1443. inc(buf);
  1444. end;
  1445. end
  1446. else
  1447. begin
  1448. p^:=buf;
  1449. inc(p);
  1450. p^:=nil;
  1451. while not (buf^ in [' ',#0,#9,#10]) do
  1452. inc(buf);
  1453. end;
  1454. end;
  1455. end;
  1456. {$endif FPC_HAS_FEATURE_HEAP}
  1457. {*****************************************************************************
  1458. Abstract/Assert support.
  1459. *****************************************************************************}
  1460. procedure fpc_emptymethod;[public,alias : 'FPC_EMPTYMETHOD'];
  1461. begin
  1462. end;
  1463. procedure fpc_AbstractErrorIntern;compilerproc;[public,alias : 'FPC_ABSTRACTERROR'];
  1464. begin
  1465. If codepointer(AbstractErrorProc)<>nil then
  1466. AbstractErrorProc();
  1467. HandleErrorAddrFrameInd(211,get_pc_addr,get_frame);
  1468. end;
  1469. Procedure fpc_assert(Const Msg,FName:Shortstring;LineNo:Longint;
  1470. ErrorAddr:Pointer); [Public,Alias : 'FPC_ASSERT']; compilerproc;
  1471. begin
  1472. if codepointer(AssertErrorProc)<>nil then
  1473. AssertErrorProc(Msg,FName,LineNo,ErrorAddr)
  1474. else
  1475. HandleErrorAddrFrameInd(227,get_pc_addr,get_frame);
  1476. end;
  1477. Procedure SysAssert(Const Msg,FName:Shortstring;LineNo:Longint;ErrorAddr:Pointer);
  1478. begin
  1479. {$ifdef FPC_HAS_FEATURE_CONSOLEIO}
  1480. If Length(msg)=0 then
  1481. write(stderr,'Assertion failed')
  1482. else
  1483. write(stderr,msg);
  1484. Writeln(stderr,' (',FName,', line ',LineNo,').');
  1485. Writeln(stderr,'');
  1486. Halt(227);
  1487. {$endif FPC_HAS_FEATURE_CONSOLEIO}
  1488. end;
  1489. {*****************************************************************************
  1490. SetJmp/LongJmp support.
  1491. *****************************************************************************}
  1492. {$i setjump.inc}
  1493. {$pop} //{$I-,R-,Q-} before 'procedure fpc_rangeerror'
  1494. {*****************************************************************************
  1495. Heap
  1496. *****************************************************************************}
  1497. {$i sysheap.inc}
  1498. {$IFDEF LEGACYHEAP}
  1499. {$i oldheap.inc}
  1500. {$ELSE}
  1501. {$i heap.inc}
  1502. {$ENDIF LEGACYHEAP}
  1503. {*****************************************************************************
  1504. Thread support
  1505. *****************************************************************************}
  1506. {$ifdef FPC_HAS_FEATURE_THREADING}
  1507. { Generic threadmanager }
  1508. {$i thread.inc}
  1509. { Generic threadvar support }
  1510. {$i threadvr.inc}
  1511. {$ifdef DISABLE_NO_THREAD_MANAGER}
  1512. { OS Dependent implementation }
  1513. {$i systhrd.inc}
  1514. {$endif DISABLE_NO_THREAD_MANAGER}
  1515. {$endif FPC_HAS_FEATURE_THREADING}
  1516. {*****************************************************************************
  1517. Dynamic library support
  1518. *****************************************************************************}
  1519. {$ifdef FPC_HAS_FEATURE_DYNLIBS}
  1520. {$i dynlib.inc}
  1521. {$ifdef DISABLE_NO_DYNLIBS_MANAGER}
  1522. { OS Dependant implementation }
  1523. {$i sysdl.inc}
  1524. {$endif DISABLE_NO_DYNLIBS_MANAGER}
  1525. {$endif FPC_HAS_FEATURE_DYNLIBS}
  1526. {*****************************************************************************
  1527. File Handling
  1528. *****************************************************************************}
  1529. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1530. { Allow slash and backslash as separators }
  1531. procedure DoDirSeparators(var p: pansichar; inplace: boolean = true);
  1532. var
  1533. i : ObjpasInt;
  1534. len : sizeint;
  1535. newp : pansichar;
  1536. begin
  1537. len:=length(p);
  1538. newp:=nil;
  1539. for i:=0 to len do
  1540. if p[i] in AllowDirectorySeparators then
  1541. begin
  1542. if not inplace and
  1543. not assigned(newp) then
  1544. begin
  1545. getmem(newp,len+1);
  1546. move(p^,newp^,len+1);
  1547. p:=newp;
  1548. end;
  1549. p[i]:=DirectorySeparator;
  1550. end;
  1551. end;
  1552. procedure DoDirSeparators(var p: pwidechar; inplace: boolean = true);
  1553. var
  1554. i : ObjpasInt;
  1555. len : sizeint;
  1556. newp : pwidechar;
  1557. begin
  1558. len:=length(p);
  1559. newp:=nil;
  1560. for i:=0 to len do
  1561. if (ord(p[i])<255) and
  1562. (ansichar(ord(p[i])) in AllowDirectorySeparators) then
  1563. begin
  1564. if not inplace and
  1565. not assigned(newp) then
  1566. begin
  1567. getmem(newp,(len+1)*2);
  1568. move(p^,newp^,(len+1)*2);
  1569. p:=newp;
  1570. end;
  1571. p[i]:=DirectorySeparator;
  1572. end;
  1573. end;
  1574. procedure DoDirSeparators(var p:shortstring);
  1575. var
  1576. i : ObjpasInt;
  1577. begin
  1578. for i:=1 to length(p) do
  1579. if p[i] in AllowDirectorySeparators then
  1580. p[i]:=DirectorySeparator;
  1581. end;
  1582. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1583. procedure DoDirSeparators(var ps:RawByteString);
  1584. var
  1585. i : ObjpasInt;
  1586. p : pansichar;
  1587. unique : boolean;
  1588. begin
  1589. unique:=false;
  1590. for i:=1 to length(ps) do
  1591. if ps[i] in AllowDirectorySeparators then
  1592. begin
  1593. if not unique then
  1594. begin
  1595. uniquestring(ps);
  1596. p:=pansichar(ps);
  1597. unique:=true;
  1598. end;
  1599. p[i-1]:=DirectorySeparator;
  1600. end;
  1601. end;
  1602. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1603. {$ifdef FPC_HAS_FEATURE_UNICODESTRINGS}
  1604. procedure DoDirSeparators(var ps:UnicodeString);
  1605. var
  1606. i : ObjpasInt;
  1607. p : pwidechar;
  1608. unique : boolean;
  1609. begin
  1610. unique:=false;
  1611. for i:=1 to length(ps) do
  1612. if ps[i] in AllowDirectorySeparators then
  1613. begin
  1614. if not unique then
  1615. begin
  1616. uniquestring(ps);
  1617. p:=pwidechar(ps);
  1618. unique:=true;
  1619. end;
  1620. p[i-1]:=DirectorySeparator;
  1621. end;
  1622. end;
  1623. {$endif FPC_HAS_FEATURE_UNICODESTRINGS}
  1624. {$endif FPC_HAS_FEATURE_FILEIO}
  1625. { OS dependent low level file functions }
  1626. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1627. {$i sysfile.inc}
  1628. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1629. {$ifdef FPC_ANSI_TEXTFILEREC}
  1630. procedure do_open(var f; p: pansichar; flags: longint; pchangeable: boolean);
  1631. var
  1632. u: UnicodeString;
  1633. begin
  1634. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1635. do_open(f,pwidechar(u),flags,true);
  1636. end;
  1637. procedure do_erase(p: pansichar; pchangeable: boolean);
  1638. var
  1639. u: UnicodeString;
  1640. begin
  1641. widestringmanager.Ansi2UnicodeMoveProc(p,DefaultFileSystemCodePage,u,length(p));
  1642. do_erase(pwidechar(u),true);
  1643. end;
  1644. procedure do_rename(src, dst: pansichar; srcchangeable, dstchangeable: boolean);
  1645. var
  1646. usrc, udst: UnicodeString;
  1647. begin
  1648. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1649. widestringmanager.Ansi2UnicodeMoveProc(dst,DefaultFileSystemCodePage,udst,length(dst));
  1650. do_rename(pwidechar(usrc),pwidechar(udst),true,true);
  1651. end;
  1652. procedure do_rename(src: pansichar; dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1653. var
  1654. usrc: UnicodeString;
  1655. begin
  1656. widestringmanager.Ansi2UnicodeMoveProc(src,DefaultFileSystemCodePage,usrc,length(src));
  1657. do_rename(pwidechar(usrc),dst,true,dstchangeable);
  1658. end;
  1659. {$endif FPC_ANSI_TEXTFILEREC}
  1660. {$endif not FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1661. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1662. {$ifndef FPC_ANSI_TEXTFILEREC}
  1663. procedure do_open(var f; p: pwidechar; flags: longint; pchangeable: boolean);
  1664. var
  1665. s: RawByteString;
  1666. begin
  1667. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1668. do_open(f,pansichar(s),flags,true);
  1669. end;
  1670. procedure do_erase(p: pwidechar; pchangeable: boolean);
  1671. var
  1672. s: RawByteString;
  1673. begin
  1674. widestringmanager.Unicode2AnsiMoveProc(p,s,DefaultFileSystemCodePage,length(p));
  1675. do_erase(pansichar(s),true);
  1676. end;
  1677. procedure do_rename(src, dst: pwidechar; srcchangeable, dstchangeable: boolean);
  1678. var
  1679. rsrc, rdst: RawByteString;
  1680. begin
  1681. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1682. widestringmanager.Unicode2AnsiMoveProc(dst,rdst,DefaultFileSystemCodePage,length(dst));
  1683. do_rename(pansichar(rsrc),pansichar(rdst),true,true);
  1684. end;
  1685. procedure do_rename(src: pwidechar; dst: pansichar; srcchangeable, dstchangeable: boolean);
  1686. var
  1687. rsrc: RawByteString;
  1688. begin
  1689. widestringmanager.Unicode2AnsiMoveProc(src,rsrc,DefaultFileSystemCodePage,length(src));
  1690. do_rename(pansichar(rsrc),dst,true,dstchangeable);
  1691. end;
  1692. {$endif not FPC_ANSI_TEXTFILEREC}
  1693. {$endif not FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1694. {$endif FPC_HAS_FEATURE_FILEIO}
  1695. { helper for targets supporting no ansistrings, it is used
  1696. by non-ansistring code }
  1697. function min(v1,v2 : SizeInt) : SizeInt;
  1698. begin
  1699. if v1<v2 then
  1700. result:=v1
  1701. else
  1702. result:=v2;
  1703. end;
  1704. {$ifdef FPC_HAS_FEATURE_TEXTIO}
  1705. { Text file }
  1706. {$i text.inc}
  1707. {$endif FPC_HAS_FEATURE_TEXTIO}
  1708. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1709. { Untyped file }
  1710. {$i file.inc}
  1711. { Typed file }
  1712. {$i typefile.inc}
  1713. {$endif FPC_HAS_FEATURE_FILEIO}
  1714. {*****************************************************************************
  1715. Directory Handling
  1716. *****************************************************************************}
  1717. {$ifdef FPC_HAS_FEATURE_FILEIO}
  1718. { OS dependent dir functions }
  1719. {$i sysdir.inc}
  1720. {$ifdef FPC_HAS_FEATURE_ANSISTRINGS}
  1721. {$ifndef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1722. procedure do_getdir(drivenr : byte;var dir : rawbytestring);
  1723. var
  1724. u: unicodestring;
  1725. begin
  1726. Do_getdir(drivenr,u);
  1727. widestringmanager.Unicode2AnsiMoveProc(pwidechar(u),dir,DefaultRTLFileSystemCodePage,length(u));
  1728. end;
  1729. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1730. Procedure MkDir(Const s: RawByteString);[IOCheck];
  1731. Begin
  1732. If (Length(s)=0) or (InOutRes <> 0) then
  1733. exit;
  1734. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1735. Do_mkdir(ToSingleByteFileSystemEncodedFileName(S));
  1736. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1737. Do_mkdir(S);
  1738. {$endif}
  1739. end;
  1740. Procedure RmDir(Const s: RawByteString);[IOCheck];
  1741. Begin
  1742. If (Length(s)=0) or (InOutRes <> 0) then
  1743. exit;
  1744. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1745. Do_rmdir(ToSingleByteFileSystemEncodedFileName(S));
  1746. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1747. Do_rmdir(S);
  1748. {$endif}
  1749. End;
  1750. Procedure ChDir(Const s: RawByteString);[IOCheck];
  1751. Begin
  1752. If (Length(s)=0) or (InOutRes <> 0) then
  1753. exit;
  1754. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1755. Do_chdir(ToSingleByteFileSystemEncodedFileName(S));
  1756. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1757. Do_chdir(S);
  1758. {$endif}
  1759. End;
  1760. Procedure getdir(drivenr:byte;Var dir:rawbytestring);
  1761. begin
  1762. Do_getdir(drivenr,dir);
  1763. { we should return results in the DefaultRTLFileSystemCodePage -> convert if
  1764. necessary }
  1765. setcodepage(dir,DefaultRTLFileSystemCodePage,true);
  1766. end;
  1767. { the generic shortstring ones are only implemented elsewhere for systems *not*
  1768. supporting ansi/unicodestrings; for now assume there are no systems that
  1769. support unicodestrings but not ansistrings }
  1770. { avoid double string conversions }
  1771. {$ifdef FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1772. function GetDirStrFromShortstring(const s: shortstring): RawByteString;
  1773. begin
  1774. GetDirStrFromShortstring:=ToSingleByteFileSystemEncodedFileName(ansistring(s));
  1775. end;
  1776. {$else FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1777. function GetDirStrFromShortstring(const s: shortstring): UnicodeString;
  1778. begin
  1779. GetDirStrFromShortstring:=s;
  1780. end;
  1781. {$endif FPCRTL_FILESYSTEM_SINGLE_BYTE_API}
  1782. Procedure MkDir(Const s: shortstring);[IOCheck];
  1783. Begin
  1784. If (Length(s)=0) or (InOutRes <> 0) then
  1785. exit;
  1786. Do_mkdir(GetDirStrFromShortstring(S));
  1787. End;
  1788. Procedure RmDir(Const s: shortstring);[IOCheck];
  1789. Begin
  1790. If (Length(s)=0) or (InOutRes <> 0) then
  1791. exit;
  1792. Do_rmdir(GetDirStrFromShortstring(S));
  1793. End;
  1794. Procedure ChDir(Const s: shortstring);[IOCheck];
  1795. Begin
  1796. If (Length(S)=0) or (InOutRes <> 0) then
  1797. exit;
  1798. Do_chdir(GetDirStrFromShortstring(S));
  1799. End;
  1800. Procedure getdir(drivenr:byte;Var dir:shortstring);
  1801. var
  1802. s: rawbytestring;
  1803. begin
  1804. Do_getdir(drivenr,s);
  1805. if length(s)<=high(dir) then
  1806. dir:=s
  1807. else
  1808. inoutres:=3;
  1809. end;
  1810. {$endif FPC_HAS_FEATURE_ANSISTRINGS}
  1811. {$if defined(FPC_HAS_FEATURE_WIDESTRINGS)}
  1812. {$ifndef FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1813. { overloads required for mkdir/rmdir/chdir to ensure that the string is
  1814. converted to the right code page }
  1815. procedure do_mkdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1816. begin
  1817. do_mkdir(ToSingleByteFileSystemEncodedFileName(s));
  1818. end;
  1819. procedure do_rmdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1820. begin
  1821. do_rmdir(ToSingleByteFileSystemEncodedFileName(s));
  1822. end;
  1823. procedure do_chdir(const s: unicodestring); {$ifdef SYSTEMINLINE}inline;{$endif}
  1824. begin
  1825. do_chdir(ToSingleByteFileSystemEncodedFileName(s));
  1826. end;
  1827. procedure do_getdir(drivenr : byte;var dir : unicodestring);
  1828. var
  1829. s: rawbytestring;
  1830. begin
  1831. Do_getdir(drivenr,s);
  1832. dir:=unicodestring(s);
  1833. end;
  1834. {$endif FPCRTL_FILESYSTEM_TWO_BYTE_API}
  1835. Procedure MkDir(Const s: UnicodeString);[IOCheck];
  1836. Begin
  1837. if (Length(s)=0) or (InOutRes <> 0) then
  1838. exit;
  1839. Do_mkdir(S);
  1840. End;
  1841. Procedure RmDir(Const s: UnicodeString);[IOCheck];
  1842. Begin
  1843. if (Length(s)=0) or (InOutRes <> 0) then
  1844. exit;
  1845. Do_rmdir(S);
  1846. End;
  1847. Procedure ChDir(Const s: UnicodeString);[IOCheck];
  1848. Begin
  1849. if (Length(s)=0) or (InOutRes <> 0) then
  1850. exit;
  1851. Do_chdir(S);
  1852. End;
  1853. Procedure getdir(drivenr:byte;Var dir:unicodestring);
  1854. begin
  1855. Do_getdir(drivenr,dir);
  1856. end;
  1857. {$endif FPC_HAS_FEATURE_WIDESTRINGS}
  1858. {$endif FPC_HAS_FEATURE_FILEIO}
  1859. {*****************************************************************************
  1860. Resources support
  1861. *****************************************************************************}
  1862. {$i sysres.inc}
  1863. const
  1864. CtrlBreakHandler: TCtrlBreakHandler = nil;
  1865. {$IFNDEF FPC_HAS_SETCTRLBREAKHANDLER}
  1866. (* It is possible to provide platform specific implementation performing *)
  1867. (* special initialization; default implementation just sets the procedural *)
  1868. (* variable to make it available for use from the exception handler. *)
  1869. function SysSetCtrlBreakHandler (Handler: TCtrlBreakHandler): TCtrlBreakHandler;
  1870. begin
  1871. (* Return either nil or previous handler *)
  1872. SysSetCtrlBreakHandler := CtrlBreakHandler;
  1873. CtrlBreakHandler := Handler;
  1874. end;
  1875. {$ENDIF FPC_HAS_SETCTRLBREAKHANDLER}