system.inc 59 KB

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