heap.inc 49 KB

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