system.inc 56 KB

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