system.inc 53 KB

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