system.inc 54 KB

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