heap.inc 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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. var
  330. fTM: TThreadManager; external name 'fCurrentTM';
  331. procedure do_heap_lock;
  332. begin
  333. if Assigned(fTM.EnterCriticalSection) then
  334. fTM.EnterCriticalSection(heap_lock);
  335. end;
  336. procedure do_heap_unlock;
  337. begin
  338. if Assigned(fTM.LeaveCriticalSection) then
  339. fTM.LeaveCriticalSection(heap_lock);
  340. end;
  341. {*****************************************************************************
  342. List adding/removal
  343. *****************************************************************************}
  344. procedure append_to_list_var(pmc: pmemchunk_var); inline;
  345. var
  346. varlist: ppmemchunk_var;
  347. begin
  348. varlist := @pmc^.freelists^.varlist;
  349. pmc^.prev_var := nil;
  350. pmc^.next_var := varlist^;
  351. if varlist^<>nil then
  352. varlist^^.prev_var := pmc;
  353. varlist^ := pmc;
  354. end;
  355. {$ifdef HEAP_DEBUG}
  356. function find_fixed_mc(loc_freelists: pfreelists; chunkindex: ptruint;
  357. pmc: pmemchunk_fixed): boolean;
  358. var
  359. pmc_temp: pmemchunk_fixed;
  360. begin
  361. pmc_temp := loc_freelists^.fixedlists[chunkindex];
  362. while pmc_temp <> nil do
  363. begin
  364. if pmc_temp = pmc then exit(true);
  365. pmc_temp := pmc_temp^.next_fixed;
  366. end;
  367. result := false;
  368. end;
  369. {$endif}
  370. procedure remove_from_list_fixed(pmc: pmemchunk_fixed; fixedlist: ppmemchunk_fixed); inline;
  371. begin
  372. if assigned(pmc^.next_fixed) then
  373. pmc^.next_fixed^.prev_fixed := pmc^.prev_fixed;
  374. if assigned(pmc^.prev_fixed) then
  375. pmc^.prev_fixed^.next_fixed := pmc^.next_fixed
  376. else
  377. fixedlist^ := pmc^.next_fixed;
  378. end;
  379. procedure remove_from_list_var(pmc: pmemchunk_var); inline;
  380. begin
  381. if assigned(pmc^.next_var) then
  382. pmc^.next_var^.prev_var := pmc^.prev_var;
  383. if assigned(pmc^.prev_var) then
  384. pmc^.prev_var^.next_var := pmc^.next_var
  385. else
  386. pmc^.freelists^.varlist := pmc^.next_var;
  387. end;
  388. procedure remove_freed_fixed_chunks(poc: poschunk);
  389. { remove all fixed chunks from the fixed free list, as this os chunk
  390. is going to be used for other purpose }
  391. var
  392. pmc, pmc_end: pmemchunk_fixed;
  393. fixedlist: ppmemchunk_fixed;
  394. chunksize: ptruint;
  395. begin
  396. { exit if this is a var size os chunk, function only applicable to fixed size }
  397. if poc^.used < 0 then
  398. exit;
  399. pmc := pmemchunk_fixed(pointer(poc)+fixedfirstoffset);
  400. chunksize := pmc^.size and fixedsizemask;
  401. pmc_end := pmemchunk_fixed(pointer(poc)+(poc^.size and sizemask)-chunksize);
  402. fixedlist := @poc^.freelists^.fixedlists[chunksize shr blockshift];
  403. repeat
  404. remove_from_list_fixed(pmc, fixedlist);
  405. pmc := pointer(pmc)+chunksize;
  406. until pmc > pmc_end;
  407. end;
  408. procedure free_oschunk(loc_freelists: pfreelists; poc: poschunk);
  409. var
  410. pocsize: ptruint;
  411. begin
  412. remove_freed_fixed_chunks(poc);
  413. if assigned(poc^.prev_any) then
  414. poc^.prev_any^.next_any := poc^.next_any
  415. else
  416. loc_freelists^.oslist_all := poc^.next_any;
  417. if assigned(poc^.next_any) then
  418. poc^.next_any^.prev_any := poc^.prev_any;
  419. pocsize := poc^.size and sizemask;
  420. dec(loc_freelists^.internal_status.currheapsize, pocsize);
  421. SysOSFree(poc, pocsize);
  422. end;
  423. procedure append_to_oslist(poc: poschunk);
  424. var
  425. loc_freelists: pfreelists;
  426. begin
  427. loc_freelists := poc^.freelists;
  428. { check if already on list }
  429. if (poc^.size and ocrecycleflag) <> 0 then
  430. begin
  431. inc(loc_freelists^.oscount);
  432. poc^.size := poc^.size and not ocrecycleflag;
  433. exit;
  434. end;
  435. { decide whether to free block or add to list }
  436. {$ifdef HAS_SYSOSFREE}
  437. if (loc_freelists^.oscount >= MaxKeptOSChunks) or
  438. ((poc^.size and sizemask) > growheapsize2) then
  439. begin
  440. free_oschunk(loc_freelists, poc);
  441. end
  442. else
  443. begin
  444. {$endif}
  445. poc^.next_free := loc_freelists^.oslist;
  446. loc_freelists^.oslist := poc;
  447. inc(loc_freelists^.oscount);
  448. {$ifdef HAS_SYSOSFREE}
  449. end;
  450. {$endif}
  451. end;
  452. procedure append_to_oslist_var(pmc: pmemchunk_var);
  453. var
  454. poc: poschunk;
  455. begin
  456. // block eligable for freeing
  457. poc := pointer(pmc)-varfirstoffset;
  458. remove_from_list_var(pmc);
  459. append_to_oslist(poc);
  460. end;
  461. procedure modify_oschunk_freelists(poc: poschunk; new_freelists: pfreelists);
  462. var
  463. pmcv: pmemchunk_var;
  464. begin
  465. poc^.freelists := new_freelists;
  466. { only if oschunk contains var memchunks, we need additional assignments }
  467. if poc^.used <> -1 then exit;
  468. pmcv := pmemchunk_var(pointer(poc)+varfirstoffset);
  469. repeat
  470. pmcv^.freelists := new_freelists;
  471. if (pmcv^.size and lastblockflag) <> 0 then
  472. break;
  473. pmcv := pmemchunk_var(pointer(pmcv)+(pmcv^.size and sizemask));
  474. until false;
  475. end;
  476. function modify_freelists(loc_freelists, new_freelists: pfreelists): poschunk;
  477. var
  478. poc: poschunk;
  479. begin
  480. poc := loc_freelists^.oslist_all;
  481. if assigned(poc) then
  482. begin
  483. repeat
  484. { fixed and var freelist for orphaned freelists do not need maintenance }
  485. { we assume the heap is not severely fragmented at thread exit }
  486. modify_oschunk_freelists(poc, new_freelists);
  487. if not assigned(poc^.next_any) then
  488. exit(poc);
  489. poc := poc^.next_any;
  490. until false;
  491. end;
  492. modify_freelists := nil;
  493. end;
  494. {*****************************************************************************
  495. Split block
  496. *****************************************************************************}
  497. function split_block(pcurr: pmemchunk_var; size: ptruint): ptruint;
  498. var
  499. pcurr_tmp : pmemchunk_var;
  500. size_flags, oldsize, sizeleft: ptruint;
  501. begin
  502. size_flags := pcurr^.size;
  503. oldsize := size_flags and sizemask;
  504. sizeleft := oldsize-size;
  505. if sizeleft>=sizeof(tmemchunk_var) then
  506. begin
  507. pcurr_tmp := pmemchunk_var(pointer(pcurr)+size);
  508. { update prevsize of block to the right }
  509. if (size_flags and lastblockflag) = 0 then
  510. pmemchunk_var(pointer(pcurr)+oldsize)^.prevsize := sizeleft;
  511. { inherit the lastblockflag }
  512. pcurr_tmp^.size := sizeleft or (size_flags and lastblockflag);
  513. pcurr_tmp^.prevsize := size;
  514. pcurr_tmp^.freelists := pcurr^.freelists;
  515. { the block we return is not the last one anymore (there's now a block after it) }
  516. { decrease size of block to new size }
  517. pcurr^.size := size or (size_flags and (not sizemask and not lastblockflag));
  518. { insert the block in the freelist }
  519. append_to_list_var(pcurr_tmp);
  520. result := size;
  521. end
  522. else
  523. result := oldsize;
  524. end;
  525. {*****************************************************************************
  526. Try concat freerecords
  527. *****************************************************************************}
  528. procedure concat_two_blocks(mc_left, mc_right: pmemchunk_var);
  529. var
  530. mc_tmp : pmemchunk_var;
  531. size_right : ptruint;
  532. begin
  533. // mc_right can't be a fixed size block
  534. if mc_right^.size and fixedsizeflag<>0 then
  535. HandleError(204);
  536. // left block free, concat with right-block
  537. size_right := mc_right^.size and sizemask;
  538. inc(mc_left^.size, size_right);
  539. // if right-block was last block, copy flag
  540. if (mc_right^.size and lastblockflag) <> 0 then
  541. begin
  542. mc_left^.size := mc_left^.size or lastblockflag;
  543. end
  544. else
  545. begin
  546. // there is a block to the right of the right-block, adjust it's prevsize
  547. mc_tmp := pmemchunk_var(pointer(mc_right)+size_right);
  548. mc_tmp^.prevsize := mc_left^.size and sizemask;
  549. end;
  550. // remove right-block from doubly linked list
  551. remove_from_list_var(mc_right);
  552. end;
  553. function try_concat_free_chunk_forward(mc: pmemchunk_var): boolean;
  554. var
  555. mc_tmp : pmemchunk_var;
  556. begin
  557. { try concat forward }
  558. result := false;
  559. if (mc^.size and lastblockflag) = 0 then
  560. begin
  561. mc_tmp := pmemchunk_var(pointer(mc)+(mc^.size and sizemask));
  562. if (mc_tmp^.size and usedflag) = 0 then
  563. begin
  564. // next block free: concat
  565. concat_two_blocks(mc, mc_tmp);
  566. result := true;
  567. end;
  568. end;
  569. end;
  570. function try_concat_free_chunk(mc: pmemchunk_var): pmemchunk_var;
  571. var
  572. mc_tmp : pmemchunk_var;
  573. begin
  574. try_concat_free_chunk_forward(mc);
  575. { try concat backward }
  576. if (mc^.size and firstblockflag) = 0 then
  577. begin
  578. mc_tmp := pmemchunk_var(pointer(mc)-mc^.prevsize);
  579. if (mc_tmp^.size and usedflag) = 0 then
  580. begin
  581. // prior block free: concat
  582. concat_two_blocks(mc_tmp, mc);
  583. mc := mc_tmp;
  584. end;
  585. end;
  586. result := mc;
  587. end;
  588. {*****************************************************************************
  589. Grow Heap
  590. *****************************************************************************}
  591. function find_free_oschunk(loc_freelists: pfreelists;
  592. minsize, maxsize: ptruint; var size: ptruint): poschunk;
  593. var
  594. prev_poc, poc: poschunk;
  595. pocsize: ptruint;
  596. begin
  597. poc := loc_freelists^.oslist;
  598. prev_poc := nil;
  599. while poc <> nil do
  600. begin
  601. if (poc^.size and ocrecycleflag) <> 0 then
  602. begin
  603. { oops! we recycled this chunk; remove it from list }
  604. poc^.size := poc^.size and not ocrecycleflag;
  605. poc := poc^.next_free;
  606. if prev_poc = nil then
  607. loc_freelists^.oslist := poc
  608. else
  609. prev_poc^.next_free := poc;
  610. continue;
  611. end;
  612. pocsize := poc^.size and sizemask;
  613. if (pocsize >= minsize) and
  614. (pocsize <= maxsize) then
  615. begin
  616. size := pocsize;
  617. if prev_poc = nil then
  618. loc_freelists^.oslist := poc^.next_free
  619. else
  620. prev_poc^.next_free := poc^.next_free;
  621. dec(loc_freelists^.oscount);
  622. remove_freed_fixed_chunks(poc);
  623. break;
  624. end;
  625. prev_poc := poc;
  626. poc := poc^.next_free;
  627. end;
  628. result := poc;
  629. end;
  630. function alloc_oschunk(loc_freelists: pfreelists; chunkindex, size: ptruint): pointer;
  631. var
  632. pmc,
  633. pmc_next : pmemchunk_fixed;
  634. pmcv : pmemchunk_var;
  635. poc : poschunk;
  636. minsize,
  637. maxsize,
  638. i : ptruint;
  639. chunksize : ptruint;
  640. status : pfpcheapstatus;
  641. begin
  642. { increase size by size needed for os block header }
  643. minsize := size + varfirstoffset;
  644. { for fixed size chunks we keep offset from os chunk to mem chunk in
  645. upper bits, so maximum os chunk size is 64K on 32bit for fixed size }
  646. if chunkindex<>0 then
  647. maxsize := 1 shl (32-fixedoffsetshift)
  648. else
  649. maxsize := high(ptruint);
  650. { blocks available in freelist? }
  651. poc := find_free_oschunk(loc_freelists, minsize, maxsize, size);
  652. if not assigned(poc) and (assigned(orphaned_freelists.waitfixed)
  653. or assigned(orphaned_freelists.waitvar) or (orphaned_freelists.oscount > 0)) then
  654. begin
  655. do_heap_lock;
  656. finish_waitfixedlist(@orphaned_freelists);
  657. finish_waitvarlist(@orphaned_freelists);
  658. if orphaned_freelists.oscount > 0 then
  659. begin
  660. { blocks available in orphaned freelist ? }
  661. poc := find_free_oschunk(@orphaned_freelists, minsize, maxsize, size);
  662. if assigned(poc) then
  663. begin
  664. { adopt this os chunk }
  665. poc^.freelists := loc_freelists;
  666. if assigned(poc^.prev_any) then
  667. poc^.prev_any^.next_any := poc^.next_any
  668. else
  669. orphaned_freelists.oslist_all := poc^.next_any;
  670. if assigned(poc^.next_any) then
  671. poc^.next_any^.prev_any := poc^.prev_any;
  672. poc^.next_any := loc_freelists^.oslist_all;
  673. if assigned(loc_freelists^.oslist_all) then
  674. loc_freelists^.oslist_all^.prev_any := poc;
  675. poc^.prev_any := nil;
  676. loc_freelists^.oslist_all := poc;
  677. end;
  678. end;
  679. do_heap_unlock;
  680. end;
  681. if poc = nil then
  682. begin
  683. {$ifdef DUMPGROW}
  684. writeln('growheap(',size,') allocating ',(size+sizeof(toschunk)+$ffff) and not $ffff);
  685. DumpBlocks(loc_freelists);
  686. {$endif}
  687. { allocate by 64K size }
  688. size := (size+varfirstoffset+$ffff) and not $ffff;
  689. { allocate smaller blocks for fixed-size chunks }
  690. if chunkindex<>0 then
  691. begin
  692. poc := SysOSAlloc(GrowHeapSizeSmall);
  693. if poc<>nil then
  694. size := GrowHeapSizeSmall;
  695. end
  696. { first try 256K (default) }
  697. else if size<=GrowHeapSize1 then
  698. begin
  699. poc := SysOSAlloc(GrowHeapSize1);
  700. if poc<>nil then
  701. size := GrowHeapSize1;
  702. end
  703. { second try 1024K (default) }
  704. else if size<=GrowHeapSize2 then
  705. begin
  706. poc := SysOSAlloc(GrowHeapSize2);
  707. if poc<>nil then
  708. size := GrowHeapSize2;
  709. end
  710. { else allocate the needed bytes }
  711. else
  712. poc := SysOSAlloc(size);
  713. { try again }
  714. if poc=nil then
  715. begin
  716. poc := SysOSAlloc(size);
  717. if poc=nil then
  718. begin
  719. if ReturnNilIfGrowHeapFails then
  720. begin
  721. result := nil;
  722. exit
  723. end
  724. else
  725. HandleError(203);
  726. end;
  727. end;
  728. poc^.freelists := loc_freelists;
  729. poc^.prev_any := nil;
  730. poc^.next_any := loc_freelists^.oslist_all;
  731. if assigned(loc_freelists^.oslist_all) then
  732. loc_freelists^.oslist_all^.prev_any := poc;
  733. loc_freelists^.oslist_all := poc;
  734. { set the total new heap size }
  735. status := @loc_freelists^.internal_status;
  736. inc(status^.currheapsize, size);
  737. if status^.currheapsize > status^.maxheapsize then
  738. status^.maxheapsize := status^.currheapsize;
  739. end;
  740. { initialize os-block }
  741. poc^.size := size;
  742. if chunkindex<>0 then
  743. begin
  744. poc^.used := 0;
  745. { chop os chunk in fixedsize parts,
  746. maximum of $ffff elements are allowed, otherwise
  747. there will be an overflow }
  748. chunksize := chunkindex shl blockshift;
  749. if size-chunksize>maxsize then
  750. HandleError(204);
  751. { we need to align the user pointers to 8 byte at least for
  752. mmx/sse and doubles on sparc, align to 16 bytes }
  753. i := fixedfirstoffset;
  754. result := pointer(poc) + i;
  755. pmc := pmemchunk_fixed(result);
  756. pmc^.prev_fixed := nil;
  757. repeat
  758. pmc^.size := fixedsizeflag or chunksize or (i shl fixedoffsetshift);
  759. inc(i, chunksize);
  760. if i > size - chunksize then break;
  761. pmc_next := pmemchunk_fixed(pointer(pmc)+chunksize);
  762. pmc^.next_fixed := pmc_next;
  763. pmc_next^.prev_fixed := pmc;
  764. pmc := pmc_next;
  765. until false;
  766. pmc_next := loc_freelists^.fixedlists[chunkindex];
  767. pmc^.next_fixed := pmc_next;
  768. if pmc_next<>nil then
  769. pmc_next^.prev_fixed := pmc;
  770. loc_freelists^.fixedlists[chunkindex] := pmemchunk_fixed(result);
  771. end
  772. else
  773. begin
  774. poc^.used := -1;
  775. { we need to align the user pointers to 8 byte at least for
  776. mmx/sse and doubles on sparc, align to 16 bytes }
  777. result := pointer(poc)+varfirstoffset;
  778. pmcv := pmemchunk_var(result);
  779. pmcv^.size := ((size-varfirstoffset) and sizemask) or (firstblockflag or lastblockflag);
  780. pmcv^.prevsize := 0;
  781. pmcv^.freelists := loc_freelists;
  782. append_to_list_var(pmcv);
  783. end;
  784. end;
  785. {*****************************************************************************
  786. SysGetMem
  787. *****************************************************************************}
  788. function SysGetMem_Fixed(chunksize: ptruint): pointer;
  789. var
  790. pmc, pmc_next: pmemchunk_fixed;
  791. poc: poschunk;
  792. chunkindex: ptruint;
  793. loc_freelists: pfreelists;
  794. begin
  795. { try to find a block in one of the freelists per size }
  796. chunkindex := chunksize shr blockshift;
  797. loc_freelists := @freelists;
  798. pmc := loc_freelists^.fixedlists[chunkindex];
  799. { no free blocks ? }
  800. if assigned(pmc) then
  801. begin
  802. { remove oschunk from free list in case we recycle it }
  803. poc := poschunk(pointer(pmc) - (pmc^.size shr fixedoffsetshift));
  804. if poc^.used = 0 then
  805. begin
  806. poc^.size := poc^.size or ocrecycleflag;
  807. dec(loc_freelists^.oscount);
  808. end;
  809. end
  810. else if try_finish_waitfixedlist(loc_freelists) then
  811. { freed some to-be freed chunks, retry allocation }
  812. exit(SysGetMem_Fixed(chunksize))
  813. else
  814. begin
  815. pmc := alloc_oschunk(loc_freelists, chunkindex, chunksize);
  816. if not assigned(pmc) then
  817. exit(nil);
  818. poc := poschunk(pointer(pmc)-fixedfirstoffset);
  819. end;
  820. { get a pointer to the block we should return }
  821. result := pointer(pmc)+sizeof(tmemchunk_fixed_hdr);
  822. { update freelist }
  823. pmc_next := pmc^.next_fixed;
  824. loc_freelists^.fixedlists[chunkindex] := pmc_next;
  825. if assigned(pmc_next) then
  826. pmc_next^.prev_fixed := nil;
  827. inc(poc^.used);
  828. { statistics }
  829. with loc_freelists^.internal_status do
  830. begin
  831. inc(currheapused, chunksize);
  832. if currheapused > maxheapused then
  833. begin
  834. maxheapused := currheapused;
  835. {$ifdef DUMP_MEM_USAGE}
  836. maxsizeusage := sizeusage;
  837. {$endif}
  838. end;
  839. end;
  840. end;
  841. function SysGetMem_Var(size: ptruint): pointer;
  842. var
  843. pcurr : pmemchunk_var;
  844. pbest : pmemchunk_var;
  845. loc_freelists : pfreelists;
  846. iter : cardinal;
  847. begin
  848. result:=nil;
  849. { free pending items }
  850. loc_freelists := @freelists;
  851. try_finish_waitvarlist(loc_freelists);
  852. pbest := nil;
  853. pcurr := loc_freelists^.varlist;
  854. iter := high(iter);
  855. while assigned(pcurr) and (iter>0) do
  856. begin
  857. if (pcurr^.size>size) then
  858. begin
  859. if not assigned(pbest) or (pcurr^.size<pbest^.size) then
  860. begin
  861. pbest := pcurr;
  862. if pcurr^.size = size then
  863. break;
  864. iter := matcheffort;
  865. end;
  866. end;
  867. pcurr := pcurr^.next_var;
  868. dec(iter);
  869. end;
  870. pcurr := pbest;
  871. if not assigned(pcurr) then
  872. begin
  873. // all os-chunks full, allocate a new one
  874. pcurr := alloc_oschunk(loc_freelists, 0, size);
  875. if not assigned(pcurr) then
  876. exit;
  877. end;
  878. { get pointer of the block we should return }
  879. result := pointer(pcurr)+sizeof(tmemchunk_var_hdr);
  880. { remove the current block from the freelist }
  881. remove_from_list_var(pcurr);
  882. { create the left over freelist block, if at least 16 bytes are free }
  883. size := split_block(pcurr, size);
  884. { flag block as used }
  885. pcurr^.size := pcurr^.size or usedflag;
  886. { statistics }
  887. with loc_freelists^.internal_status do
  888. begin
  889. inc(currheapused, size);
  890. if currheapused > maxheapused then
  891. begin
  892. maxheapused := currheapused;
  893. {$ifdef DUMP_MEM_USAGE}
  894. maxsizeusage := sizeusage;
  895. {$endif}
  896. end;
  897. end;
  898. end;
  899. function SysGetMem(size : ptruint):pointer;
  900. begin
  901. { Something to allocate ? }
  902. if size=0 then
  903. { we always need to allocate something, using heapend is not possible,
  904. because heappend can be changed by growheap (PFV) }
  905. size := 1;
  906. { calc to multiple of 16 after adding the needed bytes for memchunk header }
  907. if size <= (maxblocksize - sizeof(tmemchunk_fixed_hdr)) then
  908. begin
  909. size := (size+(sizeof(tmemchunk_fixed_hdr)+(blocksize-1))) and fixedsizemask;
  910. result := sysgetmem_fixed(size);
  911. end
  912. else
  913. begin
  914. size := (size+(sizeof(tmemchunk_var_hdr)+(blocksize-1))) and sizemask;
  915. result := sysgetmem_var(size);
  916. end;
  917. {$ifdef DUMP_MEM_USAGE}
  918. size := sysmemsize(result);
  919. if size > sizeusagesize then
  920. inc(sizeusage[sizeusageindex])
  921. else
  922. inc(sizeusage[size shr sizeusageshift]);
  923. {$endif}
  924. end;
  925. {*****************************************************************************
  926. SysFreeMem
  927. *****************************************************************************}
  928. procedure waitfree_fixed(pmc: pmemchunk_fixed; poc: poschunk);
  929. begin
  930. do_heap_lock;
  931. pmc^.next_fixed := poc^.freelists^.waitfixed;
  932. poc^.freelists^.waitfixed := pmc;
  933. do_heap_unlock;
  934. end;
  935. procedure waitfree_var(pmcv: pmemchunk_var);
  936. begin
  937. do_heap_lock;
  938. pmcv^.next_var := pmcv^.freelists^.waitvar;
  939. pmcv^.freelists^.waitvar := pmcv;
  940. do_heap_unlock;
  941. end;
  942. function SysFreeMem_Fixed(loc_freelists: pfreelists; pmc: pmemchunk_fixed): ptruint;
  943. var
  944. chunkindex,
  945. chunksize: ptruint;
  946. poc: poschunk;
  947. pmc_next: pmemchunk_fixed;
  948. begin
  949. poc := poschunk(pointer(pmc)-(pmc^.size shr fixedoffsetshift));
  950. chunksize := pmc^.size and fixedsizemask;
  951. if loc_freelists <> poc^.freelists then
  952. begin
  953. { deallocated in wrong thread! add to to-be-freed list of correct thread }
  954. waitfree_fixed(pmc, poc);
  955. exit(chunksize);
  956. end;
  957. dec(loc_freelists^.internal_status.currheapused, chunksize);
  958. { insert the block in it's freelist }
  959. chunkindex := chunksize shr blockshift;
  960. pmc_next := loc_freelists^.fixedlists[chunkindex];
  961. pmc^.prev_fixed := nil;
  962. pmc^.next_fixed := pmc_next;
  963. if assigned(pmc_next) then
  964. pmc_next^.prev_fixed := pmc;
  965. loc_freelists^.fixedlists[chunkindex] := pmc;
  966. { decrease used blocks count }
  967. dec(poc^.used);
  968. if poc^.used <= 0 then
  969. begin
  970. { decrease used blocks count }
  971. if poc^.used<0 then
  972. HandleError(204);
  973. { osblock can be freed? }
  974. append_to_oslist(poc);
  975. end;
  976. result := chunksize;
  977. end;
  978. function SysFreeMem_Var(loc_freelists: pfreelists; pmcv: pmemchunk_var): ptruint;
  979. var
  980. chunksize: ptruint;
  981. begin
  982. chunksize := pmcv^.size and sizemask;
  983. if loc_freelists <> pmcv^.freelists then
  984. begin
  985. { deallocated in wrong thread! add to to-be-freed list of correct thread }
  986. waitfree_var(pmcv);
  987. exit(chunksize);
  988. end;
  989. dec(loc_freelists^.internal_status.currheapused, chunksize);
  990. { insert the block in it's freelist }
  991. pmcv^.size := pmcv^.size and (not usedflag);
  992. append_to_list_var(pmcv);
  993. pmcv := try_concat_free_chunk(pmcv);
  994. if (pmcv^.size and (firstblockflag or lastblockflag)) = (firstblockflag or lastblockflag) then
  995. append_to_oslist_var(pmcv);
  996. result := chunksize;
  997. end;
  998. function SysFreeMem(p: pointer): ptruint;
  999. var
  1000. pmc: pmemchunk_fixed;
  1001. loc_freelists: pfreelists;
  1002. {$ifdef DUMP_MEM_USAGE}
  1003. size: sizeint;
  1004. {$endif}
  1005. begin
  1006. if p=nil then
  1007. begin
  1008. result:=0;
  1009. exit;
  1010. end;
  1011. {$ifdef DUMP_MEM_USAGE}
  1012. size := sysmemsize(p);
  1013. if size > sizeusagesize then
  1014. dec(sizeusage[sizeusageindex])
  1015. else
  1016. dec(sizeusage[size shr sizeusageshift]);
  1017. {$endif}
  1018. loc_freelists := @freelists;
  1019. pmc := pmemchunk_fixed(p-sizeof(tmemchunk_fixed_hdr));
  1020. { check if this is a fixed- or var-sized chunk }
  1021. if (pmc^.size and fixedsizeflag) = 0 then
  1022. result := sysfreemem_var(loc_freelists, pmemchunk_var(p-sizeof(tmemchunk_var_hdr)))
  1023. else
  1024. result := sysfreemem_fixed(loc_freelists, pmc);
  1025. end;
  1026. procedure finish_waitfixedlist(loc_freelists: pfreelists);
  1027. { free to-be-freed chunks, return whether we freed anything }
  1028. var
  1029. pmc: pmemchunk_fixed;
  1030. begin
  1031. while loc_freelists^.waitfixed <> nil do
  1032. begin
  1033. { keep next_fixed, might be destroyed }
  1034. pmc := loc_freelists^.waitfixed;
  1035. loc_freelists^.waitfixed := pmc^.next_fixed;
  1036. SysFreeMem_Fixed(loc_freelists, pmc);
  1037. end;
  1038. end;
  1039. function try_finish_waitfixedlist(loc_freelists: pfreelists): boolean;
  1040. begin
  1041. if loc_freelists^.waitfixed = nil then
  1042. exit(false);
  1043. do_heap_lock;
  1044. finish_waitfixedlist(loc_freelists);
  1045. do_heap_unlock;
  1046. result := true;
  1047. end;
  1048. procedure finish_waitvarlist(loc_freelists: pfreelists);
  1049. { free to-be-freed chunks, return whether we freed anything }
  1050. var
  1051. pmcv: pmemchunk_var;
  1052. begin
  1053. while loc_freelists^.waitvar <> nil do
  1054. begin
  1055. { keep next_var, might be destroyed }
  1056. pmcv := loc_freelists^.waitvar;
  1057. loc_freelists^.waitvar := pmcv^.next_var;
  1058. SysFreeMem_Var(loc_freelists, pmcv);
  1059. end;
  1060. end;
  1061. procedure try_finish_waitvarlist(loc_freelists: pfreelists);
  1062. begin
  1063. if loc_freelists^.waitvar = nil then
  1064. exit;
  1065. do_heap_lock;
  1066. finish_waitvarlist(loc_freelists);
  1067. do_heap_unlock;
  1068. end;
  1069. {*****************************************************************************
  1070. SysFreeMemSize
  1071. *****************************************************************************}
  1072. Function SysFreeMemSize(p: pointer; size: ptruint):ptruint;
  1073. begin
  1074. if size=0 then
  1075. exit(0);
  1076. { can't free partial blocks, ignore size }
  1077. result := SysFreeMem(p);
  1078. end;
  1079. {*****************************************************************************
  1080. SysMemSize
  1081. *****************************************************************************}
  1082. function SysMemSize(p: pointer): ptruint;
  1083. begin
  1084. result := pmemchunk_fixed(pointer(p)-sizeof(tmemchunk_fixed_hdr))^.size;
  1085. if (result and fixedsizeflag) = 0 then
  1086. begin
  1087. result := result and sizemask;
  1088. dec(result, sizeof(tmemchunk_var_hdr));
  1089. end
  1090. else
  1091. begin
  1092. result := result and fixedsizemask;
  1093. dec(result, sizeof(tmemchunk_fixed_hdr));
  1094. end;
  1095. end;
  1096. {*****************************************************************************
  1097. SysAllocMem
  1098. *****************************************************************************}
  1099. function SysAllocMem(size: ptruint): pointer;
  1100. begin
  1101. result := MemoryManager.GetMem(size);
  1102. if result<>nil then
  1103. FillChar(result^,MemoryManager.MemSize(result),0);
  1104. end;
  1105. {*****************************************************************************
  1106. SysResizeMem
  1107. *****************************************************************************}
  1108. function SysTryResizeMem(var p: pointer; size: ptruint): boolean;
  1109. var
  1110. chunksize,
  1111. oldsize,
  1112. currsize : ptruint;
  1113. pcurr : pmemchunk_var;
  1114. begin
  1115. SysTryResizeMem := false;
  1116. { fix p to point to the heaprecord }
  1117. chunksize := pmemchunk_fixed(p-sizeof(tmemchunk_fixed_hdr))^.size;
  1118. { handle fixed memchuncks separate. Only allow resizes when the
  1119. new size fits in the same block }
  1120. if (chunksize and fixedsizeflag) <> 0 then
  1121. begin
  1122. currsize := chunksize and fixedsizemask;
  1123. { 1. Resizing to smaller sizes will never allocate a new block. We just keep the current block. This
  1124. is needed for the expectations that resizing to a small block will not move the contents of
  1125. a memory block
  1126. 2. For resizing to greater size first check if the size fits in the fixed block range to prevent
  1127. "truncating" the size by the fixedsizemask }
  1128. if ((size <= (maxblocksize - sizeof(tmemchunk_fixed_hdr))) and
  1129. ((size+sizeof(tmemchunk_fixed_hdr)+(blocksize-1)) and sizemask <= currsize)) then
  1130. begin
  1131. systryresizemem:=true;
  1132. exit;
  1133. end;
  1134. { we need to allocate a new fixed or var memchunck }
  1135. exit;
  1136. end;
  1137. { var memchunk }
  1138. { do not fragment the heap with small shrinked blocks }
  1139. { also solves problem with var sized chunks smaller than sizeof(tmemchunk_var) }
  1140. if size < maxblocksize div 2 then
  1141. exit(false);
  1142. currsize := chunksize and sizemask;
  1143. size := (size+sizeof(tmemchunk_var_hdr)+(blocksize-1)) and sizemask;
  1144. { is the allocated block still correct? }
  1145. if (currsize>=size) and (size>(currsize-blocksize)) then
  1146. begin
  1147. SysTryResizeMem := true;
  1148. exit;
  1149. end;
  1150. { get pointer to block }
  1151. pcurr := pmemchunk_var(pointer(p)-sizeof(tmemchunk_var_hdr));
  1152. oldsize := currsize;
  1153. { do we need to allocate more memory ? }
  1154. if try_concat_free_chunk_forward(pcurr) then
  1155. currsize := pcurr^.size and sizemask;
  1156. if size>currsize then
  1157. begin
  1158. { the size is bigger than the previous size, we need to allocate more mem
  1159. but we could not concatenate with next block or not big enough }
  1160. exit;
  1161. end
  1162. else
  1163. { is the size smaller then we can adjust the block to that size and insert
  1164. the other part into the freelist }
  1165. if currsize>size then
  1166. currsize := split_block(pcurr, size);
  1167. with pcurr^.freelists^.internal_status do
  1168. begin
  1169. inc(currheapused, currsize-oldsize);
  1170. if currheapused > maxheapused then
  1171. maxheapused := currheapused;
  1172. end;
  1173. SysTryResizeMem := true;
  1174. end;
  1175. {*****************************************************************************
  1176. SysResizeMem
  1177. *****************************************************************************}
  1178. function SysReAllocMem(var p: pointer; size: ptruint):pointer;
  1179. var
  1180. newsize,
  1181. oldsize,
  1182. minsize : ptruint;
  1183. p2 : pointer;
  1184. begin
  1185. { Free block? }
  1186. if size=0 then
  1187. begin
  1188. if p<>nil then
  1189. begin
  1190. MemoryManager.FreeMem(p);
  1191. p := nil;
  1192. end;
  1193. end
  1194. else
  1195. { Allocate a new block? }
  1196. if p=nil then
  1197. begin
  1198. p := MemoryManager.GetMem(size);
  1199. end
  1200. else
  1201. begin
  1202. { Resize block }
  1203. {$ifdef DUMP_MEM_USAGE}
  1204. oldsize:=SysMemSize(p);
  1205. {$endif}
  1206. if not SysTryResizeMem(p,size) then
  1207. begin
  1208. oldsize:=MemoryManager.MemSize(p);
  1209. { Grow with bigger steps to prevent the need for
  1210. multiple getmem/freemem calls for fixed blocks. It might cost a bit
  1211. of extra memory, but in most cases a reallocmem is done multiple times. }
  1212. if oldsize<maxblocksize then
  1213. begin
  1214. newsize:=oldsize*2+blocksize;
  1215. if size>newsize then
  1216. newsize:=size;
  1217. end
  1218. else
  1219. newsize:=size;
  1220. { calc size of data to move }
  1221. minsize:=oldsize;
  1222. if newsize < minsize then
  1223. minsize := newsize;
  1224. p2 := MemoryManager.GetMem(newsize);
  1225. if p2<>nil then
  1226. Move(p^,p2^,minsize);
  1227. MemoryManager.FreeMem(p);
  1228. p := p2;
  1229. {$ifdef DUMP_MEM_USAGE}
  1230. end else begin
  1231. size := sysmemsize(p);
  1232. if size <> oldsize then
  1233. begin
  1234. if oldsize > sizeusagesize then
  1235. dec(sizeusage[sizeusageindex])
  1236. else if oldsize >= 0 then
  1237. dec(sizeusage[oldsize shr sizeusageshift]);
  1238. if size > sizeusagesize then
  1239. inc(sizeusage[sizeusageindex])
  1240. else if size >= 0 then
  1241. inc(sizeusage[size shr sizeusageshift]);
  1242. end;
  1243. {$endif}
  1244. end;
  1245. end;
  1246. SysReAllocMem := p;
  1247. end;
  1248. {$endif HAS_MEMORYMANAGER}
  1249. {$ifndef HAS_MEMORYMANAGER}
  1250. {*****************************************************************************
  1251. InitHeap
  1252. *****************************************************************************}
  1253. { This function will initialize the Heap manager and need to be called from
  1254. the initialization of the system unit }
  1255. procedure InitHeapThread;
  1256. var
  1257. loc_freelists: pfreelists;
  1258. begin
  1259. loc_freelists := @freelists;
  1260. fillchar(loc_freelists^,sizeof(tfreelists),0);
  1261. {$ifdef DUMP_MEM_USAGE}
  1262. fillchar(sizeusage,sizeof(sizeusage),0);
  1263. fillchar(maxsizeusage,sizeof(sizeusage),0);
  1264. {$endif}
  1265. end;
  1266. procedure InitHeap;
  1267. var
  1268. loc_freelists: pfreelists;
  1269. begin
  1270. { we cannot initialize the locks here yet, thread support is
  1271. not loaded yet }
  1272. loc_freelists := @freelists;
  1273. fillchar(loc_freelists^,sizeof(tfreelists),0);
  1274. fillchar(orphaned_freelists,sizeof(orphaned_freelists),0);
  1275. end;
  1276. procedure RelocateHeap;
  1277. var
  1278. loc_freelists: pfreelists;
  1279. begin
  1280. { this function should be called in main thread context }
  1281. loc_freelists := @freelists;
  1282. main_relo_freelists := loc_freelists;
  1283. initcriticalsection(heap_lock);
  1284. modify_freelists(loc_freelists, main_relo_freelists);
  1285. if MemoryManager.RelocateHeap <> nil then
  1286. MemoryManager.RelocateHeap();
  1287. end;
  1288. procedure FinalizeHeap;
  1289. var
  1290. poc, poc_next: poschunk;
  1291. loc_freelists: pfreelists;
  1292. {$ifdef DUMP_MEM_USAGE}
  1293. i : longint;
  1294. {$endif}
  1295. begin
  1296. loc_freelists := @freelists;
  1297. if main_relo_freelists <> nil then
  1298. begin
  1299. do_heap_lock;
  1300. finish_waitfixedlist(loc_freelists);
  1301. finish_waitvarlist(loc_freelists);
  1302. {$ifdef HAS_SYSOSFREE}
  1303. end;
  1304. poc := loc_freelists^.oslist;
  1305. while assigned(poc) do
  1306. begin
  1307. poc_next := poc^.next_free;
  1308. { check if this os chunk was 'recycled' i.e. taken in use again }
  1309. if (poc^.size and ocrecycleflag) = 0 then
  1310. free_oschunk(loc_freelists, poc)
  1311. else
  1312. poc^.size := poc^.size and not ocrecycleflag;
  1313. poc := poc_next;
  1314. end;
  1315. loc_freelists^.oslist := nil;
  1316. loc_freelists^.oscount := 0;
  1317. if main_relo_freelists <> nil then
  1318. begin
  1319. {$endif HAS_SYSOSFREE}
  1320. if main_relo_freelists <> loc_freelists then
  1321. begin
  1322. poc := modify_freelists(loc_freelists, @orphaned_freelists);
  1323. if assigned(poc) then
  1324. begin
  1325. poc^.next_any := orphaned_freelists.oslist_all;
  1326. if assigned(orphaned_freelists.oslist_all) then
  1327. orphaned_freelists.oslist_all^.prev_any := poc;
  1328. orphaned_freelists.oslist_all := loc_freelists^.oslist_all;
  1329. end;
  1330. end;
  1331. do_heap_unlock;
  1332. if (main_relo_freelists = loc_freelists) and Assigned(fTM.DoneCriticalSection) then
  1333. fTM.DoneCriticalSection(heap_lock);
  1334. end;
  1335. {$ifdef SHOW_MEM_USAGE}
  1336. writeln('Max heap used/size: ', loc_freelists^.internal_status.maxheapused, '/',
  1337. loc_freelists^.internal_status.maxheapsize);
  1338. flush(output);
  1339. {$endif}
  1340. {$ifdef DUMP_MEM_USAGE}
  1341. for i := 0 to sizeusageindex-1 do
  1342. if maxsizeusage[i] <> 0 then
  1343. writeln('size ', i shl sizeusageshift, ' usage ', maxsizeusage[i]);
  1344. writeln('size >', sizeusagesize, ' usage ', maxsizeusage[sizeusageindex]);
  1345. flush(output);
  1346. {$endif}
  1347. end;
  1348. {$endif HAS_MEMORYMANAGER}