system.inc 56 KB

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