heap.inc 48 KB

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