system.inc 54 KB

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