system.inc 57 KB

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