system.inc 54 KB

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