system.inc 56 KB

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