system.inc 52 KB

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