system.inc 58 KB

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