2
0

system.inc 56 KB

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