system.inc 53 KB

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