heap.inc 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484
  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. { Try to find the best matching block in general freelist }
  15. { define BESTMATCH}
  16. { DEBUG: Dump info when the heap needs to grow }
  17. { define DUMPGROW}
  18. { Memory profiling: at moment in time of max heap size usage,
  19. keep statistics of number of each size allocated
  20. (with 16 byte granularity) }
  21. { define DUMP_MEM_USAGE}
  22. {$ifdef DUMP_MEM_USAGE}
  23. {$define SHOW_MEM_USAGE}
  24. {$endif}
  25. const
  26. {$ifdef CPU64}
  27. blocksize = 32; { at least size of freerecord }
  28. blockshift = 5; { shr value for blocksize=2^blockshift}
  29. maxblocksize = 512+blocksize; { 1024+8 needed for heaprecord }
  30. {$else}
  31. blocksize = 16; { at least size of freerecord }
  32. blockshift = 4; { shr value for blocksize=2^blockshift}
  33. maxblocksize = 512+blocksize; { 1024+8 needed for heaprecord }
  34. {$endif}
  35. maxblockindex = maxblocksize div blocksize; { highest index in array of lists of memchunks }
  36. { common flags }
  37. fixedsizeflag = 1; { flag if the block is of fixed size }
  38. { memchunk var flags }
  39. usedflag = 2; { flag if the block is used or not }
  40. lastblockflag = 4; { flag if the block is the last in os chunk }
  41. firstblockflag = 8; { flag if the block is the first in os chunk }
  42. { os chunk flags }
  43. ocrecycleflag = 1;
  44. { above flags stored in size field }
  45. sizemask = not(blocksize-1);
  46. fixedoffsetshift = 16;
  47. fixedsizemask = sizemask and ((1 shl fixedoffsetshift) - 1);
  48. {****************************************************************************}
  49. {$ifdef DUMPGROW}
  50. {$define DUMPBLOCKS}
  51. {$endif}
  52. { Memory manager }
  53. const
  54. MemoryManager: TMemoryManager = (
  55. NeedLock: false; // Obsolete
  56. GetMem: @SysGetMem;
  57. FreeMem: @SysFreeMem;
  58. FreeMemSize: @SysFreeMemSize;
  59. AllocMem: @SysAllocMem;
  60. ReAllocMem: @SysReAllocMem;
  61. MemSize: @SysMemSize;
  62. InitThread: nil;
  63. DoneThread: nil;
  64. RelocateHeap: nil;
  65. GetHeapStatus: @SysGetHeapStatus;
  66. GetFPCHeapStatus: @SysGetFPCHeapStatus;
  67. );
  68. {$ifndef HAS_MEMORYMANAGER}
  69. {
  70. We use 'fixed' size chunks for small allocations,
  71. and os chunks with variable sized blocks for big
  72. allocations.
  73. * a block is an area allocated by user
  74. * a chunk is a block plus our bookkeeping
  75. * an os chunk is a collection of chunks
  76. Memory layout:
  77. fixed: < chunk size > [ ... user data ... ]
  78. variable: < prev chunk size > < chunk size > [ ... user data ... ]
  79. When all chunks in an os chunk are free, we keep a few around
  80. but otherwise it will be freed to the OS.
  81. Fixed os chunks can be converted to variable os chunks and back
  82. (if not too big). To prevent repeated conversion overhead in case
  83. of user freeing/allocing same or a small set of sizes, we only do
  84. the conversion to the new fixed os chunk size format after we
  85. reuse the os chunk for another fixed size, or variable. Note that
  86. while the fixed size os chunk is on the freelists.oslist, it is also
  87. still present in a freelists.fixedlists, therefore we can easily remove
  88. the os chunk from the freelists.oslist if this size is needed again; we
  89. don't need to search freelists.oslist in alloc_oschunk, since it won't
  90. be present anymore if alloc_oschunk is reached. Note that removing
  91. from the freelists.oslist is not really done, only the recycleflag is
  92. set, allowing to reset the flag easily. alloc_oschunk will clean up
  93. the list while passing over it, that was a slow function anyway.
  94. }
  95. type
  96. pfreelists = ^tfreelists;
  97. poschunk = ^toschunk;
  98. toschunk = record
  99. size : 0..high(ptrint); {Cannot be ptruint because used field is signed.}
  100. next_free : poschunk;
  101. prev_any : poschunk;
  102. next_any : poschunk;
  103. used : ptrint; { 0: free, >0: fixed, -1: var }
  104. freelists : pfreelists;
  105. { padding inserted automatically by alloc_oschunk }
  106. end;
  107. ppmemchunk_fixed = ^pmemchunk_fixed;
  108. pmemchunk_fixed = ^tmemchunk_fixed;
  109. tmemchunk_fixed = record
  110. { aligning is done automatically in alloc_oschunk }
  111. size : ptruint;
  112. next_fixed,
  113. prev_fixed : pmemchunk_fixed;
  114. end;
  115. ppmemchunk_var = ^pmemchunk_var;
  116. pmemchunk_var = ^tmemchunk_var;
  117. tmemchunk_var = record
  118. prevsize : ptruint;
  119. freelists : pfreelists;
  120. size : ptruint;
  121. next_var,
  122. prev_var : pmemchunk_var;
  123. end;
  124. { ``header'', ie. size of structure valid when chunk is in use }
  125. { should correspond to tmemchunk_var_hdr structure starting with the
  126. last field. Reason is that the overlap is starting from the end of the
  127. record. }
  128. tmemchunk_fixed_hdr = record
  129. { aligning is done automatically in alloc_oschunk }
  130. size : ptruint;
  131. end;
  132. tmemchunk_var_hdr = record
  133. prevsize : ptruint;
  134. freelists : pfreelists;
  135. size : ptruint;
  136. end;
  137. pfpcheapstatus = ^tfpcheapstatus;
  138. tfixedfreelists = array[1..maxblockindex] of pmemchunk_fixed;
  139. tfreelists = record
  140. oslist : poschunk; { os chunks free, available for use }
  141. oscount : dword; { number of os chunks on oslist }
  142. oslist_all : poschunk; { all os chunks allocated }
  143. fixedlists : tfixedfreelists;
  144. varlist : pmemchunk_var;
  145. { chunks waiting to be freed from other thread }
  146. waitfixed : pmemchunk_fixed;
  147. waitvar : pmemchunk_var;
  148. { heap statistics }
  149. internal_status : TFPCHeapStatus;
  150. end;
  151. const
  152. fixedfirstoffset = ((sizeof(toschunk) + sizeof(tmemchunk_fixed_hdr) + $f)
  153. and not $f) - sizeof(tmemchunk_fixed_hdr);
  154. varfirstoffset = ((sizeof(toschunk) + sizeof(tmemchunk_var_hdr) + $f)
  155. and not $f) - sizeof(tmemchunk_var_hdr);
  156. {$ifdef BESTMATCH}
  157. matcheffort = high(longint);
  158. {$else}
  159. matcheffort = 10;
  160. {$endif}
  161. var
  162. main_relo_freelists : pfreelists;
  163. orphaned_freelists : tfreelists;
  164. heap_lock : trtlcriticalsection;
  165. threadvar
  166. freelists : tfreelists;
  167. {$ifdef DUMP_MEM_USAGE}
  168. const
  169. sizeusageshift = 4;
  170. sizeusageindex = 2049;
  171. sizeusagesize = sizeusageindex shl sizeusageshift;
  172. type
  173. tsizeusagelist = array[0..sizeusageindex] of longint;
  174. threadvar
  175. sizeusage, maxsizeusage: tsizeusagelist;
  176. {$endif}
  177. {$endif HAS_MEMORYMANAGER}
  178. {*****************************************************************************
  179. Memory Manager
  180. *****************************************************************************}
  181. procedure GetMemoryManager(var MemMgr:TMemoryManager);
  182. begin
  183. MemMgr := MemoryManager;
  184. end;
  185. procedure SetMemoryManager(const MemMgr:TMemoryManager);
  186. begin
  187. MemoryManager := MemMgr;
  188. end;
  189. function IsMemoryManagerSet:Boolean;
  190. begin
  191. IsMemoryManagerSet := (MemoryManager.GetMem<>@SysGetMem)
  192. or (MemoryManager.FreeMem<>@SysFreeMem);
  193. end;
  194. procedure GetMem(Var p:pointer;Size:ptruint);
  195. begin
  196. p := MemoryManager.GetMem(Size);
  197. end;
  198. procedure GetMemory(Var p:pointer;Size:ptruint);
  199. begin
  200. GetMem(p,size);
  201. end;
  202. procedure FreeMem(p:pointer;Size:ptruint);
  203. begin
  204. MemoryManager.FreeMemSize(p,Size);
  205. end;
  206. procedure FreeMemory(p:pointer;Size:ptruint);
  207. begin
  208. FreeMem(p,size);
  209. end;
  210. function GetHeapStatus:THeapStatus;
  211. begin
  212. Result:=MemoryManager.GetHeapStatus();
  213. end;
  214. function GetFPCHeapStatus:TFPCHeapStatus;
  215. begin
  216. Result:=MemoryManager.GetFPCHeapStatus();
  217. end;
  218. function MemSize(p:pointer):ptruint;
  219. begin
  220. MemSize := MemoryManager.MemSize(p);
  221. end;
  222. { Delphi style }
  223. function FreeMem(p:pointer):ptruint;[Public,Alias:'FPC_FREEMEM_X'];
  224. begin
  225. FreeMem := MemoryManager.FreeMem(p);
  226. end;
  227. function FreeMemory(p:pointer):ptruint;
  228. begin
  229. FreeMemory := FreeMem(p);
  230. end;
  231. function GetMem(size:ptruint):pointer;
  232. begin
  233. GetMem := MemoryManager.GetMem(Size);
  234. end;
  235. function GetMemory(size:ptruint):pointer;
  236. begin
  237. GetMemory := GetMem(size);
  238. end;
  239. function AllocMem(Size:ptruint):pointer;
  240. begin
  241. AllocMem := MemoryManager.AllocMem(size);
  242. end;
  243. function ReAllocMem(var p:pointer;Size:ptruint):pointer;
  244. begin
  245. ReAllocMem := MemoryManager.ReAllocMem(p,size);
  246. end;
  247. function ReAllocMemory(var p:pointer;Size:ptruint):pointer;
  248. begin
  249. ReAllocMemory := ReAllocMem(p,size);
  250. end;
  251. { Needed for calls from Assembler }
  252. function fpc_getmem(size:ptruint):pointer;compilerproc;[public,alias:'FPC_GETMEM'];
  253. begin
  254. fpc_GetMem := MemoryManager.GetMem(size);
  255. end;
  256. procedure fpc_freemem(p:pointer);compilerproc;[public,alias:'FPC_FREEMEM'];
  257. begin
  258. MemoryManager.FreeMem(p);
  259. end;
  260. {$ifndef HAS_MEMORYMANAGER}
  261. {*****************************************************************************
  262. GetHeapStatus
  263. *****************************************************************************}
  264. function SysGetFPCHeapStatus:TFPCHeapStatus;
  265. var
  266. status: pfpcheapstatus;
  267. begin
  268. status := @freelists.internal_status;
  269. status^.CurrHeapFree := status^.CurrHeapSize - status^.CurrHeapUsed;
  270. result := status^;
  271. end;
  272. function SysGetHeapStatus :THeapStatus;
  273. var
  274. status: pfpcheapstatus;
  275. begin
  276. status := @freelists.internal_status;
  277. status^.CurrHeapFree := status^.CurrHeapSize - status^.CurrHeapUsed;
  278. result.TotalAllocated :=status^.CurrHeapUsed;
  279. result.TotalFree :=status^.CurrHeapFree;
  280. result.TotalAddrSpace :=status^.CurrHeapSize;
  281. result.TotalUncommitted :=0;
  282. result.TotalCommitted :=0;
  283. result.FreeSmall :=0;
  284. result.FreeBig :=0;
  285. result.Unused :=0;
  286. result.Overhead :=0;
  287. result.HeapErrorCode :=0;
  288. end;
  289. {$ifdef DUMPBLOCKS} // TODO
  290. procedure DumpBlocks(loc_freelists: pfreelists);
  291. var
  292. s,i,j : ptruint;
  293. hpfixed : pmemchunk_fixed;
  294. hpvar : pmemchunk_var;
  295. begin
  296. { fixed freelist }
  297. for i := 1 to maxblockindex do
  298. begin
  299. hpfixed := loc_freelists^.fixedlists[i];
  300. j := 0;
  301. while assigned(hpfixed) do
  302. begin
  303. inc(j);
  304. hpfixed := hpfixed^.next_fixed;
  305. end;
  306. writeln('Block ',i*blocksize,': ',j);
  307. end;
  308. { var freelist }
  309. hpvar := loc_freelists^.varlist;
  310. j := 0;
  311. s := 0;
  312. while assigned(hpvar) do
  313. begin
  314. inc(j);
  315. if hpvar^.size>s then
  316. s := hpvar^.size;
  317. hpvar := hpvar^.next_var;
  318. end;
  319. writeln('Variable: ',j,' maxsize: ',s);
  320. end;
  321. {$endif}
  322. {*****************************************************************************
  323. Forwards
  324. *****************************************************************************}
  325. procedure finish_waitfixedlist(loc_freelists: pfreelists); forward;
  326. procedure finish_waitvarlist(loc_freelists: pfreelists); forward;
  327. function try_finish_waitfixedlist(loc_freelists: pfreelists): boolean; forward;
  328. procedure try_finish_waitvarlist(loc_freelists: pfreelists); forward;
  329. {*****************************************************************************
  330. List adding/removal
  331. *****************************************************************************}
  332. procedure append_to_list_var(pmc: pmemchunk_var); inline;
  333. var
  334. varlist: ppmemchunk_var;
  335. begin
  336. varlist := @pmc^.freelists^.varlist;
  337. pmc^.prev_var := nil;
  338. pmc^.next_var := varlist^;
  339. if varlist^<>nil then
  340. varlist^^.prev_var := pmc;
  341. varlist^ := pmc;
  342. end;
  343. {$ifdef HEAP_DEBUG}
  344. function find_fixed_mc(loc_freelists: pfreelists; chunkindex: ptruint;
  345. pmc: pmemchunk_fixed): boolean;
  346. var
  347. pmc_temp: pmemchunk_fixed;
  348. begin
  349. pmc_temp := loc_freelists^.fixedlists[chunkindex];
  350. while pmc_temp <> nil do
  351. begin
  352. if pmc_temp = pmc then exit(true);
  353. pmc_temp := pmc_temp^.next_fixed;
  354. end;
  355. result := false;
  356. end;
  357. {$endif}
  358. procedure remove_from_list_fixed(pmc: pmemchunk_fixed; fixedlist: ppmemchunk_fixed); inline;
  359. begin
  360. if assigned(pmc^.next_fixed) then
  361. pmc^.next_fixed^.prev_fixed := pmc^.prev_fixed;
  362. if assigned(pmc^.prev_fixed) then
  363. pmc^.prev_fixed^.next_fixed := pmc^.next_fixed
  364. else
  365. fixedlist^ := pmc^.next_fixed;
  366. end;
  367. procedure remove_from_list_var(pmc: pmemchunk_var); inline;
  368. begin
  369. if assigned(pmc^.next_var) then
  370. pmc^.next_var^.prev_var := pmc^.prev_var;
  371. if assigned(pmc^.prev_var) then
  372. pmc^.prev_var^.next_var := pmc^.next_var
  373. else
  374. pmc^.freelists^.varlist := pmc^.next_var;
  375. end;
  376. procedure remove_freed_fixed_chunks(poc: poschunk);
  377. { remove all fixed chunks from the fixed free list, as this os chunk
  378. is going to be used for other purpose }
  379. var
  380. pmc, pmc_end: pmemchunk_fixed;
  381. fixedlist: ppmemchunk_fixed;
  382. chunksize: ptruint;
  383. begin
  384. { exit if this is a var size os chunk, function only applicable to fixed size }
  385. if poc^.used < 0 then
  386. exit;
  387. pmc := pmemchunk_fixed(pointer(poc)+fixedfirstoffset);
  388. chunksize := pmc^.size and fixedsizemask;
  389. pmc_end := pmemchunk_fixed(pointer(poc)+(poc^.size and sizemask)-chunksize);
  390. fixedlist := @poc^.freelists^.fixedlists[chunksize shr blockshift];
  391. repeat
  392. remove_from_list_fixed(pmc, fixedlist);
  393. pmc := pointer(pmc)+chunksize;
  394. until pmc > pmc_end;
  395. end;
  396. procedure free_oschunk(loc_freelists: pfreelists; poc: poschunk);
  397. var
  398. pocsize: ptruint;
  399. begin
  400. remove_freed_fixed_chunks(poc);
  401. if assigned(poc^.prev_any) then
  402. poc^.prev_any^.next_any := poc^.next_any
  403. else
  404. loc_freelists^.oslist_all := poc^.next_any;
  405. if assigned(poc^.next_any) then
  406. poc^.next_any^.prev_any := poc^.prev_any;
  407. pocsize := poc^.size and sizemask;
  408. dec(loc_freelists^.internal_status.currheapsize, pocsize);
  409. SysOSFree(poc, pocsize);
  410. end;
  411. procedure append_to_oslist(poc: poschunk);
  412. var
  413. loc_freelists: pfreelists;
  414. begin
  415. loc_freelists := poc^.freelists;
  416. { check if already on list }
  417. if (poc^.size and ocrecycleflag) <> 0 then
  418. begin
  419. inc(loc_freelists^.oscount);
  420. poc^.size := poc^.size and not ocrecycleflag;
  421. exit;
  422. end;
  423. { decide whether to free block or add to list }
  424. {$ifdef HAS_SYSOSFREE}
  425. if (loc_freelists^.oscount >= MaxKeptOSChunks) or
  426. ((poc^.size and sizemask) > growheapsize2) then
  427. begin
  428. free_oschunk(loc_freelists, poc);
  429. end
  430. else
  431. begin
  432. {$endif}
  433. poc^.next_free := loc_freelists^.oslist;
  434. loc_freelists^.oslist := poc;
  435. inc(loc_freelists^.oscount);
  436. {$ifdef HAS_SYSOSFREE}
  437. end;
  438. {$endif}
  439. end;
  440. procedure append_to_oslist_var(pmc: pmemchunk_var);
  441. var
  442. poc: poschunk;
  443. begin
  444. // block eligable for freeing
  445. poc := pointer(pmc)-varfirstoffset;
  446. remove_from_list_var(pmc);
  447. append_to_oslist(poc);
  448. end;
  449. procedure modify_oschunk_freelists(poc: poschunk; new_freelists: pfreelists);
  450. var
  451. pmcv: pmemchunk_var;
  452. begin
  453. poc^.freelists := new_freelists;
  454. { only if oschunk contains var memchunks, we need additional assignments }
  455. if poc^.used <> -1 then exit;
  456. pmcv := pmemchunk_var(pointer(poc)+varfirstoffset);
  457. repeat
  458. pmcv^.freelists := new_freelists;
  459. if (pmcv^.size and lastblockflag) <> 0 then
  460. break;
  461. pmcv := pmemchunk_var(pointer(pmcv)+(pmcv^.size and sizemask));
  462. until false;
  463. end;
  464. function modify_freelists(loc_freelists, new_freelists: pfreelists): poschunk;
  465. var
  466. poc: poschunk;
  467. begin
  468. poc := loc_freelists^.oslist_all;
  469. if assigned(poc) then
  470. begin
  471. repeat
  472. { fixed and var freelist for orphaned freelists do not need maintenance }
  473. { we assume the heap is not severely fragmented at thread exit }
  474. modify_oschunk_freelists(poc, new_freelists);
  475. if not assigned(poc^.next_any) then
  476. exit(poc);
  477. poc := poc^.next_any;
  478. until false;
  479. end;
  480. modify_freelists := nil;
  481. end;
  482. {*****************************************************************************
  483. Split block
  484. *****************************************************************************}
  485. function split_block(pcurr: pmemchunk_var; size: ptruint): ptruint;
  486. var
  487. pcurr_tmp : pmemchunk_var;
  488. size_flags, oldsize, sizeleft: ptruint;
  489. begin
  490. size_flags := pcurr^.size;
  491. oldsize := size_flags and sizemask;
  492. sizeleft := oldsize-size;
  493. if sizeleft>=sizeof(tmemchunk_var) then
  494. begin
  495. pcurr_tmp := pmemchunk_var(pointer(pcurr)+size);
  496. { update prevsize of block to the right }
  497. if (size_flags and lastblockflag) = 0 then
  498. pmemchunk_var(pointer(pcurr)+oldsize)^.prevsize := sizeleft;
  499. { inherit the lastblockflag }
  500. pcurr_tmp^.size := sizeleft or (size_flags and lastblockflag);
  501. pcurr_tmp^.prevsize := size;
  502. pcurr_tmp^.freelists := pcurr^.freelists;
  503. { the block we return is not the last one anymore (there's now a block after it) }
  504. { decrease size of block to new size }
  505. pcurr^.size := size or (size_flags and (not sizemask and not lastblockflag));
  506. { insert the block in the freelist }
  507. append_to_list_var(pcurr_tmp);
  508. result := size;
  509. end
  510. else
  511. result := oldsize;
  512. end;
  513. {*****************************************************************************
  514. Try concat freerecords
  515. *****************************************************************************}
  516. procedure concat_two_blocks(mc_left, mc_right: pmemchunk_var);
  517. var
  518. mc_tmp : pmemchunk_var;
  519. size_right : ptruint;
  520. begin
  521. // mc_right can't be a fixed size block
  522. if mc_right^.size and fixedsizeflag<>0 then
  523. HandleError(204);
  524. // left block free, concat with right-block
  525. size_right := mc_right^.size and sizemask;
  526. inc(mc_left^.size, size_right);
  527. // if right-block was last block, copy flag
  528. if (mc_right^.size and lastblockflag) <> 0 then
  529. begin
  530. mc_left^.size := mc_left^.size or lastblockflag;
  531. end
  532. else
  533. begin
  534. // there is a block to the right of the right-block, adjust it's prevsize
  535. mc_tmp := pmemchunk_var(pointer(mc_right)+size_right);
  536. mc_tmp^.prevsize := mc_left^.size and sizemask;
  537. end;
  538. // remove right-block from doubly linked list
  539. remove_from_list_var(mc_right);
  540. end;
  541. function try_concat_free_chunk_forward(mc: pmemchunk_var): boolean;
  542. var
  543. mc_tmp : pmemchunk_var;
  544. begin
  545. { try concat forward }
  546. result := false;
  547. if (mc^.size and lastblockflag) = 0 then
  548. begin
  549. mc_tmp := pmemchunk_var(pointer(mc)+(mc^.size and sizemask));
  550. if (mc_tmp^.size and usedflag) = 0 then
  551. begin
  552. // next block free: concat
  553. concat_two_blocks(mc, mc_tmp);
  554. result := true;
  555. end;
  556. end;
  557. end;
  558. function try_concat_free_chunk(mc: pmemchunk_var): pmemchunk_var;
  559. var
  560. mc_tmp : pmemchunk_var;
  561. begin
  562. try_concat_free_chunk_forward(mc);
  563. { try concat backward }
  564. if (mc^.size and firstblockflag) = 0 then
  565. begin
  566. mc_tmp := pmemchunk_var(pointer(mc)-mc^.prevsize);
  567. if (mc_tmp^.size and usedflag) = 0 then
  568. begin
  569. // prior block free: concat
  570. concat_two_blocks(mc_tmp, mc);
  571. mc := mc_tmp;
  572. end;
  573. end;
  574. result := mc;
  575. end;
  576. {*****************************************************************************
  577. Grow Heap
  578. *****************************************************************************}
  579. function find_free_oschunk(loc_freelists: pfreelists;
  580. minsize, maxsize: ptruint; var size: ptruint): poschunk;
  581. var
  582. prev_poc, poc: poschunk;
  583. pocsize: ptruint;
  584. begin
  585. poc := loc_freelists^.oslist;
  586. prev_poc := nil;
  587. while poc <> nil do
  588. begin
  589. if (poc^.size and ocrecycleflag) <> 0 then
  590. begin
  591. { oops! we recycled this chunk; remove it from list }
  592. poc^.size := poc^.size and not ocrecycleflag;
  593. poc := poc^.next_free;
  594. if prev_poc = nil then
  595. loc_freelists^.oslist := poc
  596. else
  597. prev_poc^.next_free := poc;
  598. continue;
  599. end;
  600. pocsize := poc^.size and sizemask;
  601. if (pocsize >= minsize) and
  602. (pocsize <= maxsize) then
  603. begin
  604. size := pocsize;
  605. if prev_poc = nil then
  606. loc_freelists^.oslist := poc^.next_free
  607. else
  608. prev_poc^.next_free := poc^.next_free;
  609. dec(loc_freelists^.oscount);
  610. remove_freed_fixed_chunks(poc);
  611. break;
  612. end;
  613. prev_poc := poc;
  614. poc := poc^.next_free;
  615. end;
  616. result := poc;
  617. end;
  618. function alloc_oschunk(loc_freelists: pfreelists; chunkindex, size: ptruint): pointer;
  619. var
  620. pmc,
  621. pmc_next : pmemchunk_fixed;
  622. pmcv : pmemchunk_var;
  623. poc : poschunk;
  624. minsize,
  625. maxsize,
  626. i : ptruint;
  627. chunksize : ptruint;
  628. status : pfpcheapstatus;
  629. begin
  630. { increase size by size needed for os block header }
  631. minsize := size + varfirstoffset;
  632. { for fixed size chunks we keep offset from os chunk to mem chunk in
  633. upper bits, so maximum os chunk size is 64K on 32bit for fixed size }
  634. if chunkindex<>0 then
  635. maxsize := 1 shl (32-fixedoffsetshift)
  636. else
  637. maxsize := high(ptruint);
  638. { blocks available in freelist? }
  639. poc := find_free_oschunk(loc_freelists, minsize, maxsize, size);
  640. if not assigned(poc) and (assigned(orphaned_freelists.waitfixed)
  641. or assigned(orphaned_freelists.waitvar) or (orphaned_freelists.oscount > 0)) then
  642. begin
  643. entercriticalsection(heap_lock);
  644. finish_waitfixedlist(@orphaned_freelists);
  645. finish_waitvarlist(@orphaned_freelists);
  646. if orphaned_freelists.oscount > 0 then
  647. begin
  648. { blocks available in orphaned freelist ? }
  649. poc := find_free_oschunk(@orphaned_freelists, minsize, maxsize, size);
  650. if assigned(poc) then
  651. begin
  652. { adopt this os chunk }
  653. poc^.freelists := loc_freelists;
  654. if assigned(poc^.prev_any) then
  655. poc^.prev_any^.next_any := poc^.next_any
  656. else
  657. orphaned_freelists.oslist_all := poc^.next_any;
  658. if assigned(poc^.next_any) then
  659. poc^.next_any^.prev_any := poc^.prev_any;
  660. poc^.next_any := loc_freelists^.oslist_all;
  661. if assigned(loc_freelists^.oslist_all) then
  662. loc_freelists^.oslist_all^.prev_any := poc;
  663. poc^.prev_any := nil;
  664. loc_freelists^.oslist_all := poc;
  665. end;
  666. end;
  667. leavecriticalsection(heap_lock);
  668. end;
  669. if poc = nil then
  670. begin
  671. {$ifdef DUMPGROW}
  672. writeln('growheap(',size,') allocating ',(size+sizeof(toschunk)+$ffff) and not $ffff);
  673. DumpBlocks(loc_freelists);
  674. {$endif}
  675. { allocate by 64K size }
  676. size := (size+varfirstoffset+$ffff) and not $ffff;
  677. { allocate smaller blocks for fixed-size chunks }
  678. if chunkindex<>0 then
  679. begin
  680. poc := SysOSAlloc(GrowHeapSizeSmall);
  681. if poc<>nil then
  682. size := GrowHeapSizeSmall;
  683. end
  684. { first try 256K (default) }
  685. else if size<=GrowHeapSize1 then
  686. begin
  687. poc := SysOSAlloc(GrowHeapSize1);
  688. if poc<>nil then
  689. size := GrowHeapSize1;
  690. end
  691. { second try 1024K (default) }
  692. else if size<=GrowHeapSize2 then
  693. begin
  694. poc := SysOSAlloc(GrowHeapSize2);
  695. if poc<>nil then
  696. size := GrowHeapSize2;
  697. end
  698. { else allocate the needed bytes }
  699. else
  700. poc := SysOSAlloc(size);
  701. { try again }
  702. if poc=nil then
  703. begin
  704. poc := SysOSAlloc(size);
  705. if poc=nil then
  706. begin
  707. if ReturnNilIfGrowHeapFails then
  708. begin
  709. result := nil;
  710. exit
  711. end
  712. else
  713. HandleError(203);
  714. end;
  715. end;
  716. poc^.freelists := loc_freelists;
  717. poc^.prev_any := nil;
  718. poc^.next_any := loc_freelists^.oslist_all;
  719. if assigned(loc_freelists^.oslist_all) then
  720. loc_freelists^.oslist_all^.prev_any := poc;
  721. loc_freelists^.oslist_all := poc;
  722. { set the total new heap size }
  723. status := @loc_freelists^.internal_status;
  724. inc(status^.currheapsize, size);
  725. if status^.currheapsize > status^.maxheapsize then
  726. status^.maxheapsize := status^.currheapsize;
  727. end;
  728. { initialize os-block }
  729. poc^.size := size;
  730. if chunkindex<>0 then
  731. begin
  732. poc^.used := 0;
  733. { chop os chunk in fixedsize parts,
  734. maximum of $ffff elements are allowed, otherwise
  735. there will be an overflow }
  736. chunksize := chunkindex shl blockshift;
  737. if size-chunksize>maxsize then
  738. HandleError(204);
  739. { we need to align the user pointers to 8 byte at least for
  740. mmx/sse and doubles on sparc, align to 16 bytes }
  741. i := fixedfirstoffset;
  742. result := pointer(poc) + i;
  743. pmc := pmemchunk_fixed(result);
  744. pmc^.prev_fixed := nil;
  745. repeat
  746. pmc^.size := fixedsizeflag or chunksize or (i shl fixedoffsetshift);
  747. inc(i, chunksize);
  748. if i > size - chunksize then break;
  749. pmc_next := pmemchunk_fixed(pointer(pmc)+chunksize);
  750. pmc^.next_fixed := pmc_next;
  751. pmc_next^.prev_fixed := pmc;
  752. pmc := pmc_next;
  753. until false;
  754. pmc_next := loc_freelists^.fixedlists[chunkindex];
  755. pmc^.next_fixed := pmc_next;
  756. if pmc_next<>nil then
  757. pmc_next^.prev_fixed := pmc;
  758. loc_freelists^.fixedlists[chunkindex] := pmemchunk_fixed(result);
  759. end
  760. else
  761. begin
  762. poc^.used := -1;
  763. { we need to align the user pointers to 8 byte at least for
  764. mmx/sse and doubles on sparc, align to 16 bytes }
  765. result := pointer(poc)+varfirstoffset;
  766. pmcv := pmemchunk_var(result);
  767. pmcv^.size := ((size-varfirstoffset) and sizemask) or (firstblockflag or lastblockflag);
  768. pmcv^.prevsize := 0;
  769. pmcv^.freelists := loc_freelists;
  770. append_to_list_var(pmcv);
  771. end;
  772. end;
  773. {*****************************************************************************
  774. SysGetMem
  775. *****************************************************************************}
  776. function SysGetMem_Fixed(chunksize: ptruint): pointer;
  777. var
  778. pmc, pmc_next: pmemchunk_fixed;
  779. poc: poschunk;
  780. chunkindex: ptruint;
  781. loc_freelists: pfreelists;
  782. begin
  783. { try to find a block in one of the freelists per size }
  784. chunkindex := chunksize shr blockshift;
  785. loc_freelists := @freelists;
  786. pmc := loc_freelists^.fixedlists[chunkindex];
  787. { no free blocks ? }
  788. if assigned(pmc) then
  789. begin
  790. { remove oschunk from free list in case we recycle it }
  791. poc := poschunk(pointer(pmc) - (pmc^.size shr fixedoffsetshift));
  792. if poc^.used = 0 then
  793. begin
  794. poc^.size := poc^.size or ocrecycleflag;
  795. dec(loc_freelists^.oscount);
  796. end;
  797. end
  798. else if try_finish_waitfixedlist(loc_freelists) then
  799. { freed some to-be freed chunks, retry allocation }
  800. exit(SysGetMem_Fixed(chunksize))
  801. else
  802. begin
  803. pmc := alloc_oschunk(loc_freelists, chunkindex, chunksize);
  804. if not assigned(pmc) then
  805. exit(nil);
  806. poc := poschunk(pointer(pmc)-fixedfirstoffset);
  807. end;
  808. { get a pointer to the block we should return }
  809. result := pointer(pmc)+sizeof(tmemchunk_fixed_hdr);
  810. { update freelist }
  811. pmc_next := pmc^.next_fixed;
  812. loc_freelists^.fixedlists[chunkindex] := pmc_next;
  813. if assigned(pmc_next) then
  814. pmc_next^.prev_fixed := nil;
  815. inc(poc^.used);
  816. { statistics }
  817. with loc_freelists^.internal_status do
  818. begin
  819. inc(currheapused, chunksize);
  820. if currheapused > maxheapused then
  821. begin
  822. maxheapused := currheapused;
  823. {$ifdef DUMP_MEM_USAGE}
  824. maxsizeusage := sizeusage;
  825. {$endif}
  826. end;
  827. end;
  828. end;
  829. function SysGetMem_Var(size: ptruint): pointer;
  830. var
  831. pcurr : pmemchunk_var;
  832. pbest : pmemchunk_var;
  833. loc_freelists : pfreelists;
  834. iter : cardinal;
  835. begin
  836. result:=nil;
  837. { free pending items }
  838. loc_freelists := @freelists;
  839. try_finish_waitvarlist(loc_freelists);
  840. pbest := nil;
  841. pcurr := loc_freelists^.varlist;
  842. iter := high(iter);
  843. while assigned(pcurr) and (iter>0) do
  844. begin
  845. if (pcurr^.size>size) then
  846. begin
  847. if not assigned(pbest) or (pcurr^.size<pbest^.size) then
  848. begin
  849. pbest := pcurr;
  850. if pcurr^.size = size then
  851. break;
  852. iter := matcheffort;
  853. end;
  854. end;
  855. pcurr := pcurr^.next_var;
  856. dec(iter);
  857. end;
  858. pcurr := pbest;
  859. if not assigned(pcurr) then
  860. begin
  861. // all os-chunks full, allocate a new one
  862. pcurr := alloc_oschunk(loc_freelists, 0, size);
  863. if not assigned(pcurr) then
  864. exit;
  865. end;
  866. { get pointer of the block we should return }
  867. result := pointer(pcurr)+sizeof(tmemchunk_var_hdr);
  868. { remove the current block from the freelist }
  869. remove_from_list_var(pcurr);
  870. { create the left over freelist block, if at least 16 bytes are free }
  871. size := split_block(pcurr, size);
  872. { flag block as used }
  873. pcurr^.size := pcurr^.size or usedflag;
  874. { statistics }
  875. with loc_freelists^.internal_status do
  876. begin
  877. inc(currheapused, size);
  878. if currheapused > maxheapused then
  879. begin
  880. maxheapused := currheapused;
  881. {$ifdef DUMP_MEM_USAGE}
  882. maxsizeusage := sizeusage;
  883. {$endif}
  884. end;
  885. end;
  886. end;
  887. function SysGetMem(size : ptruint):pointer;
  888. begin
  889. { Something to allocate ? }
  890. if size=0 then
  891. { we always need to allocate something, using heapend is not possible,
  892. because heappend can be changed by growheap (PFV) }
  893. size := 1;
  894. { calc to multiple of 16 after adding the needed bytes for memchunk header }
  895. if size <= (maxblocksize - sizeof(tmemchunk_fixed_hdr)) then
  896. begin
  897. size := (size+(sizeof(tmemchunk_fixed_hdr)+(blocksize-1))) and fixedsizemask;
  898. result := sysgetmem_fixed(size);
  899. end
  900. else
  901. begin
  902. size := (size+(sizeof(tmemchunk_var_hdr)+(blocksize-1))) and sizemask;
  903. result := sysgetmem_var(size);
  904. end;
  905. {$ifdef DUMP_MEM_USAGE}
  906. size := sysmemsize(result);
  907. if size > sizeusagesize then
  908. inc(sizeusage[sizeusageindex])
  909. else
  910. inc(sizeusage[size shr sizeusageshift]);
  911. {$endif}
  912. end;
  913. {*****************************************************************************
  914. SysFreeMem
  915. *****************************************************************************}
  916. procedure waitfree_fixed(pmc: pmemchunk_fixed; poc: poschunk);
  917. begin
  918. entercriticalsection(heap_lock);
  919. pmc^.next_fixed := poc^.freelists^.waitfixed;
  920. poc^.freelists^.waitfixed := pmc;
  921. leavecriticalsection(heap_lock);
  922. end;
  923. procedure waitfree_var(pmcv: pmemchunk_var);
  924. begin
  925. entercriticalsection(heap_lock);
  926. pmcv^.next_var := pmcv^.freelists^.waitvar;
  927. pmcv^.freelists^.waitvar := pmcv;
  928. leavecriticalsection(heap_lock);
  929. end;
  930. function SysFreeMem_Fixed(loc_freelists: pfreelists; pmc: pmemchunk_fixed): ptruint;
  931. var
  932. chunkindex,
  933. chunksize: ptruint;
  934. poc: poschunk;
  935. pmc_next: pmemchunk_fixed;
  936. begin
  937. poc := poschunk(pointer(pmc)-(pmc^.size shr fixedoffsetshift));
  938. chunksize := pmc^.size and fixedsizemask;
  939. if loc_freelists <> poc^.freelists then
  940. begin
  941. { deallocated in wrong thread! add to to-be-freed list of correct thread }
  942. waitfree_fixed(pmc, poc);
  943. exit(chunksize);
  944. end;
  945. dec(loc_freelists^.internal_status.currheapused, chunksize);
  946. { insert the block in it's freelist }
  947. chunkindex := chunksize shr blockshift;
  948. pmc_next := loc_freelists^.fixedlists[chunkindex];
  949. pmc^.prev_fixed := nil;
  950. pmc^.next_fixed := pmc_next;
  951. if assigned(pmc_next) then
  952. pmc_next^.prev_fixed := pmc;
  953. loc_freelists^.fixedlists[chunkindex] := pmc;
  954. { decrease used blocks count }
  955. dec(poc^.used);
  956. if poc^.used <= 0 then
  957. begin
  958. { decrease used blocks count }
  959. if poc^.used<0 then
  960. HandleError(204);
  961. { osblock can be freed? }
  962. append_to_oslist(poc);
  963. end;
  964. result := chunksize;
  965. end;
  966. function SysFreeMem_Var(loc_freelists: pfreelists; pmcv: pmemchunk_var): ptruint;
  967. var
  968. chunksize: ptruint;
  969. begin
  970. chunksize := pmcv^.size and sizemask;
  971. if loc_freelists <> pmcv^.freelists then
  972. begin
  973. { deallocated in wrong thread! add to to-be-freed list of correct thread }
  974. waitfree_var(pmcv);
  975. exit(chunksize);
  976. end;
  977. dec(loc_freelists^.internal_status.currheapused, chunksize);
  978. { insert the block in it's freelist }
  979. pmcv^.size := pmcv^.size and (not usedflag);
  980. append_to_list_var(pmcv);
  981. pmcv := try_concat_free_chunk(pmcv);
  982. if (pmcv^.size and (firstblockflag or lastblockflag)) = (firstblockflag or lastblockflag) then
  983. append_to_oslist_var(pmcv);
  984. result := chunksize;
  985. end;
  986. function SysFreeMem(p: pointer): ptruint;
  987. var
  988. pmc: pmemchunk_fixed;
  989. loc_freelists: pfreelists;
  990. {$ifdef DUMP_MEM_USAGE}
  991. size: sizeint;
  992. {$endif}
  993. begin
  994. if p=nil then
  995. begin
  996. result:=0;
  997. exit;
  998. end;
  999. {$ifdef DUMP_MEM_USAGE}
  1000. size := sysmemsize(p);
  1001. if size > sizeusagesize then
  1002. dec(sizeusage[sizeusageindex])
  1003. else
  1004. dec(sizeusage[size shr sizeusageshift]);
  1005. {$endif}
  1006. loc_freelists := @freelists;
  1007. pmc := pmemchunk_fixed(p-sizeof(tmemchunk_fixed_hdr));
  1008. { check if this is a fixed- or var-sized chunk }
  1009. if (pmc^.size and fixedsizeflag) = 0 then
  1010. result := sysfreemem_var(loc_freelists, pmemchunk_var(p-sizeof(tmemchunk_var_hdr)))
  1011. else
  1012. result := sysfreemem_fixed(loc_freelists, pmc);
  1013. end;
  1014. procedure finish_waitfixedlist(loc_freelists: pfreelists);
  1015. { free to-be-freed chunks, return whether we freed anything }
  1016. var
  1017. pmc: pmemchunk_fixed;
  1018. begin
  1019. while loc_freelists^.waitfixed <> nil do
  1020. begin
  1021. { keep next_fixed, might be destroyed }
  1022. pmc := loc_freelists^.waitfixed;
  1023. loc_freelists^.waitfixed := pmc^.next_fixed;
  1024. SysFreeMem_Fixed(loc_freelists, pmc);
  1025. end;
  1026. end;
  1027. function try_finish_waitfixedlist(loc_freelists: pfreelists): boolean;
  1028. begin
  1029. if loc_freelists^.waitfixed = nil then
  1030. exit(false);
  1031. entercriticalsection(heap_lock);
  1032. finish_waitfixedlist(loc_freelists);
  1033. leavecriticalsection(heap_lock);
  1034. result := true;
  1035. end;
  1036. procedure finish_waitvarlist(loc_freelists: pfreelists);
  1037. { free to-be-freed chunks, return whether we freed anything }
  1038. var
  1039. pmcv: pmemchunk_var;
  1040. begin
  1041. while loc_freelists^.waitvar <> nil do
  1042. begin
  1043. { keep next_var, might be destroyed }
  1044. pmcv := loc_freelists^.waitvar;
  1045. loc_freelists^.waitvar := pmcv^.next_var;
  1046. SysFreeMem_Var(loc_freelists, pmcv);
  1047. end;
  1048. end;
  1049. procedure try_finish_waitvarlist(loc_freelists: pfreelists);
  1050. begin
  1051. if loc_freelists^.waitvar = nil then
  1052. exit;
  1053. entercriticalsection(heap_lock);
  1054. finish_waitvarlist(loc_freelists);
  1055. leavecriticalsection(heap_lock);
  1056. end;
  1057. {*****************************************************************************
  1058. SysFreeMemSize
  1059. *****************************************************************************}
  1060. Function SysFreeMemSize(p: pointer; size: ptruint):ptruint;
  1061. begin
  1062. if size=0 then
  1063. exit(0);
  1064. { can't free partial blocks, ignore size }
  1065. result := SysFreeMem(p);
  1066. end;
  1067. {*****************************************************************************
  1068. SysMemSize
  1069. *****************************************************************************}
  1070. function SysMemSize(p: pointer): ptruint;
  1071. begin
  1072. result := pmemchunk_fixed(pointer(p)-sizeof(tmemchunk_fixed_hdr))^.size;
  1073. if (result and fixedsizeflag) = 0 then
  1074. begin
  1075. result := result and sizemask;
  1076. dec(result, sizeof(tmemchunk_var_hdr));
  1077. end
  1078. else
  1079. begin
  1080. result := result and fixedsizemask;
  1081. dec(result, sizeof(tmemchunk_fixed_hdr));
  1082. end;
  1083. end;
  1084. {*****************************************************************************
  1085. SysAllocMem
  1086. *****************************************************************************}
  1087. function SysAllocMem(size: ptruint): pointer;
  1088. begin
  1089. result := MemoryManager.GetMem(size);
  1090. if result<>nil then
  1091. FillChar(result^,MemoryManager.MemSize(result),0);
  1092. end;
  1093. {*****************************************************************************
  1094. SysResizeMem
  1095. *****************************************************************************}
  1096. function SysTryResizeMem(var p: pointer; size: ptruint): boolean;
  1097. var
  1098. chunksize,
  1099. oldsize,
  1100. currsize : ptruint;
  1101. pcurr : pmemchunk_var;
  1102. begin
  1103. SysTryResizeMem := false;
  1104. { fix p to point to the heaprecord }
  1105. chunksize := pmemchunk_fixed(p-sizeof(tmemchunk_fixed_hdr))^.size;
  1106. { handle fixed memchuncks separate. Only allow resizes when the
  1107. new size fits in the same block }
  1108. if (chunksize and fixedsizeflag) <> 0 then
  1109. begin
  1110. currsize := chunksize and fixedsizemask;
  1111. { 1. Resizing to smaller sizes will never allocate a new block. We just keep the current block. This
  1112. is needed for the expectations that resizing to a small block will not move the contents of
  1113. a memory block
  1114. 2. For resizing to greater size first check if the size fits in the fixed block range to prevent
  1115. "truncating" the size by the fixedsizemask }
  1116. if ((size <= (maxblocksize - sizeof(tmemchunk_fixed_hdr))) and
  1117. ((size+(sizeof(tmemchunk_fixed_hdr)+(blocksize-1))) and sizemask <= currsize)) then
  1118. begin
  1119. systryresizemem:=true;
  1120. exit;
  1121. end;
  1122. { we need to allocate a new fixed or var memchunck }
  1123. exit;
  1124. end;
  1125. { var memchunk }
  1126. { do not fragment the heap with small shrinked blocks }
  1127. { also solves problem with var sized chunks smaller than sizeof(tmemchunk_var) }
  1128. if size < maxblocksize div 2 then
  1129. exit(false);
  1130. currsize := chunksize and sizemask;
  1131. size := (size+sizeof(tmemchunk_var_hdr)+(blocksize-1)) and sizemask;
  1132. { is the allocated block still correct? }
  1133. if (currsize>=size) and (size>ptruint(currsize-blocksize)) then
  1134. begin
  1135. SysTryResizeMem := true;
  1136. exit;
  1137. end;
  1138. { get pointer to block }
  1139. pcurr := pmemchunk_var(pointer(p)-sizeof(tmemchunk_var_hdr));
  1140. oldsize := currsize;
  1141. { do we need to allocate more memory ? }
  1142. if try_concat_free_chunk_forward(pcurr) then
  1143. currsize := pcurr^.size and sizemask;
  1144. if size>currsize then
  1145. begin
  1146. { the size is bigger than the previous size, we need to allocate more mem
  1147. but we could not concatenate with next block or not big enough }
  1148. exit;
  1149. end
  1150. else
  1151. { is the size smaller then we can adjust the block to that size and insert
  1152. the other part into the freelist }
  1153. if currsize>size then
  1154. currsize := split_block(pcurr, size);
  1155. with pcurr^.freelists^.internal_status do
  1156. begin
  1157. inc(currheapused, currsize-oldsize);
  1158. if currheapused > maxheapused then
  1159. maxheapused := currheapused;
  1160. end;
  1161. SysTryResizeMem := true;
  1162. end;
  1163. {*****************************************************************************
  1164. SysResizeMem
  1165. *****************************************************************************}
  1166. function SysReAllocMem(var p: pointer; size: ptruint):pointer;
  1167. var
  1168. newsize,
  1169. oldsize,
  1170. minsize : ptruint;
  1171. p2 : pointer;
  1172. begin
  1173. { Free block? }
  1174. if size=0 then
  1175. begin
  1176. if p<>nil then
  1177. begin
  1178. MemoryManager.FreeMem(p);
  1179. p := nil;
  1180. end;
  1181. end
  1182. else
  1183. { Allocate a new block? }
  1184. if p=nil then
  1185. begin
  1186. p := MemoryManager.GetMem(size);
  1187. end
  1188. else
  1189. begin
  1190. { Resize block }
  1191. {$ifdef DUMP_MEM_USAGE}
  1192. oldsize:=SysMemSize(p);
  1193. {$endif}
  1194. if not SysTryResizeMem(p,size) then
  1195. begin
  1196. oldsize:=MemoryManager.MemSize(p);
  1197. { Grow with bigger steps to prevent the need for
  1198. multiple getmem/freemem calls for fixed blocks. It might cost a bit
  1199. of extra memory, but in most cases a reallocmem is done multiple times. }
  1200. if oldsize<maxblocksize then
  1201. begin
  1202. newsize:=oldsize*2+blocksize;
  1203. if size>newsize then
  1204. newsize:=size;
  1205. end
  1206. else
  1207. newsize:=size;
  1208. { calc size of data to move }
  1209. minsize:=oldsize;
  1210. if newsize < minsize then
  1211. minsize := newsize;
  1212. p2 := MemoryManager.GetMem(newsize);
  1213. if p2<>nil then
  1214. Move(p^,p2^,minsize);
  1215. MemoryManager.FreeMem(p);
  1216. p := p2;
  1217. {$ifdef DUMP_MEM_USAGE}
  1218. end else begin
  1219. size := sysmemsize(p);
  1220. if size <> oldsize then
  1221. begin
  1222. if oldsize > sizeusagesize then
  1223. dec(sizeusage[sizeusageindex])
  1224. else if oldsize >= 0 then
  1225. dec(sizeusage[oldsize shr sizeusageshift]);
  1226. if size > sizeusagesize then
  1227. inc(sizeusage[sizeusageindex])
  1228. else if size >= 0 then
  1229. inc(sizeusage[size shr sizeusageshift]);
  1230. end;
  1231. {$endif}
  1232. end;
  1233. end;
  1234. SysReAllocMem := p;
  1235. end;
  1236. {$endif HAS_MEMORYMANAGER}
  1237. {$ifndef HAS_MEMORYMANAGER}
  1238. {*****************************************************************************
  1239. InitHeap
  1240. *****************************************************************************}
  1241. { This function will initialize the Heap manager and need to be called from
  1242. the initialization of the system unit }
  1243. procedure InitHeapThread;
  1244. var
  1245. loc_freelists: pfreelists;
  1246. begin
  1247. loc_freelists := @freelists;
  1248. fillchar(loc_freelists^,sizeof(tfreelists),0);
  1249. {$ifdef DUMP_MEM_USAGE}
  1250. fillchar(sizeusage,sizeof(sizeusage),0);
  1251. fillchar(maxsizeusage,sizeof(sizeusage),0);
  1252. {$endif}
  1253. end;
  1254. procedure InitHeap;
  1255. var
  1256. loc_freelists: pfreelists;
  1257. begin
  1258. { we cannot initialize the locks here yet, thread support is
  1259. not loaded yet }
  1260. loc_freelists := @freelists;
  1261. fillchar(loc_freelists^,sizeof(tfreelists),0);
  1262. fillchar(orphaned_freelists,sizeof(orphaned_freelists),0);
  1263. end;
  1264. procedure RelocateHeap;
  1265. var
  1266. loc_freelists: pfreelists;
  1267. begin
  1268. { this function should be called in main thread context }
  1269. loc_freelists := @freelists;
  1270. main_relo_freelists := loc_freelists;
  1271. initcriticalsection(heap_lock);
  1272. modify_freelists(loc_freelists, main_relo_freelists);
  1273. if MemoryManager.RelocateHeap <> nil then
  1274. MemoryManager.RelocateHeap();
  1275. end;
  1276. procedure FinalizeHeap;
  1277. var
  1278. poc, poc_next: poschunk;
  1279. loc_freelists: pfreelists;
  1280. {$ifdef DUMP_MEM_USAGE}
  1281. i : longint;
  1282. {$endif}
  1283. begin
  1284. loc_freelists := @freelists;
  1285. if main_relo_freelists <> nil then
  1286. begin
  1287. entercriticalsection(heap_lock);
  1288. finish_waitfixedlist(loc_freelists);
  1289. finish_waitvarlist(loc_freelists);
  1290. {$ifdef HAS_SYSOSFREE}
  1291. end;
  1292. poc := loc_freelists^.oslist;
  1293. while assigned(poc) do
  1294. begin
  1295. poc_next := poc^.next_free;
  1296. { check if this os chunk was 'recycled' i.e. taken in use again }
  1297. if (poc^.size and ocrecycleflag) = 0 then
  1298. free_oschunk(loc_freelists, poc)
  1299. else
  1300. poc^.size := poc^.size and not ocrecycleflag;
  1301. poc := poc_next;
  1302. end;
  1303. loc_freelists^.oslist := nil;
  1304. loc_freelists^.oscount := 0;
  1305. if main_relo_freelists <> nil then
  1306. begin
  1307. {$endif HAS_SYSOSFREE}
  1308. if main_relo_freelists <> loc_freelists then
  1309. begin
  1310. poc := modify_freelists(loc_freelists, @orphaned_freelists);
  1311. if assigned(poc) then
  1312. begin
  1313. poc^.next_any := orphaned_freelists.oslist_all;
  1314. if assigned(orphaned_freelists.oslist_all) then
  1315. orphaned_freelists.oslist_all^.prev_any := poc;
  1316. orphaned_freelists.oslist_all := loc_freelists^.oslist_all;
  1317. end;
  1318. end;
  1319. leavecriticalsection(heap_lock);
  1320. if main_relo_freelists = loc_freelists then
  1321. donecriticalsection(heap_lock);
  1322. end;
  1323. {$ifdef SHOW_MEM_USAGE}
  1324. writeln('Max heap used/size: ', loc_freelists^.internal_status.maxheapused, '/',
  1325. loc_freelists^.internal_status.maxheapsize);
  1326. flush(output);
  1327. {$endif}
  1328. {$ifdef DUMP_MEM_USAGE}
  1329. for i := 0 to sizeusageindex-1 do
  1330. if maxsizeusage[i] <> 0 then
  1331. writeln('size ', i shl sizeusageshift, ' usage ', maxsizeusage[i]);
  1332. writeln('size >', sizeusagesize, ' usage ', maxsizeusage[sizeusageindex]);
  1333. flush(output);
  1334. {$endif}
  1335. end;
  1336. {$endif HAS_MEMORYMANAGER}