system.inc 54 KB

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