system.inc 56 KB

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