heap.inc 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  1. {
  2. This file is part of the Free Pascal run time library.
  3. Copyright (c) 1999-2000 by the Free Pascal development team.
  4. functions for heap management in the data segment
  5. See the file COPYING.FPC, included in this distribution,
  6. for details about the copyright.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  10. **********************************************************************}
  11. {****************************************************************************}
  12. { Do not use standard memory manager }
  13. { $define HAS_MEMORYMANAGER}
  14. { Memory manager }
  15. const
  16. MemoryManager: TMemoryManager = (
  17. NeedLock: false; // Obsolete
  18. GetMem: {$ifndef FPC_NO_DEFAULT_HEAP}@SysGetMem{$else}nil{$endif};
  19. FreeMem: {$ifndef FPC_NO_DEFAULT_HEAP}@SysFreeMem{$else}nil{$endif};
  20. FreeMemSize: {$ifndef FPC_NO_DEFAULT_HEAP}@SysFreeMemSize{$else}nil{$endif};
  21. AllocMem: {$ifndef FPC_NO_DEFAULT_HEAP}@SysAllocMem{$else}nil{$endif};
  22. ReAllocMem: {$ifndef FPC_NO_DEFAULT_HEAP}@SysReAllocMem{$else}nil{$endif};
  23. MemSize: {$ifndef FPC_NO_DEFAULT_HEAP}@SysMemSize{$else}nil{$endif};
  24. InitThread: nil;
  25. DoneThread: nil;
  26. RelocateHeap: nil;
  27. GetHeapStatus: {$ifndef FPC_NO_DEFAULT_HEAP}@SysGetHeapStatus{$else}nil{$endif};
  28. GetFPCHeapStatus: {$ifndef FPC_NO_DEFAULT_HEAP}@SysGetFPCHeapStatus{$else}nil{$endif};
  29. ); {$ifdef FPC_NO_DEFAULT_HEAP} public name 'FPC_SYSTEM_MEMORYMANAGER'; {$endif}
  30. {*****************************************************************************
  31. Memory Manager
  32. *****************************************************************************}
  33. procedure GetMemoryManager(var MemMgr:TMemoryManager);
  34. begin
  35. MemMgr := MemoryManager;
  36. end;
  37. procedure SetMemoryManager(const MemMgr:TMemoryManager);
  38. begin
  39. MemoryManager := MemMgr;
  40. end;
  41. function IsMemoryManagerSet:Boolean;
  42. begin
  43. {$if defined(HAS_MEMORYMANAGER) or defined(FPC_NO_DEFAULT_HEAP)}
  44. Result:=false;
  45. {$else not FPC_NO_DEFAULT_HEAP}
  46. IsMemoryManagerSet := (MemoryManager.GetMem<>@SysGetMem)
  47. or (MemoryManager.FreeMem<>@SysFreeMem);
  48. {$endif HAS_MEMORYMANAGER or FPC_NO_DEFAULT_HEAP}
  49. end;
  50. {$ifdef FPC_HAS_FEATURE_HEAP}
  51. procedure GetMem(Out p:pointer;Size:ptruint);
  52. begin
  53. p := MemoryManager.GetMem(Size);
  54. end;
  55. procedure GetMemory(Out p:pointer;Size:ptruint);
  56. begin
  57. GetMem(p,size);
  58. end;
  59. procedure FreeMem(p:pointer;Size:ptruint);
  60. begin
  61. MemoryManager.FreeMemSize(p,Size);
  62. end;
  63. procedure FreeMemory(p:pointer;Size:ptruint);
  64. begin
  65. FreeMem(p,size);
  66. end;
  67. function GetHeapStatus:THeapStatus;
  68. begin
  69. Result:=MemoryManager.GetHeapStatus();
  70. end;
  71. function GetFPCHeapStatus:TFPCHeapStatus;
  72. begin
  73. Result:=MemoryManager.GetFPCHeapStatus();
  74. end;
  75. function MemSize(p:pointer):ptruint;
  76. begin
  77. MemSize := MemoryManager.MemSize(p);
  78. end;
  79. { Delphi style }
  80. function FreeMem(p:pointer):ptruint;
  81. begin
  82. FreeMem := MemoryManager.FreeMem(p);
  83. end;
  84. function FreeMemory(p:pointer):ptruint; cdecl;
  85. begin
  86. FreeMemory := FreeMem(p);
  87. end;
  88. function GetMem(size:ptruint):pointer;
  89. begin
  90. GetMem := MemoryManager.GetMem(Size);
  91. end;
  92. function GetMemory(size:ptruint):pointer; cdecl;
  93. begin
  94. GetMemory := GetMem(size);
  95. end;
  96. function AllocMem(Size:ptruint):pointer;
  97. begin
  98. AllocMem := MemoryManager.AllocMem(size);
  99. end;
  100. function ReAllocMem(var p:pointer;Size:ptruint):pointer;
  101. begin
  102. ReAllocMem := MemoryManager.ReAllocMem(p,size);
  103. end;
  104. function ReAllocMemory(p:pointer;Size:ptruint):pointer; cdecl;
  105. begin
  106. ReAllocMemory := ReAllocMem(p,size);
  107. end;
  108. { Needed for calls from Assembler }
  109. function fpc_getmem(size:ptruint):pointer;compilerproc;[public,alias:'FPC_GETMEM'];
  110. begin
  111. fpc_GetMem := MemoryManager.GetMem(size);
  112. end;
  113. procedure fpc_freemem(p:pointer);compilerproc;[public,alias:'FPC_FREEMEM'];
  114. begin
  115. MemoryManager.FreeMem(p);
  116. end;
  117. {$ifndef HAS_MEMORYMANAGER}
  118. type
  119. {
  120. We use 'fixed' size chunks for small allocations,
  121. os chunks with variable sized blocks for bigger allocations,
  122. and (almost) directly use os chunks for huge allocations.
  123. * a block is an area allocated by user
  124. * a chunk is a block plus our bookkeeping
  125. * an os chunk is a collection of chunks
  126. Memory layout:
  127. fixed: < CommonHeader > [ ... user data ... ]
  128. variable: [ VarHeader < CommonHeader > ] [ ... user data ... ]
  129. huge: HugeChunk < CommonHeader > [ ... user data ... ]
  130. When all chunks in an os chunk are free, we keep a few around
  131. but otherwise it will be freed to the OS.
  132. }
  133. {$ifdef ENDIAN_LITTLE}
  134. {$define HEAP_INC_USE_SETS} { Potentially better codegen than “or 1 shl” etc. (at least on x86). Can be adapted for big endian, too, but I have no such platform to test. }
  135. {$endif ENDIAN_LITTLE}
  136. HeapInc = object
  137. const
  138. { Alignment requirement for blocks. All fixed sizes (among other things) are assumed to be divisible. }
  139. Alignment = 2 * sizeof(pointer);
  140. { Fixed chunk sizes are:
  141. ┌──── step = 16 ────┐┌─── step = 32 ────┐┌──── step = 48 ───┐┌ step 64 ┐
  142. 16, 32, 48, 64, 80, 96, 128, 160, 192, 224, 272, 320, 368, 416, 480, 544
  143. #0 #1 #2 #3 #4 #5 #6 #7 #8 #9 #10 #11 #12 #13 #14 #15 }
  144. MinFixedHeaderAndPayload = 16;
  145. MaxFixedHeaderAndPayload = 544;
  146. FixedSizesCount = 16;
  147. FixedSizes: array[0 .. FixedSizesCount - 1] of uint16 = (16, 32, 48, 64, 80, 96, 128, 160, 192, 224, 272, 320, 368, 416, 480, 544);
  148. SizeMinus1Div16ToIndex: array[0 .. (MaxFixedHeaderAndPayload - 1) div 16] of uint8 =
  149. { 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224, 240, 256, 272, 288, 304, 320, 336, 352, 368, 384, 400, 416, 432, 448, 464, 480, 496, 512, 528, 544 }
  150. ( 0, 1, 2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15);
  151. class function SizeMinus1ToIndex(sizeMinus1: SizeUint): SizeUint; static; inline; { sizeMinus1 + 1 ≤ MaxFixedHeaderAndPayload }
  152. class function IndexToSize(sizeIndex: SizeUint): SizeUint; static; inline;
  153. const
  154. OSChunkVarSizeQuant = 64 * 1024;
  155. FixedArenaSizeQuant = 4 * 1024;
  156. MinFixedArenaSize = 8 * 1024;
  157. MaxFixedArenaSize = 64 * 1024;
  158. MaxKeptFixedArenas = 4;
  159. { Adjustable part ends here~ }
  160. const
  161. SizeIndexBits = 1 + trunc(ln(FixedSizesCount - 1) / ln(2));
  162. SizeIndexMask = 1 shl SizeIndexBits - 1;
  163. FixedBitPos = {$if SizeIndexBits >= 4} SizeIndexBits {$else} 4 {$endif}; { Variable chunks use 4 low bits for used / last / prev. free / fixed arena. }
  164. FixedFlag = 1 shl FixedBitPos;
  165. FixedArenaOffsetShift = {$if FixedBitPos + 1 >= 5} FixedBitPos + 1 {$else} 5 {$endif}; { VarSizeQuant is expected to be 2^5. }
  166. UsedFlag = 1 shl 0;
  167. LastFlag = 1 shl 1;
  168. PrevIsFreeFlag = 1 shl 2;
  169. FixedArenaFlag = 1 shl 3;
  170. VarSizeQuant = 1 shl FixedArenaOffsetShift; {$if VarSizeQuant <> 32} {$error Should in principle work but explanations below assume exactly 32. :)} {$endif}
  171. VarSizeMask = uint32(-VarSizeQuant);
  172. HugeHeader = 0; { Special header value for huge chunks. FixedFlag must be 0, and the value must be impossible for a variable chunk. 0 turns out to be suitable. :) }
  173. { Variable chunk sizes, not counting extra MaxFixedHeaderAndPayload added to each of these:
  174. 32 sizes in the range +1 .. 1 024 (2^10) rounded up to the multiple of 32 = 2^ 5, + 0, max = 1 024 = %100 0000 0000
  175. 32 sizes in the range +1 .. 2 048 (2^11) rounded up to the multiple of 64 = 2^ 6, + 1024, max = 3 072 = %1100 0000 0000
  176. 32 sizes in the range +1 .. 4 096 (2^12) rounded up to the multiple of 128 = 2^ 7, + 1024 + 2048, max = 7 168 = %1 1100 0000 0000
  177. 32 sizes in the range +1 .. 8 192 (2^13) rounded up to the multiple of 256 = 2^ 8, + 2^10 + .. + 2^12, max = 15 360 = %11 1100 0000 0000
  178. 32 sizes in the range +1 .. 16 384 (2^14) rounded up to the multiple of 512 = 2^ 9, + 2^10 + .. + 2^13, max = 31 744 = %111 1100 0000 0000
  179. 32 sizes in the range +1 .. 32 768 (2^15) rounded up to the multiple of 1 024 = 2^10, + 2^10 + .. + 2^14, max = 64 512 = %1111 1100 0000 0000
  180. 32 sizes in the range +1 .. 65 536 (2^16) rounded up to the multiple of 2 048 = 2^11, + 2^10 + .. + 2^15, max = 130 048 = %1 1111 1100 0000 0000
  181. 32 sizes in the range +1 .. 131 072 (2^17) rounded up to the multiple of 4 096 = 2^12, + 2^10 + .. + 2^16, max = 261 120 = %11 1111 1100 0000 0000
  182. 32 sizes in the range +1 .. 262 144 (2^18) rounded up to the multiple of 8 192 = 2^13, + 2^10 + .. + 2^17, max = 523 264 = %111 1111 1100 0000 0000
  183. 32 sizes in the range +1 .. 524 288 (2^19) rounded up to the multiple of 16 384 = 2^14, + 2^10 + .. + 2^18, max = 1 047 552 = %1111 1111 1100 0000 0000 }
  184. FirstVarRangeP2 = 10;
  185. FirstVarStepP2 = FixedArenaOffsetShift; {$if FirstVarStepP2 <> 5} {$error :|} {$endif}
  186. VarSizeClassesCount = 10;
  187. VarSizesPerClass = 32;
  188. VarSizesCount = VarSizeClassesCount * VarSizesPerClass;
  189. L0BinSize = 32;
  190. { Minimum size of the chunk that can be added to varFree.
  191. Medium chunks can be smaller than this, all the way down to MinAnyVarHeaderAndPayload defined later in terms of things it must fit;
  192. they aren’t visible for varFree searches but are visible for merging with freed neighbors. }
  193. MinSearchableVarHeaderAndPayload = (MaxFixedHeaderAndPayload + 1 shl FirstVarStepP2 + VarSizeQuant - 1) and -VarSizeQuant;
  194. MaxVarHeaderAndPayload = (MaxFixedHeaderAndPayload + (1 shl VarSizeClassesCount - 1) shl FirstVarRangeP2) and -VarSizeQuant; {$if MaxVarHeaderAndPayload <> MaxFixedHeaderAndPayload + 1047552} {$error does not match the explanation above :D} {$endif}
  195. class function VarSizeToBinIndex(size: SizeUint; roundUp: boolean): SizeUint; static; inline; { roundUp is constant. }
  196. class function VarSizeToBinIndexUp(size: SizeUint): SizeUint; static; { ...but VarSizeToBinIndex is nontrivial enough to not inline except for the special case in VarFreeMap.Add. }
  197. class function BinIndexToVarSize(binIndex: SizeUint): SizeUint; static; inline;
  198. type
  199. { Common header of any memory chunk, residing immediately to the left of the ~payload~ (block).
  200. Fixed chunk header, assuming SizeIndexBits = 4:
  201. h[0:3] = size index (= h and SizeIndexMask)
  202. h[4] = 1 (h and FixedFlag <> 0)
  203. h[5:31] — offset in the FixedArena (= h shr FixedArenaOffsetShift)
  204. Variable chunk header, assuming SizeIndexBits = 4:
  205. h[0] = used flag (h and UsedFlag <> 0)
  206. h[1] = last flag (h and LastFlag <> 0)
  207. h[2] = previous is free flag (h and PrevIsFreeFlag <> 0)
  208. h[3] = fixed arena flag (h and FixedArenaFlag <> 0)
  209. h[4] = 0 (h and FixedFlag = 0)
  210. h[5:31] = size, rounded up to 32 (VarSizeQuant), shr 5; in other words, size = h and VarSizeMask.
  211. Huge chunk header:
  212. h[4] = 0 (h and FixedFlag = 0)
  213. h[0:31] = HugeHeader }
  214. pCommonHeader = ^CommonHeader;
  215. CommonHeader = record
  216. h: uint32;
  217. end;
  218. pThreadState = ^ThreadState;
  219. { Chunk that has been freed. Reuses the now-uninteresting payload, so payload must always fit its size.
  220. Used for fixed freelists and cross-thread to-free queue. }
  221. pFreeChunk = ^FreeChunk;
  222. FreeChunk = record
  223. next: pFreeChunk;
  224. end;
  225. OSChunkBase = object { Shared between OSChunk and HugeChunk. }
  226. size: SizeUint; { Full size asked from SysOSAlloc. }
  227. end;
  228. pOSChunk = ^OSChunk;
  229. OSChunk = object(OSChunkBase) { Common header for all OS chunks. }
  230. prev, next: pointer; { pOSChunk, but used for different subtypes. }
  231. end;
  232. pFreeOSChunk = ^FreeOSChunk;
  233. FreeOSChunk = object(OSChunk)
  234. end;
  235. {$ifndef HAS_SYSOSFREE}
  236. FreeOSChunkList = object
  237. first, last: pFreeOSChunk;
  238. function Get(minSize, maxSize: SizeUint): pOSChunk;
  239. end;
  240. {$endif not HAS_SYSOSFREE}
  241. pFixedArena = ^FixedArena;
  242. FixedArena = record
  243. { Allocated with AllocVar(isArena := true), so has VarHeader to the left.
  244. Data starts at FixedArenaDataOffset and spans for “maxSize” (virtual value, does not exist directly) bytes, of which:
  245. — first “formattedSize” are either allocated (“used”; counted in usedSizeMinus1) or in the freelist (firstFreeChunk; size = “formattedSize” - (usedSizeMinus1 + 1)),
  246. — the rest “maxSize” - “formattedSize” are yet unallocated space.
  247. This design, together with tracking free chunks per FixedArena rather than per fixed size, trivializes reusing the fixed arenas.
  248. Chopping all available space at once would get rid of the “unallocated space” entity, but is a lot of potentially wasted work:
  249. https://gitlab.com/freepascal.org/fpc/source/-/issues/40447.
  250. Values are multiples of the chunk size instead of counts (could be chunksUsed, chunksFormatted, chunksMax) to save on multiplications.
  251. Moreover, instead of “maxSize” from the explanation above, almostFullThreshold is used, which is such a value that the chunk is full if usedSizeMinus1 - chunk size >= almostFullThreshold.
  252. maxSize = RoundUp(almostFullThreshold + chunk size + 1, chunk size).
  253. Reasons are, calculating almostFullThreshold does not require division, and it is more convenient (in terms of code generation) for AllocFixed / FreeFixed.
  254. “formattedSize” is a virtual value, too; it equals to usedSizeMinus1 + 1 + <total size of the freelist> and is used only when said freelist is empty, so is in practice int32(usedSizeMinus1) + 1 (see AllocFixed). }
  255. firstFreeChunk: pFreeChunk;
  256. usedSizeMinus1, almostFullThreshold: uint32;
  257. prev, next: pFixedArena;
  258. end;
  259. pVarOSChunk = ^VarOSChunk;
  260. VarOSChunk = object(OSChunk)
  261. {$ifdef FPC_HAS_FEATURE_THREADING}
  262. threadState: pThreadState; { Protected with gs.lock. Nil if orphaned. }
  263. {$endif}
  264. end;
  265. pVarHeader = ^VarHeader;
  266. VarHeader = record
  267. { Negative offset from the end of this VarHeader to owning VarOSChunk, friendlier to x86 LEA instruction than the more obvious positive variant.
  268. Truly required only under FPC_HAS_FEATURE_THREADING and could be removed otherwise, bringing the variable header size to the same 4 bytes as fixed headers,
  269. but this would require some redesign (reintroducing FirstFlag removed in https://gitlab.com/freepascal.org/fpc/source/-/merge_requests/1027
  270. or some other way to detect the first chunk) and does not matter enough to bother.
  271. Moreover, accessing VarOSChunk could have been useful beyond multithreading, it just so happens it isn’t. }
  272. ofsToOs: int32;
  273. { Assumed to indeed match chunk’s CommonHeader, i.e. that there is no padding after this field.
  274. Otherwise must be accessed as pCommonHeader(pointer(varHdr) + (VarHeaderSize - CommonHeaderSize))^ :D. }
  275. ch: CommonHeader;
  276. end;
  277. { Reuses the payload of variable chunks whose ch.h and UsedFlag = 0, so variable chunk payload must always fit its size. }
  278. pFreeVarChunk = ^FreeVarChunk;
  279. FreeVarChunk = record
  280. prev, next: pFreeVarChunk;
  281. binIndex: uint32;
  282. end;
  283. { Placed at the end of the free variable chunks that have occupied chunks to the right, thus immediately to the left of such an occupied chunk. }
  284. pFreeVarTail = ^FreeVarTail;
  285. FreeVarTail = record
  286. size: uint32;
  287. end;
  288. pHugeChunk = ^HugeChunk;
  289. HugeChunk = object(OSChunkBase)
  290. end;
  291. {$ifdef HEAP_INC_USE_SETS}
  292. Set32 = set of 0 .. 31;
  293. {$endif HEAP_INC_USE_SETS}
  294. VarFreeMap = object
  295. { Two-level bitfield that allows to search for minimal-size fits (up to the quantization) using up to two “Bsf”s.
  296. Bit 1 in L1 means that the corresponding cell of L0 is non-0.
  297. Bit 1 in L0 means that the corresponding cell of bins is non-nil. }
  298. L1: uint32;
  299. L0: array[0 .. (VarSizesCount + L0BinSize - 1) div L0BinSize - 1] of uint32;
  300. bins: array[0 .. VarSizesCount - 1] of pFreeVarChunk;
  301. { As an optimization, Add.binIndex can also be a size (will be rounded down), assuming VarSizesCount <= MinSearchableVarHeaderAndPayload. }
  302. {$if VarSizesCount > MinSearchableVarHeaderAndPayload} {$error assumption above does not hold} {$endif}
  303. procedure Add(c: pFreeVarChunk; binIndex: SizeUint);
  304. procedure Remove(c: pFreeVarChunk);
  305. function Find(binIndex: SizeUint): pFreeVarChunk;
  306. end;
  307. ThreadState = object
  308. emptyArenas: pFixedArena; { Empty fixed arenas to be reused instead of slower AllocVar. Singly linked list, “prev”s are garbage. }
  309. nEmptyArenas: SizeUint; { # of items in emptyArenas. }
  310. {$ifdef HAS_SYSOSFREE}
  311. freeOS1: pFreeOSChunk; { Just one cached empty OS chunk so that borderline (free + alloc) × N scenarios don’t lead to N OS allocations. }
  312. {$else HAS_SYSOSFREE}
  313. freeOS: FreeOSChunkList; { Completely empty OS chunks. }
  314. {$endif HAS_SYSOSFREE}
  315. {$ifdef FPC_HAS_FEATURE_THREADING}
  316. toFree: pFreeChunk; { Free requests from other threads, atomic. }
  317. {$endif}
  318. used, maxUsed, allocated, maxAllocated: SizeUint; { “maxUsed” and “maxAllocated” include gs.hugeUsed; “used” and “allocated” don’t. }
  319. varOS: pVarOSChunk;
  320. { Fixed arenas with at least 1 free chunk (including unformatted space), but not completely empty.
  321. Fixed arenas that become completely empty are moved to emptyArenas, completely full are... not present in any list. }
  322. partialArenas: array[0 .. FixedSizesCount - 1] of pFixedArena;
  323. { Only to calculate preferable new fixed arena sizes...
  324. (Updated infrequently, as opposed to possible “usedPerArena”. When a new arena is required, all existing arenas of its size are full.) }
  325. allocatedByFullArenas: array[0 .. FixedSizesCount - 1] of uint32; { SizeUint is not obligatory, overflow is tolerable. }
  326. varFree: VarFreeMap;
  327. {$ifdef DEBUG_HEAP_INC}
  328. procedure Dump(var f: text);
  329. {$endif}
  330. function ChooseFixedArenaSize(sizeIndex: SizeUint): SizeUint;
  331. function AllocFixed(size: SizeUint): pointer; {$ifndef DEBUG_HEAP_INC} inline; {$endif}
  332. function FreeFixed(p: pointer): SizeUint; {$ifndef DEBUG_HEAP_INC} inline; {$endif}
  333. function GetOSChunk(minSize, maxSize: SizeUint): pOSChunk; {$if defined(HAS_SYSOSFREE) or not defined(FPC_HAS_FEATURE_THREADING)} inline; {$endif}
  334. function AllocateOSChunk(minSize, maxSize: SizeUint): pOSChunk;
  335. function AllocVar(size: SizeUint; isArena: boolean): pointer;
  336. function FreeVar(p: pointer): SizeUint;
  337. function TryResizeVar(p: pointer; size: SizeUint): pointer;
  338. class function AddToHugeUsed(delta: SizeInt): SizeUint; static;
  339. function AllocHuge(size: SizeUint): pointer;
  340. function FreeHuge(p: pointer): SizeUint;
  341. function TryResizeHuge(p: pointer; size: SizeUint): pointer;
  342. procedure UpdateMaxStats(hugeUsed: SizeUint);
  343. {$ifdef FPC_HAS_FEATURE_THREADING}
  344. procedure PushToFree(p: pFreeChunk);
  345. procedure FlushToFree;
  346. procedure Orphan;
  347. procedure AdoptArena(arena: pFixedArena);
  348. procedure AdoptVarOwner(p: pointer); { Adopts the OS chunk that contains p. Must be performed under gs.lock. }
  349. {$ifndef FPC_SECTION_THREADVARS}
  350. procedure FixupSelfPtr;
  351. {$endif ndef FPC_SECTION_THREADVARS}
  352. {$endif FPC_HAS_FEATURE_THREADING}
  353. end;
  354. GlobalState = record
  355. hugeUsed: SizeUint; { Same as non-existing “hugeAllocated” as huge chunks don’t have free space.
  356. Atomic, but can be read unprotected if unreliability is tolerable.
  357. Huge chunks don’t have thread affinity, so are tracked here. Presently, this value is added to all memory statistics.
  358. Not a good idea and makes multithreaded statistics a strange and unreliable mix, but alternatives are even worse. }
  359. {$ifdef FPC_HAS_FEATURE_THREADING}
  360. lock: TRTLCriticalSection;
  361. lockUse: int32;
  362. { Like ThreadState.varFree but over orphaned OS chunks. Protected by gs.lock. }
  363. varFree: VarFreeMap;
  364. {$ifndef HAS_SYSOSFREE}
  365. freeOS: FreeOSChunkList;
  366. {$endif not HAS_SYSOSFREE}
  367. {$endif FPC_HAS_FEATURE_THREADING}
  368. end;
  369. class function AllocFailed: pointer; static;
  370. class var
  371. gs: GlobalState;
  372. {$ifdef FPC_HAS_FEATURE_THREADING}
  373. class threadvar
  374. {$endif FPC_HAS_FEATURE_THREADING}
  375. thisTs: ThreadState;
  376. const
  377. CommonHeaderSize = sizeof(CommonHeader);
  378. {$if MinFixedHeaderAndPayload < CommonHeaderSize + sizeof(FreeChunk)} {$error MinFixedHeaderAndPayload does not fit CommonHeader + FreeChunk.} {$endif}
  379. FixedArenaDataOffset = (sizeof(FixedArena) + CommonHeaderSize + Alignment - 1) and -Alignment - CommonHeaderSize;
  380. VarHeaderSize = sizeof(VarHeader);
  381. FreeVarTailSize = sizeof(FreeVarTail);
  382. VarOSChunkDataOffset = (sizeof(VarOSChunk) + VarHeaderSize + Alignment - 1) and -Alignment - VarHeaderSize;
  383. HugeChunkDataOffset = (sizeof(HugeChunk) + CommonHeaderSize + Alignment - 1) and -Alignment - CommonHeaderSize;
  384. MinAnyVarHeaderAndPayload = (sizeof(VarHeader) + sizeof(FreeVarChunk) + sizeof(FreeVarTail) + VarSizeQuant - 1) and -VarSizeQuant;
  385. end;
  386. class function HeapInc.SizeMinus1ToIndex(sizeMinus1: SizeUint): SizeUint;
  387. begin
  388. result := SizeMinus1Div16ToIndex[sizeMinus1 div 16];
  389. end;
  390. class function HeapInc.IndexToSize(sizeIndex: SizeUint): SizeUint;
  391. begin
  392. result := FixedSizes[sizeIndex];
  393. end;
  394. class function HeapInc.VarSizeToBinIndex(size: SizeUint; roundUp: boolean): SizeUint;
  395. var
  396. maxv, binClassIndex: SizeUint;
  397. begin
  398. dec(size, MaxFixedHeaderAndPayload);
  399. binClassIndex := BsrDWord(uint32(size) or 1 shl FirstVarRangeP2); { Temporarily off by +FirstVarRangeP2. }
  400. maxv := SizeUint(2) shl binClassIndex - 1 shl FirstVarRangeP2;
  401. if size <= maxv then
  402. begin
  403. maxv := maxv shr 1; { Turn into “minv” to be subtracted from size. If size > maxv, “minv” is maxv. :) }
  404. maxv := maxv and SizeUint(-SizeInt(1 shl FirstVarRangeP2));
  405. dec(SizeInt(binClassIndex)); { Compensate extra +1 to binClassIndex below, so in the end, it is increased if size > maxv. All of this prevents having an “else” branch with its extra jump. }
  406. end;
  407. dec(size, maxv);
  408. inc(SizeInt(binClassIndex), 1 - FirstVarRangeP2); { No longer off by +FirstVarRangeP2. }
  409. result := binClassIndex * VarSizesPerClass + SizeUint(size - 1) shr (binClassIndex + FirstVarStepP2);
  410. if not roundUp and (size and SizeUint(SizeUint(1) shl (binClassIndex + FirstVarStepP2) - 1) <> 0) then
  411. dec(result);
  412. end;
  413. class function HeapInc.VarSizeToBinIndexUp(size: SizeUint): SizeUint;
  414. begin
  415. result := VarSizeToBinIndex(size, true);
  416. end;
  417. class function HeapInc.BinIndexToVarSize(binIndex: SizeUint): SizeUint;
  418. begin
  419. result := binIndex div VarSizesPerClass;
  420. result := MaxFixedHeaderAndPayload + (SizeUint(1) shl result - 1) shl FirstVarRangeP2 + (1 + binIndex mod VarSizesPerClass) shl (FirstVarStepP2 + result);
  421. end;
  422. {$ifndef HAS_SYSOSFREE}
  423. function HeapInc.FreeOSChunkList.Get(minSize, maxSize: SizeUint): pOSChunk;
  424. var
  425. prev, next: pFreeOSChunk;
  426. begin
  427. result := first;
  428. while Assigned(result) and not ((result^.size >= minSize) and (result^.size <= maxSize)) do
  429. result := result^.next;
  430. if not Assigned(result) then
  431. exit;
  432. prev := result^.prev;
  433. next := result^.next;
  434. if Assigned(prev) then
  435. prev^.next := next
  436. else
  437. first := next;
  438. if Assigned(next) then
  439. next^.prev := prev
  440. else
  441. last := prev;
  442. end;
  443. {$endif not HAS_SYSOSFREE}
  444. procedure HeapInc.VarFreeMap.Add(c: pFreeVarChunk; binIndex: SizeUint);
  445. var
  446. next: pFreeVarChunk;
  447. iL0: SizeUint;
  448. vL0 {$ifdef HEAP_INC_USE_SETS}, vL1 {$endif}: uint32;
  449. begin
  450. if binIndex >= VarSizesCount then
  451. if binIndex >= MaxVarHeaderAndPayload then { Large sizes go to the last bin, assuming searches never search for more than MaxVarHeaderAndPayload. }
  452. binIndex := VarSizesCount - 1
  453. else
  454. binIndex := VarSizeToBinIndex(binIndex, false);
  455. next := bins[binIndex];
  456. c^.prev := nil;
  457. c^.next := next;
  458. c^.binIndex := binIndex;
  459. bins[binIndex] := c;
  460. if Assigned(next) then
  461. next^.prev := c
  462. else
  463. begin
  464. iL0 := binIndex div L0BinSize;
  465. vL0 := L0[iL0];
  466. {$ifdef HEAP_INC_USE_SETS}
  467. if vL0 = 0 then
  468. begin
  469. vL1 := L1;
  470. Include(Set32(vL1), iL0);
  471. L1 := vL1;
  472. end;
  473. Include(Set32(vL0), binIndex mod L0BinSize);
  474. L0[iL0] := vL0;
  475. {$else}
  476. if vL0 = 0 then
  477. L1 := L1 or uint32(1) shl iL0;
  478. L0[iL0] := vL0 or uint32(1) shl (binIndex mod L0BinSize);
  479. {$endif}
  480. end;
  481. end;
  482. procedure HeapInc.VarFreeMap.Remove(c: pFreeVarChunk);
  483. var
  484. prev, next: pFreeVarChunk;
  485. binIndex, iL0: SizeUint;
  486. v: uint32;
  487. begin
  488. prev := c^.prev;
  489. next := c^.next;
  490. if Assigned(next) then
  491. next^.prev := prev;
  492. if Assigned(prev) then
  493. prev^.next := next
  494. else
  495. begin
  496. binIndex := c^.binIndex;
  497. bins[binIndex] := next;
  498. if not Assigned(next) then
  499. begin
  500. iL0 := binIndex div L0BinSize;
  501. {$ifdef HEAP_INC_USE_SETS}
  502. v := L0[iL0];
  503. Exclude(Set32(v), binIndex mod L0BinSize);
  504. L0[iL0] := v;
  505. if v = 0 then
  506. begin
  507. v := L1;
  508. Exclude(Set32(v), iL0);
  509. L1 := v;
  510. end;
  511. {$else}
  512. v := L0[iL0] xor (uint32(1) shl (binIndex mod L0BinSize));
  513. L0[iL0] := v;
  514. if v = 0 then
  515. L1 := L1 xor (uint32(1) shl iL0);
  516. {$endif}
  517. end;
  518. end;
  519. end;
  520. function HeapInc.VarFreeMap.Find(binIndex: SizeUint): pFreeVarChunk;
  521. var
  522. mask: uint32;
  523. begin
  524. result := bins[binIndex];
  525. if Assigned(result) then
  526. exit;
  527. mask := L0[binIndex div L0BinSize] shr (binIndex mod L0BinSize); { Logically should be “1 + binIndex mod L0BinSize” but the bit that represents the binIndex-th bin is 0 anyway. }
  528. if mask <> 0 then
  529. exit(bins[binIndex + BsfDWord(mask or 1 shl (L0BinSize - 1))]); { In these two BsfDWords, ensuring the highest bit to be set is just an optimization, as long as the supposed alternative from https://gitlab.com/freepascal.org/fpc/source/-/issues/41179 does not work. }
  530. mask := L1 and (SizeUint(-2) shl (binIndex div L0BinSize));
  531. if mask <> 0 then
  532. begin
  533. binIndex := BsfDWord(mask or 1 shl (L0BinSize - 1)); { Index at L0. }
  534. result := bins[binIndex * L0BinSize + BsfDWord(L0[binIndex] or 1 shl (L0BinSize - 1))]; { Careful, this time “or 1 shl (L0BinSize - 1)” is NOT an optimization: unsynchronized gs.varFree.Find can read zero from L0[binIndex]. }
  535. end;
  536. end;
  537. {$ifdef DEBUG_HEAP_INC}
  538. procedure HeapInc.ThreadState.Dump(var f: text);
  539. var
  540. i: SizeInt;
  541. fix: pFixedArena;
  542. fr: pFreeOSChunk;
  543. {$ifdef FPC_HAS_FEATURE_THREADING}
  544. tf: pFreeChunk;
  545. {$endif}
  546. vf: pFreeVarChunk;
  547. vOs: pVarOSChunk;
  548. p: pointer;
  549. needLE, anything: boolean;
  550. procedure MaybeLE;
  551. begin
  552. if needLE then
  553. writeln(f);
  554. needLE := false;
  555. end;
  556. procedure DumpVarFree(const varFree: VarFreeMap; const name: string);
  557. var
  558. i: SizeInt;
  559. begin
  560. if varFree.L1 = 0 then
  561. exit;
  562. MaybeLE;
  563. write(f, name, LineEnding, 'L1:');
  564. for i := 0 to VarSizesCount div L0BinSize - 1 do
  565. if varFree.L1 shr i and 1 <> 0 then
  566. begin
  567. write(f, ' #', i, ' ', BinIndexToVarSize(i * L0BinSize), '-');
  568. if i = VarSizesCount div L0BinSize - 1 then
  569. write(f, 'inf')
  570. else
  571. write(f, BinIndexToVarSize((i + 1) * L0BinSize) - 1);
  572. end;
  573. writeln(f);
  574. write(f, 'L0 (bins):');
  575. for i := 0 to VarSizesCount - 1 do
  576. begin
  577. if varFree.L0[SizeUint(i) div L0BinSize] shr (SizeUint(i) mod L0BinSize) and 1 <> 0 then
  578. begin
  579. write(f, ' #', i, ' ', BinIndexToVarSize(i), '-');
  580. if i = VarSizesCount - 1 then
  581. write(f, 'inf')
  582. else
  583. write(f, BinIndexToVarSize(i + 1) - 1);
  584. end;
  585. if Assigned(varFree.bins[i]) then
  586. begin
  587. write(f, ' (');
  588. vf := varFree.bins[i];
  589. repeat
  590. if Assigned(vf^.prev) then write(f, ' ');
  591. write(f, HexStr(PtrUint(vf), 1 + BsrQWord(PtrUint(vf)) div 4), ':', pVarHeader(vf)[-1].ch.h and VarSizeMask);
  592. vf := vf^.next;
  593. until not Assigned(vf);
  594. write(f, ')');
  595. end;
  596. end;
  597. writeln(f);
  598. needLE := true;
  599. end;
  600. begin
  601. writeln(f, 'used = ', used, ', allocated = ', allocated, ', hugeUsed = ', gs.hugeUsed, ', maxUsed = ', maxUsed, ', maxAllocated = ', maxAllocated);
  602. needLE := true;
  603. anything := false;
  604. for i := 0 to FixedSizesCount - 1 do
  605. begin
  606. if not Assigned(partialArenas[i]) and (allocatedByFullArenas[i] = 0) then
  607. continue;
  608. MaybeLE;
  609. anything := true;
  610. write(f, 'Size #', i, ' (', IndexToSize(i), '):');
  611. if allocatedByFullArenas[i] <> 0 then
  612. write(f, ' allocatedByFullArenas = ', allocatedByFullArenas[i]);
  613. if Assigned(partialArenas[i]) then
  614. begin
  615. writeln(f);
  616. fix := partialArenas[i];
  617. repeat
  618. writeln(f, 'arena size = ', pVarHeader(fix)[-1].ch.h and VarSizeMask - VarHeaderSize - FixedArenaDataOffset, ', usedSizeMinus1 = ', fix^.usedSizeMinus1, ', almostFullThreshold = ', fix^.almostFullThreshold);
  619. fix := fix^.next;
  620. until not Assigned(fix);
  621. end
  622. else if allocatedByFullArenas[i] <> 0 then
  623. writeln(f);
  624. end;
  625. needLE := needLE or anything;
  626. if nEmptyArenas <> 0 then
  627. begin
  628. MaybeLE;
  629. writeln(f, 'nEmptyArenas = ', nEmptyArenas);
  630. needLE := true;
  631. end;
  632. vOs := varOS;
  633. while Assigned(vOs) do
  634. begin
  635. MaybeLE;
  636. writeln(f, 'Var OS chunk, size ', vOs^.size);
  637. p := pointer(vOs) + (VarOSChunkDataOffset + VarHeaderSize);
  638. repeat
  639. write(f, HexStr(p), ': size = ', pVarHeader(p - VarHeaderSize)^.ch.h and VarSizeMask, ', ofsToOs = ', pVarHeader(p - VarHeaderSize)^.ofsToOs);
  640. if pVarHeader(p - VarHeaderSize)^.ch.h and UsedFlag <> 0 then
  641. write(f, ', used')
  642. else
  643. begin
  644. write(f, ', f r e e');
  645. if pVarHeader(p - VarHeaderSize)^.ch.h and LastFlag = 0 then
  646. write(f, ' (tail ', pFreeVarTail(p + pVarHeader(p - VarHeaderSize)^.ch.h - VarHeaderSize - FreeVarTailSize)^.size, ')');
  647. end;
  648. if pVarHeader(p - VarHeaderSize)^.ch.h and LastFlag <> 0 then
  649. write(f, ', last');
  650. if pVarHeader(p - VarHeaderSize)^.ch.h and PrevIsFreeFlag <> 0 then
  651. write(f, ', prev. is free');
  652. if pVarHeader(p - VarHeaderSize)^.ch.h and FixedArenaFlag <> 0 then
  653. write(f, ', fixed arena');
  654. writeln(f);
  655. if pVarHeader(p - VarHeaderSize)^.ch.h and LastFlag <> 0 then
  656. break;
  657. p := p + pVarHeader(p - VarHeaderSize)^.ch.h and VarSizeMask;
  658. until false;
  659. needLE := true;
  660. vOs := vOs^.next;
  661. end;
  662. fr := {$ifdef HAS_SYSOSFREE} freeOS1 {$else} freeOS.first {$endif};
  663. if Assigned(fr) then
  664. begin
  665. MaybeLE;
  666. repeat
  667. writeln(f, 'Free OS: ', HexStr(fr), ', size = ', fr^.size);
  668. {$ifndef HAS_SYSOSFREE} fr := fr^.next; {$endif}
  669. until {$ifdef HAS_SYSOSFREE} true {$else} not Assigned(fr) {$endif};
  670. needLE := true;
  671. end;
  672. DumpVarFree(varFree, 'varFree');
  673. {$ifdef FPC_HAS_FEATURE_THREADING}
  674. DumpVarFree(gs.varFree, 'Orphaned varFree');
  675. tf := toFree;
  676. if Assigned(tf) then
  677. begin
  678. MaybeLE;
  679. write(f, 'To-free:');
  680. repeat
  681. if pCommonHeader(pointer(tf) - CommonHeaderSize)^.h and FixedFlag <> 0 then
  682. write(f, ' f ', CommonHeaderSize + SysMemSize(tf))
  683. else
  684. write(f, ' v ', VarHeaderSize + SysMemSize(tf));
  685. tf := tf^.next;
  686. until not Assigned(tf);
  687. writeln(f);
  688. end;
  689. {$endif FPC_HAS_FEATURE_THREADING}
  690. end;
  691. {$endif DEBUG_HEAP_INC}
  692. function HeapInc.ThreadState.ChooseFixedArenaSize(sizeIndex: SizeUint): SizeUint;
  693. begin
  694. result := (allocatedByFullArenas[sizeIndex] div 8 + (FixedArenaSizeQuant - 1)) and SizeUint(-FixedArenaSizeQuant); { 12.5% of memory allocated by the size. }
  695. if result < MinFixedArenaSize then
  696. result := MinFixedArenaSize;
  697. if result > MaxFixedArenaSize then
  698. result := MaxFixedArenaSize;
  699. dec(result, result shr (FirstVarRangeP2 - FirstVarStepP2)); { Prettier fit into OS chunks. }
  700. end;
  701. function HeapInc.ThreadState.AllocFixed(size: SizeUint): pointer;
  702. var
  703. sizeIndex, sizeUp, statv: SizeUint;
  704. usedSizeMinus1: int32;
  705. arena, nextArena: pFixedArena;
  706. begin
  707. sizeIndex := SizeMinus1ToIndex(size + (CommonHeaderSize - 1));
  708. arena := partialArenas[sizeIndex];
  709. if not Assigned(arena) then
  710. begin
  711. {$ifdef FPC_HAS_FEATURE_THREADING}
  712. if Assigned(toFree) then
  713. begin
  714. FlushToFree;
  715. arena := partialArenas[sizeIndex];
  716. end;
  717. if not Assigned(arena) then
  718. {$endif FPC_HAS_FEATURE_THREADING}
  719. begin
  720. arena := emptyArenas;
  721. if Assigned(arena) then
  722. begin
  723. emptyArenas := arena^.next;
  724. dec(nEmptyArenas);
  725. end else
  726. begin
  727. arena := AllocVar(ChooseFixedArenaSize(sizeIndex), true);
  728. if not Assigned(arena) then
  729. exit(nil);
  730. { Size index of the first chunk in the arena is used to determine if it can be reused. Set a purposely mismatching value for freshly allocated arena. }
  731. pCommonHeader(pointer(arena) + FixedArenaDataOffset)^.h := uint32(not sizeIndex);
  732. end;
  733. if pCommonHeader(pointer(arena) + FixedArenaDataOffset)^.h and SizeIndexMask = uint32(sizeIndex) then
  734. { Lucky! Just don’t reset the chunk and use its old freelist. }
  735. else
  736. begin
  737. arena^.firstFreeChunk := nil;
  738. arena^.usedSizeMinus1 := uint32(-1);
  739. arena^.almostFullThreshold := pVarHeader(arena)[-1].ch.h and VarSizeMask - 2 * IndexToSize(sizeIndex) - (VarHeaderSize + FixedArenaDataOffset); { available space - 2 * chunk size. }
  740. end;
  741. { Add arena to partialArenas[sizeIndex], which is nil. Careful: AllocVar above should not call FlushToFree, or this assumption might be violated. }
  742. arena^.prev := nil;
  743. arena^.next := nil;
  744. partialArenas[sizeIndex] := arena;
  745. end;
  746. end;
  747. sizeUp := IndexToSize(sizeIndex); { Not reusing the “size” variable saved a register at the time of writing this comment. }
  748. inc(used, sizeUp);
  749. { arena from partialArenas has either free chunk or free unformatted space for a new chunk. }
  750. usedSizeMinus1 := int32(arena^.usedSizeMinus1);
  751. arena^.usedSizeMinus1 := uint32(usedSizeMinus1 + int32(sizeUp));
  752. result := arena^.firstFreeChunk;
  753. if Assigned(result) then
  754. begin
  755. { This branch is much more likely (when compiling FPC: 9×), so comes first. }
  756. arena^.firstFreeChunk := pFreeChunk(result)^.next;
  757. if usedSizeMinus1 < int32(arena^.almostFullThreshold) then { Arena is still not full? Uses usedSizeMinus1 value before adding sizeUp, as assumed by almostFullThreshold. }
  758. exit;
  759. end else
  760. begin
  761. { Freelist is empty, so “formattedSize” = usedSizeMinus1 + 1. This “+ 1” is folded into constants. }
  762. result := pointer(arena) + (FixedArenaDataOffset + CommonHeaderSize + 1) + usedSizeMinus1;
  763. pCommonHeader(result - CommonHeadersize)^.h := uint32(int32(sizeIndex) + int32(usedSizeMinus1 shl FixedArenaOffsetShift) +
  764. (FixedFlag + (FixedArenaDataOffset + CommonHeaderSize + 1) shl FixedArenaOffsetShift) { ← const });
  765. if usedSizeMinus1 < int32(arena^.almostFullThreshold) then { Arena is still not full? }
  766. exit;
  767. end;
  768. { Arena became full. This is unlikely, so instead of the “if”, the check is duplicated in both branches above. (Saves a jump from the “then” branch above.) }
  769. inc(allocatedByFullArenas[sizeIndex], pVarHeader(arena)[-1].ch.h and VarSizeMask);
  770. { Remove arena from partialArenas[sizeIndex]. (It was first.) }
  771. nextArena := arena^.next;
  772. partialArenas[sizeIndex] := nextArena;
  773. if Assigned(nextArena) then
  774. nextArena^.prev := nil;
  775. { And since this is unlikely, it won’t hurt to update maxUsed (unlike doing it in the common path). }
  776. statv := used + gs.hugeUsed;
  777. if statv > maxUsed then
  778. maxUsed := statv;
  779. end;
  780. function HeapInc.ThreadState.FreeFixed(p: pointer): SizeUint;
  781. var
  782. sizeIndex: SizeUint;
  783. usedSizeMinus1: int32;
  784. arena, prevArena, nextArena: pFixedArena;
  785. {$ifdef FPC_HAS_FEATURE_THREADING}
  786. ts: pThreadState;
  787. {$endif FPC_HAS_FEATURE_THREADING}
  788. begin
  789. arena := p - pCommonHeader(p - CommonHeaderSize)^.h shr FixedArenaOffsetShift;
  790. {$ifdef FPC_HAS_FEATURE_THREADING}
  791. { This can be checked without blocking; <arena>.threadState can only change from one value not equal to @self to another value not equal to @self. }
  792. if pVarOSChunk(pointer(arena) + pVarHeader(arena)[-1].ofsToOs)^.threadState <> @self then
  793. begin
  794. EnterCriticalSection(gs.lock);
  795. ts := pVarOSChunk(pointer(arena) + pVarHeader(arena)[-1].ofsToOs)^.threadState;
  796. if Assigned(ts) then
  797. begin
  798. { Despite atomic Push lock must be held as otherwise target thread might end and destroy its threadState.
  799. However, target thread won’t block to free p, so PushToFree instantly invalidates p. }
  800. result := IndexToSize(pCommonHeader(p - CommonHeaderSize)^.h and SizeIndexMask) - CommonHeaderSize;
  801. ts^.PushToFree(p);
  802. LeaveCriticalSection(gs.lock);
  803. exit;
  804. end;
  805. AdoptVarOwner(arena); { ...And continue! }
  806. LeaveCriticalSection(gs.lock);
  807. end;
  808. {$endif FPC_HAS_FEATURE_THREADING}
  809. pFreeChunk(p)^.next := arena^.firstFreeChunk;
  810. arena^.firstFreeChunk := p;
  811. sizeIndex := pCommonHeader(p - CommonHeaderSize)^.h and SizeIndexMask;
  812. result := IndexToSize(sizeIndex);
  813. dec(used, result);
  814. usedSizeMinus1 := int32(arena^.usedSizeMinus1) - int32(result);
  815. arena^.usedSizeMinus1 := uint32(usedSizeMinus1);
  816. dec(result, CommonHeaderSize);
  817. { “(usedSizeMinus1 = -1) or (usedSizeMinus1 >= arena^.almostFullThreshold)” as 1 comparison. }
  818. if uint32(usedSizeMinus1) >= arena^.almostFullThreshold then
  819. if usedSizeMinus1 <> -1 then
  820. begin
  821. dec(allocatedByFullArenas[sizeIndex], pVarHeader(arena)[-1].ch.h and VarSizeMask);
  822. { Add arena to partialArenas[sizeIndex]. }
  823. nextArena := partialArenas[sizeIndex];
  824. arena^.prev := nil;
  825. arena^.next := nextArena;
  826. if Assigned(nextArena) then
  827. nextArena^.prev := arena;
  828. partialArenas[sizeIndex] := arena;
  829. end else
  830. begin
  831. { Remove arena from partialArenas[sizeIndex], add to emptyArenas (maybe). }
  832. prevArena := arena^.prev;
  833. nextArena := arena^.next;
  834. if Assigned(prevArena) then
  835. prevArena^.next := nextArena
  836. else
  837. partialArenas[sizeIndex] := nextArena;
  838. if Assigned(nextArena) then
  839. nextArena^.prev := prevArena;
  840. if nEmptyArenas < MaxKeptFixedArenas then
  841. begin
  842. arena^.next := emptyArenas;
  843. emptyArenas := arena;
  844. inc(nEmptyArenas);
  845. end else
  846. FreeVar(arena);
  847. end;
  848. end;
  849. function HeapInc.ThreadState.GetOSChunk(minSize, maxSize: SizeUint): pOSChunk;
  850. {$if defined(FPC_HAS_FEATURE_THREADING) and not defined(HAS_SYSOSFREE)}
  851. var
  852. statv: SizeUint;
  853. {$endif FPC_HAS_FEATURE_THREADING and not HAS_SYSOSFREE}
  854. begin
  855. {$ifdef HAS_SYSOSFREE}
  856. result := freeOS1;
  857. if Assigned(result) then
  858. if (result^.size >= minSize) and (result^.size <= maxSize) then
  859. freeOS1 := nil
  860. else
  861. result := nil;
  862. {$else HAS_SYSOSFREE}
  863. result := freeOS.Get(minSize, maxSize);
  864. {$ifdef FPC_HAS_FEATURE_THREADING}
  865. if not Assigned(result) and Assigned(gs.freeOS.first) then { Racing precheck. }
  866. begin
  867. EnterCriticalSection(gs.lock);
  868. result := gs.freeOS.Get(minSize, maxSize);
  869. LeaveCriticalSection(gs.lock);
  870. if Assigned(result) then
  871. begin
  872. statv := allocated + result^.size;
  873. allocated := statv;
  874. inc(statv, gs.hugeUsed);
  875. if statv > maxAllocated then
  876. maxAllocated := statv;
  877. end;
  878. end;
  879. {$endif FPC_HAS_FEATURE_THREADING}
  880. {$endif HAS_SYSOSFREE}
  881. end;
  882. function HeapInc.ThreadState.AllocateOSChunk(minSize, maxSize: SizeUint): pOSChunk;
  883. var
  884. query, statv: SizeUint;
  885. begin
  886. query := used div 16 + minSize div 2; { Base: 6.25% of the memory used, so if GrowHeapSize2 = 1 Mb, 1 Mb OS allocations start at 16 Mb used. }
  887. if query > maxSize then { Limit by maxSize (usually GrowHeapSize2). }
  888. query := maxSize;
  889. if query < minSize then { But of course allocate at least the amount requested. Also triggers if maxSize was wrong (smaller than minSize). }
  890. query := minSize;
  891. query := (query + (OSChunkVarSizeQuant - 1)) and SizeUint(-OSChunkVarSizeQuant); { Quantize. }
  892. result := SysOSAlloc(query);
  893. if not Assigned(result) and (query > minSize) then
  894. begin
  895. query := minSize;
  896. result := SysOSAlloc(query);
  897. end;
  898. if not Assigned(result) then
  899. exit(AllocFailed);
  900. result^.size := query;
  901. statv := allocated + query;
  902. allocated := statv;
  903. inc(statv, gs.hugeUsed);
  904. if statv > maxAllocated then
  905. maxAllocated := statv;
  906. end;
  907. function HeapInc.ThreadState.AllocVar(size: SizeUint; isArena: boolean): pointer;
  908. var
  909. fv: pFreeVarChunk;
  910. osChunk, osNext: pVarOSChunk;
  911. binIndex, vSizeFlags, statv: SizeUint;
  912. begin
  913. { Search varFree for (roughly) smallest chunk ≥ size. }
  914. binIndex := VarSizeToBinIndexUp(size + VarHeaderSize);
  915. { Round the size up to the bin size.
  916. Can do without that, but not doing that will often mean the inability to reuse the hole because varFree rounds up for searches and down for additions. }
  917. size := BinIndexToVarSize(binIndex);
  918. fv := varFree.Find(binIndex);
  919. if not Assigned(fv) then
  920. begin
  921. { Find either other fv or other osChunk that can fit the requested size. }
  922. osChunk := pVarOSChunk(GetOSChunk(VarOSChunkDataOffset + size, GrowHeapSize2));
  923. if not Assigned(osChunk) then
  924. begin
  925. {$ifdef FPC_HAS_FEATURE_THREADING}
  926. { Preliminary search without blocking, assuming varFree.Find doesn’t do anything that can go wrong. }
  927. fv := gs.varFree.Find(binIndex);
  928. if Assigned(fv) then
  929. begin
  930. EnterCriticalSection(gs.lock);
  931. fv := gs.varFree.Find(binIndex); { True search. }
  932. if Assigned(fv) then
  933. AdoptVarOwner(fv); { Moves fv to own varFree. }
  934. LeaveCriticalSection(gs.lock);
  935. end;
  936. if not Assigned(fv) then
  937. {$endif FPC_HAS_FEATURE_THREADING}
  938. begin
  939. osChunk := pVarOSChunk(AllocateOSChunk(VarOSChunkDataOffset + size, GrowHeapSize2));
  940. if not Assigned(osChunk) then
  941. exit(nil);
  942. end;
  943. end;
  944. end;
  945. if not Assigned(fv) then
  946. begin
  947. {$ifdef FPC_HAS_FEATURE_THREADING}
  948. osChunk^.threadState := @self;
  949. {$endif}
  950. { Add osChunk to varOS. }
  951. osNext := varOS;
  952. osChunk^.prev := nil;
  953. osChunk^.next := osNext;
  954. if Assigned(osNext) then
  955. osNext^.prev := osChunk;
  956. varOS := osChunk;
  957. { Format new free var chunk spanning the entire osChunk. FreeVarTail is not required. }
  958. fv := pointer(osChunk) + (VarOSChunkDataOffset + VarHeaderSize);
  959. pVarHeader(pointer(fv) - VarHeaderSize)^.ofsToOs := -(VarOSChunkDataOffset + VarHeaderSize);
  960. pVarHeader(pointer(fv) - VarHeaderSize)^.ch.h := (uint32(osChunk^.size) - VarOSChunkDataOffset) and VarSizeMask + LastFlag;
  961. end else
  962. varFree.Remove(fv);
  963. { Result will be allocated at the beginning of fv; maybe format the remainder and add it back to varFree. }
  964. result := fv;
  965. vSizeFlags := pVarHeader(fv)[-1].ch.h - size; { Inherits LastFlag. }
  966. { Allow leaving a non-searchable tail if non-last.
  967. “vSizeFlags >= MinAnyVarHeaderAndPayload” if non-last, “vSizeFlags >= MinSearchableVarHeaderAndPayload” if last. }
  968. if vSizeFlags >= MinAnyVarHeaderAndPayload + (MinSearchableVarHeaderAndPayload - MinAnyVarHeaderAndPayload) div LastFlag * (vSizeFlags and LastFlag) then
  969. begin
  970. pVarHeader(result - VarHeaderSize)^.ch.h := uint32(size) + UsedFlag;
  971. inc(pointer(fv), size); { result = allocated block, fv = remainder. }
  972. pVarHeader(pointer(fv) - VarHeaderSize)^.ofsToOs := pVarHeader(result - VarHeaderSize)^.ofsToOs - int32(size);
  973. pVarHeader(pointer(fv) - VarHeaderSize)^.ch.h := vSizeFlags;
  974. { Chunk to the right retains its PrevFreeFlag. }
  975. if vSizeFlags and LastFlag = 0 then
  976. pFreeVarTail(pointer(fv) + vSizeFlags - (VarHeaderSize + FreeVarTailSize))^.size := vSizeFlags;
  977. if vSizeFlags >= MinSearchableVarHeaderAndPayload then
  978. varFree.Add(fv, vSizeFlags); { Rounding down, so not masking is ok. }
  979. end else
  980. begin
  981. { Use the entire chunk. }
  982. inc(vSizeFlags, size);
  983. pVarHeader(result - VarHeaderSize)^.ch.h := uint32(vSizeFlags) + UsedFlag;
  984. if vSizeFlags and LastFlag = 0 then
  985. dec(pVarHeader(pointer(fv) + vSizeFlags - VarHeaderSize)^.ch.h, PrevIsFreeFlag);
  986. size := vSizeFlags and VarSizeMask;
  987. end;
  988. { Update maxUsed regardless. }
  989. statv := used + gs.hugeUsed;
  990. if statv > maxUsed then
  991. maxUsed := statv;
  992. if isArena then
  993. inc(pVarHeader(result)[-1].ch.h, FixedArenaFlag) { Arenas aren’t counted in “used” directly. }
  994. else
  995. inc(used, size);
  996. end;
  997. function HeapInc.ThreadState.FreeVar(p: pointer): SizeUint;
  998. var
  999. p2: pointer;
  1000. fSizeFlags, hPrev, hNext: SizeUint;
  1001. osChunk, osPrev, osNext: pVarOSChunk;
  1002. {$ifdef FPC_HAS_FEATURE_THREADING}
  1003. pts: ^pThreadState;
  1004. {$endif FPC_HAS_FEATURE_THREADING}
  1005. {$ifndef HAS_SYSOSFREE}
  1006. freeOsNext: pFreeOSChunk;
  1007. fOs: ^FreeOSChunkList;
  1008. {$endif not HAS_SYSOSFREE}
  1009. begin
  1010. {$ifdef FPC_HAS_FEATURE_THREADING}
  1011. pts := @pVarOSChunk(p + pVarHeader(p - VarHeaderSize)^.ofsToOs)^.threadState;
  1012. if pts^ <> @self then
  1013. begin
  1014. EnterCriticalSection(gs.lock);
  1015. if Assigned(pts^) then
  1016. begin
  1017. { Despite atomic Push lock must be held as otherwise target thread might end and destroy its threadState.
  1018. However, target thread won’t block to free p, so PushToFree instantly invalidates p. }
  1019. result := pVarHeader(p - VarHeaderSize)^.ch.h and VarSizeMask - VarHeaderSize;
  1020. pts^^.PushToFree(p);
  1021. LeaveCriticalSection(gs.lock);
  1022. exit;
  1023. end;
  1024. AdoptVarOwner(p); { ...And continue! }
  1025. LeaveCriticalSection(gs.lock);
  1026. end;
  1027. {$endif FPC_HAS_FEATURE_THREADING}
  1028. fSizeFlags := pVarHeader(p - VarHeaderSize)^.ch.h;
  1029. result := fSizeFlags and VarSizeMask;
  1030. if fSizeFlags and FixedArenaFlag = 0 then
  1031. dec(used, result)
  1032. else
  1033. dec(fSizeFlags, FixedArenaFlag);
  1034. { If next/prev are free, remove them from varFree and merge with f — (f)uture (f)ree chunk that starts at p and has fSizeFlags. }
  1035. if fSizeFlags and LastFlag = 0 then
  1036. begin
  1037. p2 := p + result;
  1038. hNext := pVarHeader(p2 - VarHeaderSize)^.ch.h;
  1039. if uint32(hNext) and UsedFlag = 0 then
  1040. begin
  1041. inc(fSizeFlags, hNext); { Inherit LastFlag, other p2 flags must be 0. }
  1042. if hNext >= MinSearchableVarHeaderAndPayload then { Logically “hNext and VarSizeMask”. }
  1043. varFree.Remove(p2);
  1044. { Chunk to the right retains its PrevFreeFlag. }
  1045. end;
  1046. end;
  1047. if fSizeFlags and PrevIsFreeFlag <> 0 then
  1048. begin
  1049. dec(fSizeFlags, PrevIsFreeFlag);
  1050. p2 := p - pFreeVarTail(p - (VarHeaderSize + FreeVarTailSize))^.size;
  1051. hPrev := pVarHeader(p2 - VarHeaderSize)^.ch.h;
  1052. if uint32(hPrev) and UsedFlag = 0 then
  1053. begin
  1054. p := p2;
  1055. inc(fSizeFlags, hPrev); { All p2 flags must be 0. }
  1056. if hPrev >= MinSearchableVarHeaderAndPayload then { Logically “hPrev and VarSizeMask”. }
  1057. varFree.Remove(p2);
  1058. end;
  1059. end;
  1060. { Turn p into a free chunk and add it back to varFree...
  1061. unless it spans the entire OS chunk, in which case instead move the chunk from varOS to freeOS1 / freeOS. }
  1062. if (fSizeFlags and LastFlag = 0) or (pVarHeader(p - VarHeaderSize)^.ofsToOs <> -(VarOSChunkDataOffset + VarHeaderSize)) then
  1063. begin
  1064. dec(fSizeFlags, UsedFlag);
  1065. pVarHeader(p - VarHeaderSize)^.ch.h := fSizeFlags;
  1066. varFree.Add(p, fSizeFlags);
  1067. if fSizeFlags and LastFlag = 0 then
  1068. begin
  1069. pVarHeader(p + fSizeFlags - VarHeaderSize)^.ch.h := pVarHeader(p + fSizeFlags - VarHeaderSize)^.ch.h or PrevIsFreeFlag; { Could have it already. }
  1070. pFreeVarTail(p + fSizeFlags - (VarHeaderSize + FreeVarTailSize))^.size := fSizeFlags;
  1071. end;
  1072. end else
  1073. begin
  1074. osChunk := p - (VarOSChunkDataOffset + VarHeaderSize);
  1075. { Remove osChunk from varOS. }
  1076. osPrev := osChunk^.prev;
  1077. osNext := osChunk^.next;
  1078. if Assigned(osPrev) then
  1079. osPrev^.next := osNext
  1080. else
  1081. varOS := osNext;
  1082. if Assigned(osNext) then
  1083. osNext^.prev := osPrev;
  1084. {$ifdef HAS_SYSOSFREE}
  1085. { Move to freeOS1, discarding old freeOS1. }
  1086. if Assigned(freeOS1) then
  1087. begin
  1088. dec(allocated, freeOS1^.size);
  1089. SysOSFree(freeOS1, freeOS1^.size);
  1090. end;
  1091. freeOS1 := pFreeOSChunk(osChunk);
  1092. {$else HAS_SYSOSFREE}
  1093. fOs := @freeOS;
  1094. { Share if huge. }
  1095. {$ifdef FPC_HAS_FEATURE_THREADING}
  1096. if osChunk^.size > GrowHeapSize2 then
  1097. begin
  1098. fOs := @gs.freeOS;
  1099. EnterCriticalSection(gs.lock);
  1100. end;
  1101. {$endif FPC_HAS_FEATURE_THREADING}
  1102. { Add to fOs. }
  1103. freeOsNext := fOs^.first;
  1104. osChunk^.prev := nil;
  1105. osChunk^.next := freeOsNext;
  1106. if Assigned(freeOsNext) then
  1107. freeOsNext^.prev := osChunk
  1108. else
  1109. fOs^.last := pFreeOSChunk(osChunk);
  1110. fOs^.first := pFreeOSChunk(osChunk);
  1111. {$ifdef FPC_HAS_FEATURE_THREADING}
  1112. if fOs <> @freeOS then
  1113. begin
  1114. dec(allocated, osChunk^.size); { gs.freeOS aren’t counted anywhere, for now. }
  1115. LeaveCriticalSection(gs.lock);
  1116. end;
  1117. {$endif FPC_HAS_FEATURE_THREADING}
  1118. {$endif HAS_SYSOSFREE}
  1119. end;
  1120. dec(result, VarHeaderSize);
  1121. end;
  1122. function HeapInc.ThreadState.TryResizeVar(p: pointer; size: SizeUint): pointer;
  1123. var
  1124. ar: pointer absolute result;
  1125. fv, fp: pointer;
  1126. arSizeFlags, prevSize2, maxFv, minFragment, fSizeFlags, hNext, hNext2, oldph: uint32;
  1127. prevSize, binIndex, oldpsize, statv, arSize: SizeUint;
  1128. {$ifdef FPC_HAS_FEATURE_THREADING}
  1129. pts: ^pThreadState;
  1130. {$endif FPC_HAS_FEATURE_THREADING}
  1131. begin
  1132. result := nil;
  1133. if (size > GrowHeapSize2) { Assuming GrowHeapSize2 is never larger than 3.999 Gb, this prevents overflow on adding headers and allows uint32(size) to tune for x64. }
  1134. or (uint32(size) <= MaxFixedHeaderAndPayload - CommonHeaderSize)
  1135. then
  1136. exit;
  1137. {$ifdef FPC_HAS_FEATURE_THREADING}
  1138. pts := @pVarOSChunk(p + pVarHeader(p - VarHeaderSize)^.ofsToOs)^.threadState;
  1139. if pts^ <> @self then
  1140. begin
  1141. if Assigned(pts^) then { Pretest to avoid acquiring the lock. }
  1142. exit;
  1143. EnterCriticalSection(gs.lock);
  1144. if Assigned(pts^) then
  1145. begin
  1146. LeaveCriticalSection(gs.lock);
  1147. exit;
  1148. end;
  1149. AdoptVarOwner(p); { ...And continue! }
  1150. LeaveCriticalSection(gs.lock);
  1151. end;
  1152. {$endif FPC_HAS_FEATURE_THREADING}
  1153. { Round the size up, but only if supported by VarSizeToBinIndexUp: chunks can be reallocated to the sizes larger than MaxVarHeaderAndPayload. }
  1154. if uint32(size) <= MaxVarHeaderAndPayload - VarHeaderSize then
  1155. begin
  1156. binIndex := VarSizeToBinIndexUp(size + VarHeaderSize);
  1157. size := BinIndexToVarSize(binIndex);
  1158. end else
  1159. size := uint32(uint32(size) + (VarHeaderSize + VarSizeQuant - 1)) and uint32(-VarSizeQuant); { Just do the strictly necessary quantization... }
  1160. { ar + arSizeFlags (from “around”) is the chunk made from p and its adjacent free chunks. }
  1161. ar := p;
  1162. arSizeFlags := pVarHeader(ar - VarHeaderSize)^.ch.h;
  1163. if arSizeFlags and LastFlag = 0 then
  1164. begin
  1165. hNext := pVarHeader(ar + arSizeFlags and VarSizeMask - VarHeaderSize)^.ch.h;
  1166. if hNext and UsedFlag = 0 then
  1167. inc(arSizeFlags, hNext); { Inherit LastFlag, other flags must be 0. }
  1168. end;
  1169. if arSizeFlags and PrevIsFreeFlag <> 0 then
  1170. begin
  1171. prevSize := pFreeVarTail(ar - (VarHeaderSize + FreeVarTailSize))^.size;
  1172. dec(ar, prevSize);
  1173. inc(arSizeFlags, prevSize);
  1174. end;
  1175. if uint32(size) > arSizeFlags then { “ar” has no way to fit the new chunk. }
  1176. exit(nil);
  1177. { Check if there is a better place... }
  1178. maxFv := arSizeFlags div 4 * 3;
  1179. if (uint32(size) <= MaxVarHeaderAndPayload) and (uint32(size) < maxFv) then { Pretest the condition on a “CONSIDERABLY” better fv below, maybe it’s not going to happen no matter what. }
  1180. begin
  1181. fv := varFree.Find(binIndex);
  1182. if Assigned(fv)
  1183. { fv may be one of the chunks around; in this case, ignore it. Checked as unsigned(fv - ar) < arSize. }
  1184. and (PtrUint(PtrInt(PtrUint(fv)) - PtrInt(PtrUint(ar))) >= arSizeFlags) { Logically “arSizeFlags and VarSizeMask”. }
  1185. { To justify moving FAR, better place should be CONSIDERABLY better: say, <75% of the ar. }
  1186. and (pVarHeader(fv)[-1].ch.h < maxFv) { Ignore masking, this is a rough check anyway. }
  1187. then
  1188. exit(nil);
  1189. end;
  1190. { So p will be placed inside “ar” after all. It is either moved to the beginning of “ar” or stays in place.
  1191. There might be no choice but to move: reallocating A in
  1192. [free 1,000][A 1,000][free 1,000]
  1193. to 2,500 bytes has to move, resulting in
  1194. [A 2,500][free 500].
  1195. But if there is a choice, moving might be or not be worth it. If we have
  1196. [free 5,000][A 1,000][free 5,000]
  1197. then moving will give
  1198. [A 1,000][free 10,000]
  1199. and that’s the point — [free 10,000] is better than 2 × [free 5,000]. But if we have
  1200. [free 64][A 1,000][free 9,936]
  1201. then moving for the sake of defragmenting these 64 bytes is definitely a waste of time.
  1202. So if there is a choice, moving is performed if fragments on BOTH sides are larger than 1/8 (12.5%) of the (new) size. }
  1203. if arSizeFlags and PrevIsFreeFlag <> 0 then
  1204. begin
  1205. prevSize2 := pFreeVarTail(p - (VarHeaderSize + FreeVarTailSize))^.size;
  1206. { Consider (not) moving... }
  1207. dec(arSizeFlags, prevSize2); { Temporarily (or not) remove prevSize from arSizeFlags. This corresponds to the size available without moving. }
  1208. minFragment := uint32(size) div 8;
  1209. if (arSizeFlags < uint32(size)) { Size does not fit without moving? }
  1210. or (prevSize2 >= minFragment) and (uint32(arSizeFlags - uint32(size)) >= minFragment) { There are large enough fragments on both sides? }
  1211. then
  1212. begin
  1213. if prevSize2 >= MinSearchableVarHeaderAndPayload then
  1214. varFree.Remove(ar);
  1215. inc(arSizeFlags, prevSize2 - PrevIsFreeFlag); { Add prevSize back, and remove PrevIsFreeFlag. }
  1216. { Move(p^, ar^, ...) is postponed, see below. }
  1217. end else
  1218. { Not moving; finish the removal of the previous chunk from “ar”. arSizeFlags is already decreased by prevSize, and keeps PrevIsFreeFlag. }
  1219. ar := p; { Same as inc(ar, prevSize2). }
  1220. end;
  1221. { Remove the free chunk after p. Note that:
  1222. — Under some circumstances, it can be overwritten with Move, so Move must be postponed.
  1223. — This section might decide that TryResizeVar is a complete no-op and exit “early”, and this decision depends on the decision to move,
  1224. so the decision to move must be made first.
  1225. Though a nontrivial amount of work has been done by this point, some more remains and can be skipped to speed up no-op ReallocMems (e.g. 26 → 16 ns).
  1226. Without shortcutting the no-op case, this entire section can be simply moved above the previous one and postponing Move would not be required. }
  1227. oldph := pVarHeader(p)[-1].ch.h;
  1228. oldpsize := oldph and VarSizeMask;
  1229. if (uint32(size) = uint32(oldpsize)) and (ar = p) then
  1230. { TryResizeVar was a no-op, and with some explicit efforts we managed to write nothing by this point,
  1231. so we use our last chance to get out. }
  1232. exit;
  1233. if oldph and LastFlag = 0 then
  1234. begin
  1235. hNext2 := pVarHeader(p + oldpsize - VarHeaderSize)^.ch.h;
  1236. if (hNext2 and UsedFlag = 0) and (hNext2 >= MinSearchableVarHeaderAndPayload) then
  1237. varFree.Remove(p + oldpsize);
  1238. end;
  1239. dec(used, oldpsize);
  1240. if ar <> p then
  1241. begin
  1242. if uint32(size) < uint32(oldpsize) then { oldpsize is reused as “moveSize”. }
  1243. oldpsize := uint32(size);
  1244. Move(p^, ar^, oldpsize - VarHeaderSize);
  1245. end;
  1246. { Format the free chunk after ar, or its absence. }
  1247. fSizeFlags := uint32(arSizeFlags - uint32(size)) and (VarSizeMask or LastFlag);
  1248. if fSizeFlags >= uint32(MinAnyVarHeaderAndPayload + (MinSearchableVarHeaderAndPayload - MinAnyVarHeaderAndPayload) div LastFlag * (fSizeFlags and LastFlag)) then
  1249. begin
  1250. dec(arSizeFlags, fSizeFlags);
  1251. arSize := arSizeFlags and VarSizeMask;
  1252. fp := ar + arSize;
  1253. pVarHeader(fp)[-1].ofsToOs := pVarHeader(ar)[-1].ofsToOs - int32(arSize);
  1254. pVarHeader(fp)[-1].ch.h := fSizeFlags;
  1255. if fSizeFlags and LastFlag = 0 then
  1256. begin
  1257. pFreeVarTail(fp + fSizeFlags - (VarHeaderSize + FreeVarTailSize))^.size := fSizeFlags;
  1258. pVarHeader(fp + fSizeFlags)[-1].ch.h := pVarHeader(fp + fSizeFlags)[-1].ch.h or PrevIsFreeFlag; { May have had it already. }
  1259. end;
  1260. if fSizeFlags >= MinSearchableVarHeaderAndPayload then
  1261. varFree.Add(fp, fSizeFlags);
  1262. end
  1263. else if arSizeFlags and LastFlag = 0 then
  1264. pVarHeader(ar + arSizeFlags and VarSizeMask)[-1].ch.h := pVarHeader(ar + arSizeFlags and VarSizeMask)[-1].ch.h and uint32(not PrevIsFreeFlag); { May not have had it already. }
  1265. pVarHeader(ar)[-1].ch.h := arSizeFlags;
  1266. statv := used + arSizeFlags and VarSizeMask;
  1267. used := statv;
  1268. inc(statv, gs.hugeUsed);
  1269. if statv > maxUsed then
  1270. maxUsed := statv;
  1271. end;
  1272. { If SysOSFree is available, huge chunks aren’t cached by any means.
  1273. If SysOSFree is not available, there’s no choice but to cache them.
  1274. Caching is done directly into gs.freeOS if FPC_HAS_FEATURE_THREADING, otherwise ThreadState.freeOS. }
  1275. class function HeapInc.ThreadState.AddToHugeUsed(delta: SizeInt): SizeUint;
  1276. begin
  1277. {$if not defined(FPC_HAS_FEATURE_THREADING)}
  1278. result := SizeUint(SizeInt(gs.hugeUsed) + delta);
  1279. gs.hugeUsed := result;
  1280. {$elseif not defined(VER3_2)}
  1281. result := AtomicIncrement(gs.hugeUsed, SizeUint(delta));
  1282. {$elseif sizeof(SizeInt) = sizeof(int64)}
  1283. result := SizeUint(delta + InterlockedExchangeAdd64(SizeInt(gs.hugeUsed), delta));
  1284. {$else}
  1285. result := SizeUint(delta + InterlockedExchangeAdd(SizeInt(gs.hugeUsed), delta));
  1286. {$endif}
  1287. end;
  1288. function HeapInc.ThreadState.AllocHuge(size: SizeUint): pointer;
  1289. var
  1290. userSize: SizeUint;
  1291. begin
  1292. userSize := size;
  1293. size := (size + (HugeChunkDataOffset + CommonHeaderSize + OSChunkVarSizeQuant - 1)) and SizeUint(-OSChunkVarSizeQuant);
  1294. if size < userSize then { Overflow. }
  1295. exit(AllocFailed);
  1296. {$ifdef HAS_SYSOSFREE}
  1297. result := SysOSAlloc(size);
  1298. if not Assigned(result) then
  1299. exit(AllocFailed);
  1300. pHugeChunk(result)^.size := size;
  1301. {$else HAS_SYSOSFREE}
  1302. result := GetOSChunk(size, High(SizeUint));
  1303. if not Assigned(result) then
  1304. begin
  1305. result := AllocateOSChunk(size, High(SizeUint));
  1306. if not Assigned(result) then
  1307. exit; { AllocateOSChunk throws an error if required. }
  1308. end;
  1309. size := pOSChunk(result)^.size;
  1310. dec(allocated, size); { After GetOSChunk* chunk size is counted in “allocated”; don’t count. }
  1311. {$endif HAS_SYSOSFREE}
  1312. pCommonHeader(result + HugeChunkDataOffset)^.h := HugeHeader;
  1313. inc(result, HugeChunkDataOffset + CommonHeaderSize);
  1314. UpdateMaxStats(AddToHugeUsed(size));
  1315. end;
  1316. function HeapInc.ThreadState.FreeHuge(p: pointer): SizeUint;
  1317. {$ifndef HAS_SYSOSFREE}
  1318. var
  1319. fOs: ^FreeOSChunkList;
  1320. osPrev: pOSChunk;
  1321. {$endif ndef HAS_SYSOSFREE}
  1322. begin
  1323. dec(p, HugeChunkDataOffset + CommonHeaderSize);
  1324. result := pHugeChunk(p)^.size;
  1325. AddToHugeUsed(-SizeInt(result));
  1326. {$ifndef HAS_SYSOSFREE} { But you’d better have SysOSFree... }
  1327. {$ifdef FPC_HAS_FEATURE_THREADING}
  1328. fOs := @gs.freeOS; { gs.freeOS aren’t counted anywhere (for now). }
  1329. EnterCriticalSection(gs.lock);
  1330. {$else FPC_HAS_FEATURE_THREADING}
  1331. fOs := @freeOS;
  1332. inc(allocated, result); { ThreadState.freeOS are counted in ThreadState.allocated. But since “size” (= result) is just moved from “hugeUsed” to “allocated”, it won’t affect maximums. }
  1333. {$endif FPC_HAS_FEATURE_THREADING}
  1334. { Turn p into FreeOSChunk and add to fOs; add to the end to reduce the chance for this chunk to be reused
  1335. (other OS chunks are added to the beginning and searched from the beginning). }
  1336. osPrev := fOs^.last;
  1337. pFreeOSChunk(p)^.prev := osPrev;
  1338. pFreeOSChunk(p)^.next := nil;
  1339. if Assigned(osPrev) then
  1340. osPrev^.next := p
  1341. else
  1342. fOs^.first := p;
  1343. fOs^.last := p;
  1344. {$ifdef FPC_HAS_FEATURE_THREADING} LeaveCriticalSection(gs.lock); {$endif}
  1345. {$endif ndef HAS_SYSOSFREE}
  1346. {$ifdef HAS_SYSOSFREE} SysOSFree(p, result); {$endif}
  1347. dec(result, HugeChunkDataOffset + CommonHeaderSize);
  1348. end;
  1349. function HeapInc.ThreadState.TryResizeHuge(p: pointer; size: SizeUint): pointer;
  1350. var
  1351. userSize, oldSize: SizeUint;
  1352. begin
  1353. userSize := size;
  1354. size := (size + (HugeChunkDataOffset + CommonHeaderSize + OSChunkVarSizeQuant - 1)) and SizeUint(-OSChunkVarSizeQuant);
  1355. if (size < userSize) or { Overflow. }
  1356. (size < GrowHeapSize2 div 4) { Limit on shrinking huge chunks. }
  1357. then
  1358. exit(nil);
  1359. oldSize := pHugeChunk(p - (HugeChunkDataOffset + CommonHeaderSize))^.size;
  1360. if size = oldSize then
  1361. exit(p);
  1362. {$ifdef FPC_SYSTEM_HAS_SYSOSREALLOC}
  1363. result := SysOSRealloc(p - (HugeChunkDataOffset + CommonHeaderSize), oldSize, size);
  1364. if Assigned(result) then
  1365. begin
  1366. UpdateMaxStats(AddToHugeUsed(SizeInt(size) - SizeInt(oldSize)));
  1367. pHugeChunk(result)^.size := size;
  1368. inc(result, HugeChunkDataOffset + CommonHeaderSize);
  1369. end;
  1370. {$else FPC_SYSTEM_HAS_SYSOSREALLOC}
  1371. result := nil; { Just don’t. Note shrinking 20 Mb to 19 will require temporary 39 because of this. }
  1372. {$endif FPC_SYSTEM_HAS_SYSOSREALLOC}
  1373. end;
  1374. procedure HeapInc.ThreadState.UpdateMaxStats(hugeUsed: SizeUint);
  1375. var
  1376. statv: SizeUint;
  1377. begin
  1378. statv := used + hugeUsed;
  1379. if statv > maxUsed then
  1380. maxUsed := statv;
  1381. statv := allocated + hugeUsed;
  1382. if statv > maxAllocated then
  1383. maxAllocated := statv;
  1384. end;
  1385. {$ifdef FPC_HAS_FEATURE_THREADING}
  1386. procedure HeapInc.ThreadState.PushToFree(p: pFreeChunk);
  1387. var
  1388. next: pFreeChunk;
  1389. begin
  1390. repeat
  1391. next := toFree;
  1392. p^.next := next;
  1393. WriteBarrier; { Write p after p^.next. }
  1394. until InterlockedCompareExchange(toFree, p, next) = next;
  1395. end;
  1396. procedure HeapInc.ThreadState.FlushToFree;
  1397. var
  1398. tf, nx: pFreeChunk;
  1399. begin
  1400. tf := InterlockedExchange(toFree, nil);
  1401. while Assigned(tf) do
  1402. begin
  1403. ReadDependencyBarrier; { Read toFree^.next after toFree. }
  1404. nx := tf^.next;
  1405. SysFreeMem(tf);
  1406. tf := nx;
  1407. end;
  1408. end;
  1409. procedure HeapInc.ThreadState.Orphan;
  1410. var
  1411. arena: pFixedArena;
  1412. vOs: pVarOSChunk;
  1413. p: pointer;
  1414. h: uint32;
  1415. {$ifndef HAS_SYSOSFREE}
  1416. lastFree, nextFree: pFreeOSChunk;
  1417. {$endif not HAS_SYSOSFREE}
  1418. begin
  1419. if gs.lockUse > 0 then
  1420. EnterCriticalSection(HeapInc.gs.lock);
  1421. FlushToFree; { Performing it under gs.lock guarantees there will be no new toFree requests. }
  1422. { Has to free all empty arenas, otherwise the chunk that contains only empty arenas will leak (no one will ever adopt it, as it has nothing to free). }
  1423. while nEmptyArenas > 0 do
  1424. begin
  1425. arena := emptyArenas;
  1426. emptyArenas := arena^.next;
  1427. dec(nEmptyArenas);
  1428. FreeVar(arena);
  1429. end;
  1430. {$ifndef HAS_SYSOSFREE}
  1431. { Prepend freeOS to gs.freeOS. }
  1432. lastFree := freeOS.last;
  1433. if Assigned(lastFree) then
  1434. begin
  1435. nextFree := gs.freeOS.first;
  1436. lastFree^.next := nextFree;
  1437. if Assigned(nextFree) then
  1438. nextFree^.prev := lastFree
  1439. else
  1440. gs.freeOS.last := lastFree;
  1441. gs.freeOS.first := freeOS.first;
  1442. { Zeroing is probably required, because Orphan is called from FinalizeHeap which is called from DoneThread which can be called twice, according to this comment from syswin.inc: }
  1443. // DoneThread; { Assume everything is idempotent there }
  1444. freeOS.first := nil;
  1445. freeOS.last := nil;
  1446. end;
  1447. {$endif not HAS_SYSOSFREE}
  1448. vOs := varOS;
  1449. while Assigned(vOs) do
  1450. begin
  1451. vOs^.threadState := nil;
  1452. p := pointer(vOs) + (VarOSChunkDataOffset + VarHeaderSize);
  1453. repeat
  1454. h := pVarHeader(p - VarHeaderSize)^.ch.h;
  1455. if (h and UsedFlag = 0) and (h >= MinSearchableVarHeaderAndPayload) then
  1456. gs.varFree.Add(p, pFreeVarChunk(p)^.binIndex);
  1457. inc(p, h and VarSizeMask);
  1458. until h and LastFlag <> 0;
  1459. vOs := vOs^.next;
  1460. end;
  1461. varOS := nil;
  1462. if gs.lockUse > 0 then
  1463. LeaveCriticalSection(gs.lock);
  1464. {$ifdef HAS_SYSOSFREE}
  1465. if Assigned(freeOS1) then
  1466. begin
  1467. SysOSFree(freeOS1, freeOS1^.size); { Does not require gs.lock. }
  1468. freeOS1 := nil;
  1469. end;
  1470. {$endif HAS_SYSOSFREE}
  1471. end;
  1472. procedure HeapInc.ThreadState.AdoptArena(arena: pFixedArena);
  1473. var
  1474. sizeIndex: SizeUint;
  1475. nextArena: pFixedArena;
  1476. begin
  1477. sizeIndex := pCommonHeader(pointer(arena) + FixedArenaDataOffset)^.h and SizeIndexMask;
  1478. inc(used, arena^.usedSizeMinus1 + 1); { maxUsed is updated at the end of AdoptVarOwner. }
  1479. { Orphan frees all empty arenas, so adopted arena can’t be empty. }
  1480. if arena^.usedSizeMinus1 < arena^.almostFullThreshold + IndexToSize(sizeIndex) then
  1481. begin
  1482. { Add arena to partialArenas[sizeIndex]. }
  1483. nextArena := partialArenas[sizeIndex];
  1484. arena^.prev := nil;
  1485. arena^.next := nextArena;
  1486. if Assigned(nextArena) then
  1487. nextArena^.prev := arena;
  1488. partialArenas[sizeIndex] := arena;
  1489. end else
  1490. inc(allocatedByFullArenas[sizeIndex], pVarHeader(arena)[-1].ch.h and VarSizeMask);
  1491. end;
  1492. procedure HeapInc.ThreadState.AdoptVarOwner(p: pointer);
  1493. var
  1494. statv: SizeUint;
  1495. h: uint32;
  1496. vOs, osNext: pVarOSChunk;
  1497. begin
  1498. vOs := p + pVarHeader(p)[-1].ofsToOs;
  1499. vOs^.threadState := @self;
  1500. { Add OS chunk to varOS. }
  1501. vOs^.prev := nil;
  1502. osNext := varOS;
  1503. vOs^.next := osNext;
  1504. if Assigned(osNext) then
  1505. osNext^.prev := vOs;
  1506. varOS := vOs;
  1507. statv := allocated + vOs^.size;
  1508. allocated := statv;
  1509. inc(statv, gs.hugeUsed);
  1510. if statv > maxAllocated then
  1511. maxAllocated := statv;
  1512. p := pointer(vOs) + VarOSChunkDataOffset + VarHeaderSize;
  1513. repeat
  1514. h := pVarHeader(p - VarHeaderSize)^.ch.h;
  1515. if h and UsedFlag = 0 then
  1516. begin
  1517. if h >= MinSearchableVarHeaderAndPayload then
  1518. begin
  1519. gs.varFree.Remove(p);
  1520. varFree.Add(p, pFreeVarChunk(p)^.binIndex);
  1521. end;
  1522. end
  1523. else if h and FixedArenaFlag <> 0 then
  1524. AdoptArena(p)
  1525. else
  1526. inc(used, h and VarSizeMask); { maxUsed is updated after the loop. }
  1527. inc(p, h and VarSizeMask);
  1528. until h and LastFlag <> 0;
  1529. statv := used + gs.hugeUsed;
  1530. if statv > maxUsed then
  1531. maxUsed := statv;
  1532. end;
  1533. {$ifndef FPC_SECTION_THREADVARS}
  1534. procedure HeapInc.ThreadState.FixupSelfPtr;
  1535. var
  1536. vOs: pVarOSChunk;
  1537. begin
  1538. vOs := varOS;
  1539. while Assigned(vOs) do
  1540. begin
  1541. vOs^.threadState := @self;
  1542. vOs := vOs^.next;
  1543. end;
  1544. end;
  1545. {$endif ndef FPC_SECTION_THREADVARS}
  1546. {$endif FPC_HAS_FEATURE_THREADING}
  1547. class function HeapInc.AllocFailed: pointer;
  1548. begin
  1549. if not ReturnNilIfGrowHeapFails then
  1550. HandleError(204);
  1551. result := nil;
  1552. end;
  1553. function SysGetFPCHeapStatus:TFPCHeapStatus;
  1554. var
  1555. ts: HeapInc.pThreadState;
  1556. hugeUsed: SizeUint;
  1557. begin
  1558. ts := @HeapInc.thisTs;
  1559. hugeUsed := HeapInc.gs.hugeUsed;
  1560. ts^.UpdateMaxStats(hugeUsed); { Cheat to avoid clearly implausible values like current > max. }
  1561. result.MaxHeapSize := ts^.maxAllocated;
  1562. result.MaxHeapUsed := ts^.maxUsed;
  1563. result.CurrHeapSize := hugeUsed + ts^.allocated;
  1564. result.CurrHeapUsed := hugeUsed + ts^.used;
  1565. result.CurrHeapFree := result.CurrHeapSize - result.CurrHeapUsed;
  1566. end;
  1567. function SysGetHeapStatus :THeapStatus;
  1568. var
  1569. fhs: TFPCHeapStatus;
  1570. begin
  1571. fhs := SysGetFPCHeapStatus;
  1572. FillChar((@result)^, sizeof(result), 0);
  1573. result.TotalAllocated := fhs.CurrHeapUsed;
  1574. result.TotalFree := fhs.CurrHeapSize - fhs.CurrHeapUsed;
  1575. result.TotalAddrSpace := fhs.CurrHeapSize;
  1576. end;
  1577. function SysGetMem(size : ptruint):pointer;
  1578. var
  1579. ts: HeapInc.pThreadState;
  1580. begin
  1581. ts := @HeapInc.thisTs;
  1582. if size <= HeapInc.MaxFixedHeaderAndPayload - HeapInc.CommonHeaderSize then
  1583. exit(ts^.AllocFixed(size));
  1584. {$ifdef FPC_HAS_FEATURE_THREADING}
  1585. if Assigned(ts^.toFree) then
  1586. ts^.FlushToFree;
  1587. {$endif}
  1588. if (size < GrowHeapSize2 div 2) { Approximate idea on the max size of the variable chunk. Approximate because size does not include headers but GrowHeapSize2 does. }
  1589. and (size <= HeapInc.MaxVarHeaderAndPayload - HeapInc.VarHeaderSize) then
  1590. result := ts^.AllocVar(size, false)
  1591. else
  1592. result := ts^.AllocHuge(size);
  1593. end;
  1594. function SysFreeMem(p: pointer): ptruint;
  1595. var
  1596. ts: HeapInc.pThreadState;
  1597. begin
  1598. if Assigned(p) then
  1599. begin
  1600. ts := @HeapInc.thisTs;
  1601. if HeapInc.pCommonHeader(p - HeapInc.CommonHeaderSize)^.h and HeapInc.FixedFlag <> 0 then
  1602. result := ts^.FreeFixed(p)
  1603. else if HeapInc.pCommonHeader(p - HeapInc.CommonHeaderSize)^.h <> HeapInc.HugeHeader then
  1604. result := ts^.FreeVar(p)
  1605. else
  1606. result := ts^.FreeHuge(p);
  1607. end
  1608. else
  1609. result := 0;
  1610. end;
  1611. function SysTryResizeMem(var p: pointer; size: ptruint): boolean;
  1612. var
  1613. ts: HeapInc.pThreadState;
  1614. h: uint32;
  1615. newp: pointer;
  1616. begin
  1617. h := HeapInc.pCommonHeader(p - HeapInc.CommonHeaderSize)^.h;
  1618. if h and HeapInc.FixedFlag <> 0 then
  1619. result := (size <= HeapInc.MaxFixedHeaderAndPayload - HeapInc.CommonHeaderSize) and (h and HeapInc.SizeIndexMask = HeapInc.SizeMinus1ToIndex(size + (HeapInc.CommonHeaderSize - 1)))
  1620. else
  1621. begin
  1622. ts := @HeapInc.thisTs;
  1623. {$ifdef FPC_HAS_FEATURE_THREADING}
  1624. if Assigned(ts^.toFree) then
  1625. ts^.FlushToFree;
  1626. {$endif FPC_HAS_FEATURE_THREADING}
  1627. if h <> HeapInc.HugeHeader then
  1628. newp := ts^.TryResizeVar(p, size)
  1629. else
  1630. newp := ts^.TryResizeHuge(p, size);
  1631. result := Assigned(newp);
  1632. if result then
  1633. p := newp;
  1634. end;
  1635. end;
  1636. function SysMemSize(p: pointer): ptruint;
  1637. var
  1638. h: uint32;
  1639. begin
  1640. if not Assigned(p) then
  1641. exit(0);
  1642. h := HeapInc.pCommonHeader(p - HeapInc.CommonHeaderSize)^.h;
  1643. if h and HeapInc.FixedFlag <> 0 then
  1644. result := HeapInc.IndexToSize(h and HeapInc.SizeIndexMask) - HeapInc.CommonHeaderSize
  1645. else if h <> HeapInc.HugeHeader then
  1646. result := HeapInc.pVarHeader(p - HeapInc.VarHeaderSize)^.ch.h and uint32(HeapInc.VarSizeMask) - HeapInc.VarHeaderSize
  1647. else
  1648. result := HeapInc.pHugeChunk(p - (HeapInc.HugeChunkDataOffset + HeapInc.CommonHeaderSize))^.size - (HeapInc.HugeChunkDataOffset + HeapInc.CommonHeaderSize);
  1649. end;
  1650. function SysReAllocMem(var p: pointer; size: ptruint):pointer;
  1651. var
  1652. oldsize, newsize, tocopy: SizeUint;
  1653. begin
  1654. if size = 0 then
  1655. begin
  1656. SysFreeMem(p);
  1657. result := nil;
  1658. p := nil;
  1659. end
  1660. else if not Assigned(p) then
  1661. begin
  1662. result := SysGetMem(size);
  1663. p := result;
  1664. end
  1665. else if SysTryResizeMem(p, size) then
  1666. result := p
  1667. else
  1668. begin
  1669. oldsize := SysMemSize(p);
  1670. newsize := size;
  1671. result := SysGetMem(newsize);
  1672. if not Assigned(result) then
  1673. begin
  1674. if size <= oldsize then
  1675. { Don’t fail if shrinking. }
  1676. result := p;
  1677. exit; { If growing failed, return nil, but keep the old p. }
  1678. end;
  1679. tocopy := oldsize;
  1680. if tocopy > newsize then
  1681. tocopy := newsize;
  1682. Move(p^, result^, tocopy);
  1683. SysFreeMem(p);
  1684. p := result;
  1685. end;
  1686. end;
  1687. Function SysFreeMemSize(p: pointer; size: ptruint):ptruint;
  1688. begin
  1689. { can't free partial blocks, ignore size }
  1690. result := SysFreeMem(p);
  1691. end;
  1692. function SysAllocMem(size: ptruint): pointer;
  1693. begin
  1694. result := SysGetMem(size);
  1695. if Assigned(result) then
  1696. FillChar(result^, SysMemSize(result), 0);
  1697. end;
  1698. {*****************************************************************************
  1699. InitHeap
  1700. *****************************************************************************}
  1701. { This function will initialize the Heap manager and need to be called from
  1702. the initialization of the system unit }
  1703. {$ifdef FPC_HAS_FEATURE_THREADING}
  1704. procedure InitHeapThread;
  1705. begin
  1706. if HeapInc.gs.lockUse>0 then
  1707. InterlockedIncrement(HeapInc.gs.lockUse);
  1708. end;
  1709. {$endif}
  1710. procedure InitHeap; public name '_FPC_InitHeap';
  1711. begin
  1712. { we cannot initialize the locks here yet, thread support is
  1713. not loaded yet }
  1714. end;
  1715. procedure RelocateHeap;
  1716. begin
  1717. {$ifdef FPC_HAS_FEATURE_THREADING}
  1718. if HeapInc.gs.lockUse > 0 then
  1719. exit;
  1720. HeapInc.gs.lockUse := 1;
  1721. InitCriticalSection(HeapInc.gs.lock);
  1722. {$ifndef FPC_SECTION_THREADVARS}
  1723. { threadState pointers still point to main thread's thisTs, but they
  1724. have a reference to the global main thisTs, fix them to point
  1725. to the main thread specific variable.
  1726. even if section threadvars are used, this shouldn't cause problems as threadState pointers simply
  1727. do not change but we do not need it }
  1728. HeapInc.thisTs.FixupSelfPtr;
  1729. {$endif FPC_SECTION_THREADVARS}
  1730. if MemoryManager.RelocateHeap <> nil then
  1731. MemoryManager.RelocateHeap();
  1732. {$endif FPC_HAS_FEATURE_THREADING}
  1733. end;
  1734. procedure FinalizeHeap;
  1735. begin
  1736. { Do not try to do anything if the heap manager already reported an error }
  1737. if (errorcode=203) or (errorcode=204) then
  1738. exit;
  1739. {$if defined(FPC_HAS_FEATURE_THREADING)}
  1740. HeapInc.thisTs.Orphan;
  1741. if (HeapInc.gs.lockUse > 0) and (InterlockedDecrement(HeapInc.gs.lockUse) = 0) then
  1742. DoneCriticalSection(HeapInc.gs.lock);
  1743. {$elseif defined(HAS_SYSOSFREE)}
  1744. if Assigned(HeapInc.thisTs.freeOS1) then
  1745. begin
  1746. dec(HeapInc.thisTs.allocated, HeapInc.thisTs.freeOS1^.size); { Just in case... }
  1747. SysOSFree(HeapInc.thisTs.freeOS1, HeapInc.thisTs.freeOS1^.size);
  1748. HeapInc.thisTs.freeOS1 := nil; { Just in case... }
  1749. end;
  1750. {$endif FPC_HAS_FEATURE_THREADING | defined(HAS_SYSOSFREE)}
  1751. end;
  1752. {$endif ndef HAS_MEMORYMANAGER}
  1753. {$endif FPC_HAS_FEATURE_HEAP}