system.inc 51 KB

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