nedmalloc.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. #ifdef NEDMALLOC_ENABLED
  2. /* Alternative malloc implementation for multiple threads without
  3. lock contention based on dlmalloc. (C) 2005-2009 Niall Douglas
  4. Boost Software License - Version 1.0 - August 17th, 2003
  5. Permission is hereby granted, free of charge, to any person or organization
  6. obtaining a copy of the software and accompanying documentation covered by
  7. this license (the "Software") to use, reproduce, display, distribute,
  8. execute, and transmit the Software, and to prepare derivative works of the
  9. Software, and to permit third-parties to whom the Software is furnished to
  10. do so, all subject to the following:
  11. The copyright notices in the Software and this entire statement, including
  12. the above license grant, this restriction and the following disclaimer,
  13. must be included in all copies of the Software, in whole or in part, and
  14. all derivative works of the Software, unless such copies or derivative
  15. works are solely in the form of machine-executable object code generated by
  16. a source language processor.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  20. SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  21. FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  22. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  23. DEALINGS IN THE SOFTWARE.
  24. */
  25. #ifdef _MSC_VER
  26. /* Enable full aliasing on MSVC */
  27. /*#pragma optimize("a", on)*/
  28. #pragma warning(push)
  29. #pragma warning(disable:4100) /* unreferenced formal parameter */
  30. #pragma warning(disable:4127) /* conditional expression is constant */
  31. #pragma warning(disable:4706) /* assignment within conditional expression */
  32. #endif
  33. /*#define ENABLE_TOLERANT_NEDMALLOC 1*/
  34. /*#define ENABLE_FAST_HEAP_DETECTION 1*/
  35. /*#define NEDMALLOC_DEBUG 1*/
  36. /*#define FULLSANITYCHECKS*/
  37. /* If link time code generation is on, don't force or prevent inlining */
  38. #if defined(_MSC_VER) && defined(NEDMALLOC_DLL_EXPORTS)
  39. #define FORCEINLINE
  40. #define NOINLINE
  41. #endif
  42. #include "nedmalloc.h"
  43. #ifdef WIN32
  44. #include <malloc.h>
  45. #include <stddef.h>
  46. #endif
  47. #if USE_ALLOCATOR==1
  48. #define MSPACES 1
  49. #define ONLY_MSPACES 1
  50. #endif
  51. #define USE_DL_PREFIX 1
  52. #ifndef USE_LOCKS
  53. #define USE_LOCKS 1
  54. #endif
  55. #define FOOTERS 1 /* Need to enable footers so frees lock the right mspace */
  56. #ifndef NEDMALLOC_DEBUG
  57. #if defined(DEBUG) || defined(_DEBUG)
  58. #define NEDMALLOC_DEBUG 1
  59. #else
  60. #define NEDMALLOC_DEBUG 0
  61. #endif
  62. #endif
  63. /* We need to consistently define DEBUG=0|1, _DEBUG and NDEBUG for dlmalloc */
  64. #undef DEBUG
  65. #undef _DEBUG
  66. #if NEDMALLOC_DEBUG
  67. #define _DEBUG
  68. #define DEBUG 1
  69. #else
  70. #define DEBUG 0
  71. #endif
  72. #ifdef NDEBUG /* Disable assert checking on release builds */
  73. #undef DEBUG
  74. #undef _DEBUG
  75. #endif
  76. /* The default of 64Kb means we spend too much time kernel-side */
  77. #ifndef DEFAULT_GRANULARITY
  78. #define DEFAULT_GRANULARITY (1*1024*1024)
  79. #if DEBUG
  80. #define DEFAULT_GRANULARITY_ALIGNED
  81. #endif
  82. #endif
  83. /*#define USE_SPIN_LOCKS 0*/
  84. #include "malloc.c.h"
  85. #ifdef NDEBUG /* Disable assert checking on release builds */
  86. #undef DEBUG
  87. #elif !NEDMALLOC_DEBUG
  88. #ifdef __GNUC__
  89. #warning DEBUG is defined so allocator will run with assert checking! Define NDEBUG to run at full speed.
  90. #elif defined(_MSC_VER)
  91. #pragma message(__FILE__ ": WARNING: DEBUG is defined so allocator will run with assert checking! Define NDEBUG to run at full speed.")
  92. #endif
  93. #endif
  94. /* The maximum concurrent threads in a pool possible */
  95. #ifndef MAXTHREADSINPOOL
  96. #define MAXTHREADSINPOOL 16
  97. #endif
  98. /* The maximum number of threadcaches which can be allocated */
  99. #ifndef THREADCACHEMAXCACHES
  100. #define THREADCACHEMAXCACHES 256
  101. #endif
  102. /* The maximum size to be allocated from the thread cache */
  103. #ifndef THREADCACHEMAX
  104. #define THREADCACHEMAX 8192
  105. #endif
  106. #if 0
  107. /* The number of cache entries for finer grained bins. This is (topbitpos(THREADCACHEMAX)-4)*2 */
  108. #define THREADCACHEMAXBINS ((13-4)*2)
  109. #else
  110. /* The number of cache entries. This is (topbitpos(THREADCACHEMAX)-4) */
  111. #define THREADCACHEMAXBINS (13-4)
  112. #endif
  113. /* Point at which the free space in a thread cache is garbage collected */
  114. #ifndef THREADCACHEMAXFREESPACE
  115. #define THREADCACHEMAXFREESPACE (512*1024)
  116. #endif
  117. #ifdef WIN32
  118. #define TLSVAR DWORD
  119. #define TLSALLOC(k) (*(k)=TlsAlloc(), TLS_OUT_OF_INDEXES==*(k))
  120. #define TLSFREE(k) (!TlsFree(k))
  121. #define TLSGET(k) TlsGetValue(k)
  122. #define TLSSET(k, a) (!TlsSetValue(k, a))
  123. #ifdef DEBUG
  124. static LPVOID ChkedTlsGetValue(DWORD idx)
  125. {
  126. LPVOID ret=TlsGetValue(idx);
  127. assert(S_OK==GetLastError());
  128. return ret;
  129. }
  130. #undef TLSGET
  131. #define TLSGET(k) ChkedTlsGetValue(k)
  132. #endif
  133. #else
  134. #define TLSVAR pthread_key_t
  135. #define TLSALLOC(k) pthread_key_create(k, 0)
  136. #define TLSFREE(k) pthread_key_delete(k)
  137. #define TLSGET(k) pthread_getspecific(k)
  138. #define TLSSET(k, a) pthread_setspecific(k, a)
  139. #endif
  140. #if defined(__cplusplus)
  141. #if !defined(NO_NED_NAMESPACE)
  142. namespace nedalloc {
  143. #else
  144. extern "C" {
  145. #endif
  146. #endif
  147. #if USE_ALLOCATOR==0
  148. static void *unsupported_operation(const char *opname) THROWSPEC
  149. {
  150. fprintf(stderr, "nedmalloc: The operation %s is not supported under this build configuration\n", opname);
  151. abort();
  152. return 0;
  153. }
  154. static size_t mspacecounter=(size_t) 0xdeadbeef;
  155. #endif
  156. #ifndef ENABLE_FAST_HEAP_DETECTION
  157. static void *RESTRICT leastusedaddress;
  158. static size_t largestusedblock;
  159. #endif
  160. static FORCEINLINE void *CallMalloc(void *RESTRICT mspace, size_t size, size_t alignment) THROWSPEC
  161. {
  162. void *RESTRICT ret=0;
  163. size_t _alignment=alignment;
  164. #if USE_MAGIC_HEADERS
  165. size_t *_ret=0;
  166. size+=alignment+3*sizeof(size_t);
  167. _alignment=0;
  168. #endif
  169. #if USE_ALLOCATOR==0
  170. ret=_alignment ?
  171. #ifdef _MSC_VER
  172. /* This is the MSVCRT equivalent */
  173. _aligned_malloc(size, _alignment)
  174. #elif defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)
  175. /* This is the glibc/ptmalloc2/dlmalloc/BSD libc equivalent. */
  176. memalign(_alignment, size)
  177. #else
  178. #error Cannot aligned allocate with the memory allocator of an unknown system!
  179. #endif
  180. : malloc(size);
  181. #elif USE_ALLOCATOR==1
  182. ret=_alignment ? mspace_memalign((mstate) mspace, _alignment, size) : mspace_malloc((mstate) mspace, size);
  183. #ifndef ENABLE_FAST_HEAP_DETECTION
  184. if(ret)
  185. {
  186. size_t truesize=chunksize(mem2chunk(ret));
  187. if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
  188. if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
  189. }
  190. #endif
  191. #endif
  192. if(!ret) return 0;
  193. #if USE_MAGIC_HEADERS
  194. _ret=(size_t *) ret;
  195. ret=(void *)(_ret+3);
  196. if(alignment) ret=(void *)(((size_t) ret+alignment-1)&~(alignment-1));
  197. for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *)"NEDMALOC";
  198. _ret[0]=(size_t) mspace;
  199. _ret[1]=size-3*sizeof(size_t);
  200. #endif
  201. return ret;
  202. }
  203. static FORCEINLINE void *CallCalloc(void *RESTRICT mspace, size_t size, size_t alignment) THROWSPEC
  204. {
  205. void *RESTRICT ret=0;
  206. #if USE_MAGIC_HEADERS
  207. size_t *_ret=0;
  208. size+=alignment+3*sizeof(size_t);
  209. #endif
  210. #if USE_ALLOCATOR==0
  211. ret=calloc(1, size);
  212. #elif USE_ALLOCATOR==1
  213. ret=mspace_calloc((mstate) mspace, 1, size);
  214. #ifndef ENABLE_FAST_HEAP_DETECTION
  215. if(ret)
  216. {
  217. size_t truesize=chunksize(mem2chunk(ret));
  218. if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
  219. if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
  220. }
  221. #endif
  222. #endif
  223. if(!ret) return 0;
  224. #if USE_MAGIC_HEADERS
  225. _ret=(size_t *) ret;
  226. ret=(void *)(_ret+3);
  227. if(alignment) ret=(void *)(((size_t) ret+alignment-1)&~(alignment-1));
  228. for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *) "NEDMALOC";
  229. _ret[0]=(size_t) mspace;
  230. _ret[1]=size-3*sizeof(size_t);
  231. #endif
  232. return ret;
  233. }
  234. static FORCEINLINE void *CallRealloc(void *RESTRICT mspace, void *RESTRICT mem, int isforeign, size_t oldsize, size_t newsize) THROWSPEC
  235. {
  236. void *RESTRICT ret=0;
  237. #if USE_MAGIC_HEADERS
  238. mstate oldmspace=0;
  239. size_t *_ret=0, *_mem=(size_t *) mem-3;
  240. #endif
  241. if(isforeign)
  242. { /* Transfer */
  243. #if USE_MAGIC_HEADERS
  244. assert(_mem[0]!=*(size_t *) "NEDMALOC");
  245. #endif
  246. if((ret=CallMalloc(mspace, newsize, 0)))
  247. {
  248. #if defined(DEBUG)
  249. printf("*** nedmalloc frees system allocated block %p\n", mem);
  250. #endif
  251. memcpy(ret, mem, oldsize<newsize ? oldsize : newsize);
  252. free(mem);
  253. }
  254. return ret;
  255. }
  256. #if USE_MAGIC_HEADERS
  257. assert(_mem[0]==*(size_t *) "NEDMALOC");
  258. newsize+=3*sizeof(size_t);
  259. oldmspace=(mstate) _mem[1];
  260. assert(oldsize>=_mem[2]);
  261. for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
  262. mem=(void *)(++_mem);
  263. #endif
  264. #if USE_ALLOCATOR==0
  265. ret=realloc(mem, newsize);
  266. #elif USE_ALLOCATOR==1
  267. ret=mspace_realloc((mstate) mspace, mem, newsize);
  268. #ifndef ENABLE_FAST_HEAP_DETECTION
  269. if(ret)
  270. {
  271. size_t truesize=chunksize(mem2chunk(ret));
  272. if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
  273. }
  274. #endif
  275. #endif
  276. if(!ret)
  277. { /* Put it back the way it was */
  278. #if USE_MAGIC_HEADERS
  279. for(; *_mem==0; *_mem++=*(size_t *) "NEDMALOC");
  280. #endif
  281. return 0;
  282. }
  283. #if USE_MAGIC_HEADERS
  284. _ret=(size_t *) ret;
  285. ret=(void *)(_ret+3);
  286. for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *) "NEDMALOC";
  287. _ret[0]=(size_t) mspace;
  288. _ret[1]=newsize-3*sizeof(size_t);
  289. #endif
  290. return ret;
  291. }
  292. static FORCEINLINE void CallFree(void *RESTRICT mspace, void *RESTRICT mem, int isforeign) THROWSPEC
  293. {
  294. #if USE_MAGIC_HEADERS
  295. mstate oldmspace=0;
  296. size_t *_mem=(size_t *) mem-3, oldsize=0;
  297. #endif
  298. if(isforeign)
  299. {
  300. #if USE_MAGIC_HEADERS
  301. assert(_mem[0]!=*(size_t *) "NEDMALOC");
  302. #endif
  303. #if defined(DEBUG)
  304. printf("*** nedmalloc frees system allocated block %p\n", mem);
  305. #endif
  306. free(mem);
  307. return;
  308. }
  309. #if USE_MAGIC_HEADERS
  310. assert(_mem[0]==*(size_t *) "NEDMALOC");
  311. oldmspace=(mstate) _mem[1];
  312. oldsize=_mem[2];
  313. for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
  314. mem=(void *)(++_mem);
  315. #endif
  316. #if USE_ALLOCATOR==0
  317. free(mem);
  318. #elif USE_ALLOCATOR==1
  319. mspace_free((mstate) mspace, mem);
  320. #endif
  321. }
  322. static NEDMALLOCNOALIASATTR mstate nedblkmstate(void *RESTRICT mem) THROWSPEC
  323. {
  324. if(mem)
  325. {
  326. #if USE_MAGIC_HEADERS
  327. size_t *_mem=(size_t *) mem-3;
  328. if(_mem[0]==*(size_t *) "NEDMALOC")
  329. {
  330. return (mstate) _mem[1];
  331. }
  332. else return 0;
  333. #else
  334. #if USE_ALLOCATOR==0
  335. /* Fail everything */
  336. return 0;
  337. #elif USE_ALLOCATOR==1
  338. #ifdef ENABLE_FAST_HEAP_DETECTION
  339. #ifdef WIN32
  340. /* On Windows for RELEASE both x86 and x64 the NT heap precedes each block with an eight byte header
  341. which looks like:
  342. normal: 4 bytes of size, 4 bytes of [char < 64, char < 64, char < 64 bit 0 always set, char random ]
  343. mmaped: 4 bytes of size 4 bytes of [zero, zero, 0xb, zero ]
  344. On Windows for DEBUG both x86 and x64 the preceding four bytes is always 0xfdfdfdfd (no man's land).
  345. */
  346. #pragma pack(push, 1)
  347. struct _HEAP_ENTRY
  348. {
  349. USHORT Size;
  350. USHORT PreviousSize;
  351. UCHAR Cookie; /* SegmentIndex */
  352. UCHAR Flags; /* always bit 0 (HEAP_ENTRY_BUSY). bit 1=(HEAP_ENTRY_EXTRA_PRESENT), bit 2=normal block (HEAP_ENTRY_FILL_PATTERN), bit 3=mmap block (HEAP_ENTRY_VIRTUAL_ALLOC). Bit 4 (HEAP_ENTRY_LAST_ENTRY) could be set */
  353. UCHAR UnusedBytes;
  354. UCHAR SmallTagIndex; /* fastbin index. Always one of 0x02, 0x03, 0x04 < 0x80 */
  355. } *RESTRICT he=((struct _HEAP_ENTRY *) mem)-1;
  356. #pragma pack(pop)
  357. unsigned int header=((unsigned int *)mem)[-1], mask1=0x8080E100, result1, mask2=0xFFFFFF06, result2;
  358. result1=header & mask1; /* Positive testing for NT heap */
  359. result2=header & mask2; /* Positive testing for dlmalloc */
  360. if(result1==0x00000100 && result2!=0x00000102)
  361. { /* This is likely a NT heap block */
  362. return 0;
  363. }
  364. #endif
  365. #ifdef __linux__
  366. /* On Linux glibc uses ptmalloc2 (really dlmalloc) just as we do, but prev_foot contains rubbish
  367. when the preceding block is allocated because ptmalloc2 finds the local mstate by rounding the ptr
  368. down to the nearest megabyte. It's like dlmalloc with FOOTERS disabled. */
  369. mchunkptr p=mem2chunk(mem);
  370. mstate fm=get_mstate_for(p);
  371. /* If it's a ptmalloc2 block, fm is likely to be some crazy value */
  372. if(!is_aligned(fm)) return 0;
  373. if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
  374. if(ok_magic(fm))
  375. return fm;
  376. else
  377. return 0;
  378. if(1) { }
  379. #endif
  380. else
  381. {
  382. mchunkptr p=mem2chunk(mem);
  383. mstate fm=get_mstate_for(p);
  384. assert(ok_magic(fm)); /* If this fails, someone tried to free a block twice */
  385. if(ok_magic(fm))
  386. return fm;
  387. }
  388. #else
  389. //#ifdef WIN32
  390. // __try
  391. //#endif
  392. {
  393. /* We try to return zero here if it isn't one of our own blocks, however
  394. the current block annotation scheme used by dlmalloc makes it impossible
  395. to be absolutely sure of avoiding a segfault.
  396. mchunkptr->prev_foot = mem-(2*size_t) = mstate ^ mparams.magic for PRECEDING block;
  397. mchunkptr->head = mem-(1*size_t) = 8 multiple size of this block with bottom three bits = FLAG_BITS
  398. FLAG_BITS = bit 0 is CINUSE (currently in use unless is mmap), bit 1 is PINUSE (previous block currently
  399. in use unless mmap), bit 2 is UNUSED and currently is always zero.
  400. */
  401. register void *RESTRICT leastusedaddress_=leastusedaddress; /* Cache these to avoid register reloading */
  402. register size_t largestusedblock_=largestusedblock;
  403. if(!is_aligned(mem)) return 0; /* Would fail very rarely as all allocators return aligned blocks */
  404. if(mem<leastusedaddress_) return 0; /* Simple but effective */
  405. {
  406. mchunkptr p=mem2chunk(mem);
  407. mstate fm=0;
  408. int ismmapped=is_mmapped(p);
  409. if((!ismmapped && !is_inuse(p)) || (p->head & FLAG4_BIT)) return 0;
  410. /* Reduced uncertainty by 0.5^2 = 25.0% */
  411. /* size should never exceed largestusedblock */
  412. if(chunksize(p)>largestusedblock_) return 0;
  413. /* Reduced uncertainty by a minimum of 0.5^3 = 12.5%, maximum 0.5^16 = 0.0015% */
  414. /* Having sanity checked prev_foot and head, check next block */
  415. if(!ismmapped && (!next_pinuse(p) || (next_chunk(p)->head & FLAG4_BIT))) return 0;
  416. /* Reduced uncertainty by 0.5^5 = 3.13% or 0.5^18 = 0.00038% */
  417. #if 0
  418. /* If previous block is free, check that its next block pointer equals us */
  419. if(!ismmapped && !pinuse(p))
  420. if(next_chunk(prev_chunk(p))!=p) return 0;
  421. /* We could start comparing prev_foot's for similarity but it starts getting slow. */
  422. #endif
  423. fm = get_mstate_for(p);
  424. if(!is_aligned(fm) || (void *)fm<leastusedaddress_) return 0;
  425. if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
  426. assert(ok_magic(fm)); /* If this fails, someone tried to free a block twice */
  427. if(ok_magic(fm))
  428. return fm;
  429. }
  430. }
  431. //#ifdef WIN32
  432. // __except(1) { }
  433. //#endif
  434. #endif
  435. #endif
  436. #endif
  437. }
  438. return 0;
  439. }
  440. NEDMALLOCNOALIASATTR size_t nedblksize(int *RESTRICT isforeign, void *RESTRICT mem) THROWSPEC
  441. {
  442. if(mem)
  443. {
  444. if(isforeign) *isforeign=1;
  445. #if USE_MAGIC_HEADERS
  446. {
  447. size_t *_mem=(size_t *) mem-3;
  448. if(_mem[0]==*(size_t *) "NEDMALOC")
  449. {
  450. mstate mspace=(mstate) _mem[1];
  451. size_t size=_mem[2];
  452. if(isforeign) *isforeign=0;
  453. return size;
  454. }
  455. }
  456. #elif USE_ALLOCATOR==1
  457. if(nedblkmstate(mem))
  458. {
  459. mchunkptr p=mem2chunk(mem);
  460. if(isforeign) *isforeign=0;
  461. return chunksize(p)-overhead_for(p);
  462. }
  463. #ifdef DEBUG
  464. else
  465. {
  466. int a=1; /* Set breakpoints here if needed */
  467. }
  468. #endif
  469. #endif
  470. #if defined(ENABLE_TOLERANT_NEDMALLOC) || USE_ALLOCATOR==0
  471. #ifdef _MSC_VER
  472. /* This is the MSVCRT equivalent */
  473. return _msize(mem);
  474. #elif defined(__linux__)
  475. /* This is the glibc/ptmalloc2/dlmalloc equivalent. */
  476. return malloc_usable_size(mem);
  477. #elif defined(__FreeBSD__) || defined(__APPLE__)
  478. /* This is the BSD libc equivalent. */
  479. return malloc_size(mem);
  480. #else
  481. #error Cannot tolerate the memory allocator of an unknown system!
  482. #endif
  483. #endif
  484. }
  485. return 0;
  486. }
  487. NEDMALLOCNOALIASATTR void nedsetvalue(void *v) THROWSPEC { nedpsetvalue((nedpool *) 0, v); }
  488. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc(size_t size) THROWSPEC { return nedpmalloc((nedpool *) 0, size); }
  489. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedcalloc(size_t no, size_t size) THROWSPEC { return nedpcalloc((nedpool *) 0, no, size); }
  490. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc(void *mem, size_t size) THROWSPEC { return nedprealloc((nedpool *) 0, mem, size); }
  491. NEDMALLOCNOALIASATTR void nedfree(void *mem) THROWSPEC { nedpfree((nedpool *) 0, mem); }
  492. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmemalign(size_t alignment, size_t bytes) THROWSPEC { return nedpmemalign((nedpool *) 0, alignment, bytes); }
  493. NEDMALLOCNOALIASATTR struct nedmallinfo nedmallinfo(void) THROWSPEC { return nedpmallinfo((nedpool *) 0); }
  494. NEDMALLOCNOALIASATTR int nedmallopt(int parno, int value) THROWSPEC { return nedpmallopt((nedpool *) 0, parno, value); }
  495. NEDMALLOCNOALIASATTR int nedmalloc_trim(size_t pad) THROWSPEC { return nedpmalloc_trim((nedpool *) 0, pad); }
  496. void nedmalloc_stats() THROWSPEC { nedpmalloc_stats((nedpool *) 0); }
  497. NEDMALLOCNOALIASATTR size_t nedmalloc_footprint() THROWSPEC { return nedpmalloc_footprint((nedpool *) 0); }
  498. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_calloc(size_t elemsno, size_t elemsize, void **chunks) THROWSPEC { return nedpindependent_calloc((nedpool *) 0, elemsno, elemsize, chunks); }
  499. NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_comalloc(size_t elems, size_t *sizes, void **chunks) THROWSPEC { return nedpindependent_comalloc((nedpool *) 0, elems, sizes, chunks); }
  500. struct threadcacheblk_t;
  501. typedef struct threadcacheblk_t threadcacheblk;
  502. struct threadcacheblk_t
  503. { /* Keep less than 16 bytes on 32 bit systems and 32 bytes on 64 bit systems */
  504. #ifdef FULLSANITYCHECKS
  505. unsigned int magic;
  506. #endif
  507. unsigned int lastUsed, size;
  508. threadcacheblk *next, *prev;
  509. };
  510. typedef struct threadcache_t
  511. {
  512. #ifdef FULLSANITYCHECKS
  513. unsigned int magic1;
  514. #endif
  515. int mymspace; /* Last mspace entry this thread used */
  516. long threadid;
  517. unsigned int mallocs, frees, successes;
  518. size_t freeInCache; /* How much free space is stored in this cache */
  519. threadcacheblk *bins[(THREADCACHEMAXBINS+1)*2];
  520. #ifdef FULLSANITYCHECKS
  521. unsigned int magic2;
  522. #endif
  523. } threadcache;
  524. struct nedpool_t
  525. {
  526. MLOCK_T mutex;
  527. void *uservalue;
  528. int threads; /* Max entries in m to use */
  529. threadcache *caches[THREADCACHEMAXCACHES];
  530. TLSVAR mycache; /* Thread cache for this thread. 0 for unset, negative for use mspace-1 directly, otherwise is cache-1 */
  531. mstate m[MAXTHREADSINPOOL+1]; /* mspace entries for this pool */
  532. };
  533. static nedpool syspool;
  534. static FORCEINLINE NEDMALLOCNOALIASATTR unsigned int size2binidx(size_t _size) THROWSPEC
  535. { /* 8=1000 16=10000 20=10100 24=11000 32=100000 48=110000 4096=1000000000000 */
  536. unsigned int topbit, size=(unsigned int)(_size>>4);
  537. /* 16=1 20=1 24=1 32=10 48=11 64=100 96=110 128=1000 4096=100000000 */
  538. #if defined(__GNUC__)
  539. topbit = sizeof(size)*__CHAR_BIT__ - 1 - __builtin_clz(size);
  540. #elif defined(_MSC_VER) && _MSC_VER>=1300
  541. {
  542. unsigned long bsrTopBit;
  543. _BitScanReverse(&bsrTopBit, size);
  544. topbit = bsrTopBit;
  545. }
  546. #else
  547. #if 0
  548. union {
  549. unsigned asInt[2];
  550. double asDouble;
  551. };
  552. int n;
  553. asDouble = (double)size + 0.5;
  554. topbit = (asInt[!FOX_BIGENDIAN] >> 20) - 1023;
  555. #else
  556. {
  557. unsigned int x=size;
  558. x = x | (x >> 1);
  559. x = x | (x >> 2);
  560. x = x | (x >> 4);
  561. x = x | (x >> 8);
  562. x = x | (x >>16);
  563. x = ~x;
  564. x = x - ((x >> 1) & 0x55555555);
  565. x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
  566. x = (x + (x >> 4)) & 0x0F0F0F0F;
  567. x = x + (x << 8);
  568. x = x + (x << 16);
  569. topbit=31 - (x >> 24);
  570. }
  571. #endif
  572. #endif
  573. return topbit;
  574. }
  575. #ifdef FULLSANITYCHECKS
  576. static void tcsanitycheck(threadcacheblk **ptr) THROWSPEC
  577. {
  578. assert((ptr[0] && ptr[1]) || (!ptr[0] && !ptr[1]));
  579. if(ptr[0] && ptr[1])
  580. {
  581. assert(nedblksize(ptr[0])>=sizeof(threadcacheblk));
  582. assert(nedblksize(ptr[1])>=sizeof(threadcacheblk));
  583. assert(*(unsigned int *) "NEDN"==ptr[0]->magic);
  584. assert(*(unsigned int *) "NEDN"==ptr[1]->magic);
  585. assert(!ptr[0]->prev);
  586. assert(!ptr[1]->next);
  587. if(ptr[0]==ptr[1])
  588. {
  589. assert(!ptr[0]->next);
  590. assert(!ptr[1]->prev);
  591. }
  592. }
  593. }
  594. static void tcfullsanitycheck(threadcache *tc) THROWSPEC
  595. {
  596. threadcacheblk **tcbptr=tc->bins;
  597. int n;
  598. for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
  599. {
  600. threadcacheblk *b, *ob=0;
  601. tcsanitycheck(tcbptr);
  602. for(b=tcbptr[0]; b; ob=b, b=b->next)
  603. {
  604. assert(*(unsigned int *) "NEDN"==b->magic);
  605. assert(!ob || ob->next==b);
  606. assert(!ob || b->prev==ob);
  607. }
  608. }
  609. }
  610. #endif
  611. static NOINLINE void RemoveCacheEntries(nedpool *RESTRICT p, threadcache *RESTRICT tc, unsigned int age) THROWSPEC
  612. {
  613. #ifdef FULLSANITYCHECKS
  614. tcfullsanitycheck(tc);
  615. #endif
  616. if(tc->freeInCache)
  617. {
  618. threadcacheblk **tcbptr=tc->bins;
  619. int n;
  620. for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
  621. {
  622. threadcacheblk **tcb=tcbptr+1; /* come from oldest end of list */
  623. /*tcsanitycheck(tcbptr);*/
  624. for(; *tcb && tc->frees-(*tcb)->lastUsed>=age; )
  625. {
  626. threadcacheblk *f=*tcb;
  627. size_t blksize=f->size; /*nedblksize(f);*/
  628. assert(blksize<=nedblksize(0, f));
  629. assert(blksize);
  630. #ifdef FULLSANITYCHECKS
  631. assert(*(unsigned int *) "NEDN"==(*tcb)->magic);
  632. #endif
  633. *tcb=(*tcb)->prev;
  634. if(*tcb)
  635. (*tcb)->next=0;
  636. else
  637. *tcbptr=0;
  638. tc->freeInCache-=blksize;
  639. assert((long) tc->freeInCache>=0);
  640. CallFree(0, f, 0);
  641. /*tcsanitycheck(tcbptr);*/
  642. }
  643. }
  644. }
  645. #ifdef FULLSANITYCHECKS
  646. tcfullsanitycheck(tc);
  647. #endif
  648. }
  649. static void DestroyCaches(nedpool *RESTRICT p) THROWSPEC
  650. {
  651. if(p->caches)
  652. {
  653. threadcache *tc;
  654. int n;
  655. for(n=0; n<THREADCACHEMAXCACHES; n++)
  656. {
  657. if((tc=p->caches[n]))
  658. {
  659. tc->frees++;
  660. RemoveCacheEntries(p, tc, 0);
  661. assert(!tc->freeInCache);
  662. tc->mymspace=-1;
  663. tc->threadid=0;
  664. CallFree(0, tc, 0);
  665. p->caches[n]=0;
  666. }
  667. }
  668. }
  669. }
  670. static NOINLINE threadcache *AllocCache(nedpool *RESTRICT p) THROWSPEC
  671. {
  672. threadcache *tc=0;
  673. int n, end;
  674. ACQUIRE_LOCK(&p->mutex);
  675. for(n=0; n<THREADCACHEMAXCACHES && p->caches[n]; n++);
  676. if(THREADCACHEMAXCACHES==n)
  677. { /* List exhausted, so disable for this thread */
  678. RELEASE_LOCK(&p->mutex);
  679. return 0;
  680. }
  681. tc=p->caches[n]=(threadcache *) CallCalloc(p->m[0], sizeof(threadcache), 0);
  682. if(!tc)
  683. {
  684. RELEASE_LOCK(&p->mutex);
  685. return 0;
  686. }
  687. #ifdef FULLSANITYCHECKS
  688. tc->magic1=*(unsigned int *)"NEDMALC1";
  689. tc->magic2=*(unsigned int *)"NEDMALC2";
  690. #endif
  691. tc->threadid=(long)(size_t)CURRENT_THREAD;
  692. for(end=0; p->m[end]; end++);
  693. tc->mymspace=abs(tc->threadid) % end;
  694. RELEASE_LOCK(&p->mutex);
  695. if(TLSSET(p->mycache, (void *)(size_t)(n+1))) abort();
  696. return tc;
  697. }
  698. static void *threadcache_malloc(nedpool *RESTRICT p, threadcache *RESTRICT tc, size_t *RESTRICT _size) THROWSPEC
  699. {
  700. void *RESTRICT ret=0;
  701. size_t size=*_size, blksize=0;
  702. unsigned int bestsize;
  703. unsigned int idx=size2binidx(size);
  704. threadcacheblk *RESTRICT blk, **RESTRICT binsptr;
  705. #ifdef FULLSANITYCHECKS
  706. tcfullsanitycheck(tc);
  707. #endif
  708. /* Calculate best fit bin size */
  709. bestsize=1<<(idx+4);
  710. #if 0
  711. /* Finer grained bin fit */
  712. idx<<=1;
  713. if(size>bestsize)
  714. {
  715. idx++;
  716. bestsize+=bestsize>>1;
  717. }
  718. if(size>bestsize)
  719. {
  720. idx++;
  721. bestsize=1<<(4+(idx>>1));
  722. }
  723. #else
  724. if(size>bestsize)
  725. {
  726. idx++;
  727. bestsize<<=1;
  728. }
  729. #endif
  730. assert(bestsize>=size);
  731. if(size<bestsize) size=bestsize;
  732. assert(size<=THREADCACHEMAX);
  733. assert(idx<=THREADCACHEMAXBINS);
  734. binsptr=&tc->bins[idx*2];
  735. /* Try to match close, but move up a bin if necessary */
  736. blk=*binsptr;
  737. if(!blk || blk->size<size)
  738. { /* Bump it up a bin */
  739. if(idx<THREADCACHEMAXBINS)
  740. {
  741. idx++;
  742. binsptr+=2;
  743. blk=*binsptr;
  744. }
  745. }
  746. if(blk)
  747. {
  748. blksize=blk->size; /*nedblksize(blk);*/
  749. assert(nedblksize(0, blk)>=blksize);
  750. assert(blksize>=size);
  751. if(blk->next)
  752. blk->next->prev=0;
  753. *binsptr=blk->next;
  754. if(!*binsptr)
  755. binsptr[1]=0;
  756. #ifdef FULLSANITYCHECKS
  757. blk->magic=0;
  758. #endif
  759. assert(binsptr[0]!=blk && binsptr[1]!=blk);
  760. assert(nedblksize(0, blk)>=sizeof(threadcacheblk) && nedblksize(0, blk)<=THREADCACHEMAX+CHUNK_OVERHEAD);
  761. /*printf("malloc: %p, %p, %p, %lu\n", p, tc, blk, (long) _size);*/
  762. ret=(void *) blk;
  763. }
  764. ++tc->mallocs;
  765. if(ret)
  766. {
  767. assert(blksize>=size);
  768. ++tc->successes;
  769. tc->freeInCache-=blksize;
  770. assert((long) tc->freeInCache>=0);
  771. }
  772. #if defined(DEBUG) && 0
  773. if(!(tc->mallocs & 0xfff))
  774. {
  775. printf("*** threadcache=%u, mallocs=%u (%f), free=%u (%f), freeInCache=%u\n", (unsigned int) tc->threadid, tc->mallocs,
  776. (float) tc->successes/tc->mallocs, tc->frees, (float) tc->successes/tc->frees, (unsigned int) tc->freeInCache);
  777. }
  778. #endif
  779. #ifdef FULLSANITYCHECKS
  780. tcfullsanitycheck(tc);
  781. #endif
  782. *_size=size;
  783. return ret;
  784. }
  785. static NOINLINE void ReleaseFreeInCache(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace) THROWSPEC
  786. {
  787. unsigned int age=THREADCACHEMAXFREESPACE/8192;
  788. /*ACQUIRE_LOCK(&p->m[mymspace]->mutex);*/
  789. while(age && tc->freeInCache>=THREADCACHEMAXFREESPACE)
  790. {
  791. RemoveCacheEntries(p, tc, age);
  792. /*printf("*** Removing cache entries older than %u (%u)\n", age, (unsigned int) tc->freeInCache);*/
  793. age>>=1;
  794. }
  795. /*RELEASE_LOCK(&p->m[mymspace]->mutex);*/
  796. }
  797. static void threadcache_free(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace, void *RESTRICT mem, size_t size) THROWSPEC
  798. {
  799. unsigned int bestsize;
  800. unsigned int idx=size2binidx(size);
  801. threadcacheblk **RESTRICT binsptr, *RESTRICT tck=(threadcacheblk *) mem;
  802. assert(size>=sizeof(threadcacheblk) && size<=THREADCACHEMAX+CHUNK_OVERHEAD);
  803. #ifdef DEBUG
  804. /* Make sure this is a valid memory block */
  805. assert(nedblksize(0, mem));
  806. #endif
  807. #ifdef FULLSANITYCHECKS
  808. tcfullsanitycheck(tc);
  809. #endif
  810. /* Calculate best fit bin size */
  811. bestsize=1<<(idx+4);
  812. #if 0
  813. /* Finer grained bin fit */
  814. idx<<=1;
  815. if(size>bestsize)
  816. {
  817. unsigned int biggerbestsize=bestsize+bestsize<<1;
  818. if(size>=biggerbestsize)
  819. {
  820. idx++;
  821. bestsize=biggerbestsize;
  822. }
  823. }
  824. #endif
  825. if(bestsize!=size) /* dlmalloc can round up, so we round down to preserve indexing */
  826. size=bestsize;
  827. binsptr=&tc->bins[idx*2];
  828. assert(idx<=THREADCACHEMAXBINS);
  829. if(tck==*binsptr)
  830. {
  831. fprintf(stderr, "nedmalloc: Attempt to free already freed memory block %p - aborting!\n", tck);
  832. abort();
  833. }
  834. #ifdef FULLSANITYCHECKS
  835. tck->magic=*(unsigned int *) "NEDN";
  836. #endif
  837. tck->lastUsed=++tc->frees;
  838. tck->size=(unsigned int) size;
  839. tck->next=*binsptr;
  840. tck->prev=0;
  841. if(tck->next)
  842. tck->next->prev=tck;
  843. else
  844. binsptr[1]=tck;
  845. assert(!*binsptr || (*binsptr)->size==tck->size);
  846. *binsptr=tck;
  847. assert(tck==tc->bins[idx*2]);
  848. assert(tc->bins[idx*2+1]==tck || binsptr[0]->next->prev==tck);
  849. /*printf("free: %p, %p, %p, %lu\n", p, tc, mem, (long) size);*/
  850. tc->freeInCache+=size;
  851. #ifdef FULLSANITYCHECKS
  852. tcfullsanitycheck(tc);
  853. #endif
  854. #if 1
  855. if(tc->freeInCache>=THREADCACHEMAXFREESPACE)
  856. ReleaseFreeInCache(p, tc, mymspace);
  857. #endif
  858. }
  859. static NOINLINE int InitPool(nedpool *RESTRICT p, size_t capacity, int threads) THROWSPEC
  860. { /* threads is -1 for system pool */
  861. ensure_initialization();
  862. ACQUIRE_MALLOC_GLOBAL_LOCK();
  863. if(p->threads) goto done;
  864. if(INITIAL_LOCK(&p->mutex)) goto err;
  865. if(TLSALLOC(&p->mycache)) goto err;
  866. #if USE_ALLOCATOR==0
  867. p->m[0]=(mstate) mspacecounter++;
  868. #elif USE_ALLOCATOR==1
  869. if(!(p->m[0]=(mstate) create_mspace(capacity, 1))) goto err;
  870. p->m[0]->extp=p;
  871. #endif
  872. p->threads=(threads<1 || threads>MAXTHREADSINPOOL) ? MAXTHREADSINPOOL : threads;
  873. done:
  874. RELEASE_MALLOC_GLOBAL_LOCK();
  875. return 1;
  876. err:
  877. if(threads<0)
  878. abort(); /* If you can't allocate for system pool, we're screwed */
  879. DestroyCaches(p);
  880. if(p->m[0])
  881. {
  882. #if USE_ALLOCATOR==1
  883. destroy_mspace(p->m[0]);
  884. #endif
  885. p->m[0]=0;
  886. }
  887. if(p->mycache)
  888. {
  889. if(TLSFREE(p->mycache)) abort();
  890. p->mycache=0;
  891. }
  892. RELEASE_MALLOC_GLOBAL_LOCK();
  893. return 0;
  894. }
  895. static NOINLINE mstate FindMSpace(nedpool *RESTRICT p, threadcache *RESTRICT tc, int *RESTRICT lastUsed, size_t size) THROWSPEC
  896. { /* Gets called when thread's last used mspace is in use. The strategy
  897. is to run through the list of all available mspaces looking for an
  898. unlocked one and if we fail, we create a new one so long as we don't
  899. exceed p->threads */
  900. int n, end;
  901. for(n=end=*lastUsed+1; p->m[n]; end=++n)
  902. {
  903. if(TRY_LOCK(&p->m[n]->mutex)) goto found;
  904. }
  905. for(n=0; n<*lastUsed && p->m[n]; n++)
  906. {
  907. if(TRY_LOCK(&p->m[n]->mutex)) goto found;
  908. }
  909. if(end<p->threads)
  910. {
  911. mstate temp;
  912. #if USE_ALLOCATOR==0
  913. temp=(mstate) mspacecounter++;
  914. #elif USE_ALLOCATOR==1
  915. if(!(temp=(mstate) create_mspace(size, 1)))
  916. goto badexit;
  917. #endif
  918. /* Now we're ready to modify the lists, we lock */
  919. ACQUIRE_LOCK(&p->mutex);
  920. while(p->m[end] && end<p->threads)
  921. end++;
  922. if(end>=p->threads)
  923. { /* Drat, must destroy it now */
  924. RELEASE_LOCK(&p->mutex);
  925. #if USE_ALLOCATOR==1
  926. destroy_mspace((mstate) temp);
  927. #endif
  928. goto badexit;
  929. }
  930. /* We really want to make sure this goes into memory now but we
  931. have to be careful of breaking aliasing rules, so write it twice */
  932. *((volatile struct malloc_state **) &p->m[end])=p->m[end]=temp;
  933. ACQUIRE_LOCK(&p->m[end]->mutex);
  934. /*printf("Created mspace idx %d\n", end);*/
  935. RELEASE_LOCK(&p->mutex);
  936. n=end;
  937. goto found;
  938. }
  939. /* Let it lock on the last one it used */
  940. badexit:
  941. ACQUIRE_LOCK(&p->m[*lastUsed]->mutex);
  942. return p->m[*lastUsed];
  943. found:
  944. *lastUsed=n;
  945. if(tc)
  946. tc->mymspace=n;
  947. else
  948. {
  949. if(TLSSET(p->mycache, (void *)(size_t)(-(n+1)))) abort();
  950. }
  951. return p->m[n];
  952. }
  953. typedef struct PoolList_t
  954. {
  955. size_t size; /* Size of list */
  956. size_t length; /* Actual entries in list */
  957. #ifdef DEBUG
  958. nedpool *list[1]; /* Force testing of list expansion */
  959. #else
  960. nedpool *list[16];
  961. #endif
  962. } PoolList;
  963. static MLOCK_T poollistlock;
  964. static PoolList *poollist;
  965. NEDMALLOCPTRATTR nedpool *nedcreatepool(size_t capacity, int threads) THROWSPEC
  966. {
  967. nedpool *ret=0;
  968. if(!poollist)
  969. {
  970. PoolList *newpoollist=0;
  971. if(!(newpoollist=(PoolList *) nedpcalloc(0, 1, sizeof(PoolList)+sizeof(nedpool *)))) return 0;
  972. INITIAL_LOCK(&poollistlock);
  973. ACQUIRE_LOCK(&poollistlock);
  974. poollist=newpoollist;
  975. poollist->size=sizeof(poollist->list)/sizeof(nedpool *);
  976. }
  977. else
  978. ACQUIRE_LOCK(&poollistlock);
  979. if(poollist->length==poollist->size)
  980. {
  981. PoolList *newpoollist=0;
  982. size_t newsize=0;
  983. newsize=sizeof(PoolList)+(poollist->size+1)*sizeof(nedpool *);
  984. if(!(newpoollist=(PoolList *) nedprealloc(0, poollist, newsize))) goto badexit;
  985. poollist=newpoollist;
  986. memset(&poollist->list[poollist->size], 0, newsize-((size_t)&poollist->list[poollist->size]-(size_t)&poollist->list[0]));
  987. poollist->size=((newsize-((char *)&poollist->list[0]-(char *)poollist))/sizeof(nedpool *))-1;
  988. assert(poollist->size>poollist->length);
  989. }
  990. if(!(ret=(nedpool *) nedpcalloc(0, 1, sizeof(nedpool)))) goto badexit;
  991. if(!InitPool(ret, capacity, threads))
  992. {
  993. nedpfree(0, ret);
  994. goto badexit;
  995. }
  996. poollist->list[poollist->length++]=ret;
  997. badexit:
  998. RELEASE_LOCK(&poollistlock);
  999. return ret;
  1000. }
  1001. void neddestroypool(nedpool *p) THROWSPEC
  1002. {
  1003. unsigned int n;
  1004. ACQUIRE_LOCK(&p->mutex);
  1005. DestroyCaches(p);
  1006. for(n=0; p->m[n]; n++)
  1007. {
  1008. #if USE_ALLOCATOR==1
  1009. destroy_mspace(p->m[n]);
  1010. #endif
  1011. p->m[n]=0;
  1012. }
  1013. RELEASE_LOCK(&p->mutex);
  1014. if(TLSFREE(p->mycache)) abort();
  1015. nedpfree(0, p);
  1016. ACQUIRE_LOCK(&poollistlock);
  1017. assert(poollist);
  1018. for(n=0; n<poollist->length && poollist->list[n]!=p; n++);
  1019. assert(n!=poollist->length);
  1020. memmove(&poollist->list[n], &poollist->list[n+1], (size_t)&poollist->list[poollist->length]-(size_t)&poollist->list[n]);
  1021. if(!--poollist->length)
  1022. {
  1023. assert(!poollist->list[0]);
  1024. nedpfree(0, poollist);
  1025. poollist=0;
  1026. }
  1027. RELEASE_LOCK(&poollistlock);
  1028. }
  1029. void neddestroysyspool() THROWSPEC
  1030. {
  1031. nedpool *p=&syspool;
  1032. int n;
  1033. ACQUIRE_LOCK(&p->mutex);
  1034. DestroyCaches(p);
  1035. for(n=0; p->m[n]; n++)
  1036. {
  1037. #if USE_ALLOCATOR==1
  1038. destroy_mspace(p->m[n]);
  1039. #endif
  1040. p->m[n]=0;
  1041. }
  1042. /* Render syspool unusable */
  1043. for(n=0; n<THREADCACHEMAXCACHES; n++)
  1044. p->caches[n]=(threadcache *)(size_t)(sizeof(size_t)>4 ? 0xdeadbeefdeadbeefULL : 0xdeadbeefUL);
  1045. for(n=0; n<MAXTHREADSINPOOL+1; n++)
  1046. p->m[n]=(mstate)(size_t)(sizeof(size_t)>4 ? 0xdeadbeefdeadbeefULL : 0xdeadbeefUL);
  1047. if(TLSFREE(p->mycache)) abort();
  1048. RELEASE_LOCK(&p->mutex);
  1049. }
  1050. nedpool **nedpoollist() THROWSPEC
  1051. {
  1052. nedpool **ret=0;
  1053. if(poollist)
  1054. {
  1055. ACQUIRE_LOCK(&poollistlock);
  1056. if(!(ret=(nedpool **) nedmalloc((poollist->length+1)*sizeof(nedpool *)))) goto badexit;
  1057. memcpy(ret, poollist->list, (poollist->length+1)*sizeof(nedpool *));
  1058. badexit:
  1059. RELEASE_LOCK(&poollistlock);
  1060. }
  1061. return ret;
  1062. }
  1063. void nedpsetvalue(nedpool *p, void *v) THROWSPEC
  1064. {
  1065. if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
  1066. p->uservalue=v;
  1067. }
  1068. void *nedgetvalue(nedpool **p, void *mem) THROWSPEC
  1069. {
  1070. nedpool *np=0;
  1071. mstate fm=nedblkmstate(mem);
  1072. if(!fm || !fm->extp) return 0;
  1073. np=(nedpool *) fm->extp;
  1074. if(p) *p=np;
  1075. return np->uservalue;
  1076. }
  1077. void nedtrimthreadcache(nedpool *p, int disable) THROWSPEC
  1078. {
  1079. int mycache;
  1080. if(!p)
  1081. {
  1082. p=&syspool;
  1083. if(!syspool.threads) InitPool(&syspool, 0, -1);
  1084. }
  1085. mycache=(int)(size_t) TLSGET(p->mycache);
  1086. if(!mycache)
  1087. { /* Set to mspace 0 */
  1088. if(disable && TLSSET(p->mycache, (void *)(size_t)-1)) abort();
  1089. }
  1090. else if(mycache>0)
  1091. { /* Set to last used mspace */
  1092. threadcache *tc=p->caches[mycache-1];
  1093. #if defined(DEBUG)
  1094. printf("Threadcache utilisation: %lf%% in cache with %lf%% lost to other threads\n",
  1095. 100.0*tc->successes/tc->mallocs, 100.0*((double) tc->mallocs-tc->frees)/tc->mallocs);
  1096. #endif
  1097. if(disable && TLSSET(p->mycache, (void *)(size_t)(-tc->mymspace))) abort();
  1098. tc->frees++;
  1099. RemoveCacheEntries(p, tc, 0);
  1100. assert(!tc->freeInCache);
  1101. if(disable)
  1102. {
  1103. tc->mymspace=-1;
  1104. tc->threadid=0;
  1105. CallFree(0, p->caches[mycache-1], 0);
  1106. p->caches[mycache-1]=0;
  1107. }
  1108. }
  1109. }
  1110. void neddisablethreadcache(nedpool *p) THROWSPEC
  1111. {
  1112. nedtrimthreadcache(p, 1);
  1113. }
  1114. #define GETMSPACE(m,p,tc,ms,s,action) \
  1115. do \
  1116. { \
  1117. mstate m = GetMSpace((p),(tc),(ms),(s)); \
  1118. action; \
  1119. if(USE_ALLOCATOR==1) { RELEASE_LOCK(&m->mutex); } \
  1120. } while (0)
  1121. static FORCEINLINE mstate GetMSpace(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace, size_t size) THROWSPEC
  1122. { /* Returns a locked and ready for use mspace */
  1123. mstate m=p->m[mymspace];
  1124. assert(m);
  1125. #if USE_ALLOCATOR==1
  1126. if(!TRY_LOCK(&p->m[mymspace]->mutex)) m=FindMSpace(p, tc, &mymspace, size);
  1127. /*assert(IS_LOCKED(&p->m[mymspace]->mutex));*/
  1128. #endif
  1129. return m;
  1130. }
  1131. static NOINLINE void GetThreadCache_cold1(nedpool *RESTRICT *RESTRICT p) THROWSPEC
  1132. {
  1133. *p=&syspool;
  1134. if(!syspool.threads) InitPool(&syspool, 0, -1);
  1135. }
  1136. static NOINLINE void GetThreadCache_cold2(nedpool *RESTRICT *RESTRICT p, threadcache *RESTRICT *RESTRICT tc, int *RESTRICT mymspace, int mycache) THROWSPEC
  1137. {
  1138. if(!mycache)
  1139. { /* Need to allocate a new cache */
  1140. *tc=AllocCache(*p);
  1141. if(!*tc)
  1142. { /* Disable */
  1143. if(TLSSET((*p)->mycache, (void *)(size_t)-1)) abort();
  1144. *mymspace=0;
  1145. }
  1146. else
  1147. *mymspace=(*tc)->mymspace;
  1148. }
  1149. else
  1150. { /* Cache disabled, but we do have an assigned thread pool */
  1151. *tc=0;
  1152. *mymspace=-mycache-1;
  1153. }
  1154. }
  1155. static FORCEINLINE void GetThreadCache(nedpool *RESTRICT *RESTRICT p, threadcache *RESTRICT *RESTRICT tc, int *RESTRICT mymspace, size_t *RESTRICT size) THROWSPEC
  1156. {
  1157. int mycache;
  1158. if(size && *size<sizeof(threadcacheblk)) *size=sizeof(threadcacheblk);
  1159. if(!*p)
  1160. GetThreadCache_cold1(p);
  1161. mycache=(int)(size_t) TLSGET((*p)->mycache);
  1162. if(mycache>0)
  1163. { /* Already have a cache */
  1164. *tc=(*p)->caches[mycache-1];
  1165. *mymspace=(*tc)->mymspace;
  1166. }
  1167. else GetThreadCache_cold2(p, tc, mymspace, mycache);
  1168. assert(*mymspace>=0);
  1169. assert(!(*tc) || (long)(size_t)CURRENT_THREAD==(*tc)->threadid);
  1170. #ifdef FULLSANITYCHECKS
  1171. if(*tc)
  1172. {
  1173. if(*(unsigned int *)"NEDMALC1"!=(*tc)->magic1 || *(unsigned int *)"NEDMALC2"!=(*tc)->magic2)
  1174. {
  1175. abort();
  1176. }
  1177. }
  1178. #endif
  1179. }
  1180. NEDMALLOCPTRATTR void * nedpmalloc(nedpool *p, size_t size) THROWSPEC
  1181. {
  1182. void *ret=0;
  1183. threadcache *tc;
  1184. int mymspace;
  1185. GetThreadCache(&p, &tc, &mymspace, &size);
  1186. #if THREADCACHEMAX
  1187. if(tc && size<=THREADCACHEMAX)
  1188. { /* Use the thread cache */
  1189. ret=threadcache_malloc(p, tc, &size);
  1190. }
  1191. #endif
  1192. if(!ret)
  1193. { /* Use this thread's mspace */
  1194. GETMSPACE(m, p, tc, mymspace, size,
  1195. ret=CallMalloc(m, size, 0));
  1196. }
  1197. return ret;
  1198. }
  1199. NEDMALLOCPTRATTR void * nedpcalloc(nedpool *p, size_t no, size_t size) THROWSPEC
  1200. {
  1201. size_t rsize=size*no;
  1202. void *ret=0;
  1203. threadcache *tc;
  1204. int mymspace;
  1205. GetThreadCache(&p, &tc, &mymspace, &rsize);
  1206. #if THREADCACHEMAX
  1207. if(tc && rsize<=THREADCACHEMAX)
  1208. { /* Use the thread cache */
  1209. if((ret=threadcache_malloc(p, tc, &rsize)))
  1210. memset(ret, 0, rsize);
  1211. }
  1212. #endif
  1213. if(!ret)
  1214. { /* Use this thread's mspace */
  1215. GETMSPACE(m, p, tc, mymspace, rsize,
  1216. ret=CallCalloc(m, rsize, 0));
  1217. }
  1218. return ret;
  1219. }
  1220. NEDMALLOCPTRATTR void * nedprealloc(nedpool *p, void *mem, size_t size) THROWSPEC
  1221. {
  1222. void *ret=0;
  1223. threadcache *tc;
  1224. int mymspace, isforeign=1;
  1225. size_t memsize;
  1226. if(!mem) return nedpmalloc(p, size);
  1227. memsize=nedblksize(&isforeign, mem);
  1228. assert(memsize);
  1229. if(!memsize)
  1230. {
  1231. fprintf(stderr, "nedmalloc: nedprealloc() called with a block not created by nedmalloc!\n");
  1232. abort();
  1233. }
  1234. else if(size<=memsize && memsize-size<
  1235. #ifdef DEBUG
  1236. 32
  1237. #else
  1238. 1024
  1239. #endif
  1240. ) /* If realloc size is within 1Kb smaller than existing, noop it */
  1241. return mem;
  1242. GetThreadCache(&p, &tc, &mymspace, &size);
  1243. #if THREADCACHEMAX
  1244. if(tc && size && size<=THREADCACHEMAX)
  1245. { /* Use the thread cache */
  1246. if((ret=threadcache_malloc(p, tc, &size)))
  1247. {
  1248. memcpy(ret, mem, memsize<size ? memsize : size);
  1249. if(memsize>=sizeof(threadcacheblk) && memsize<=(THREADCACHEMAX+CHUNK_OVERHEAD))
  1250. threadcache_free(p, tc, mymspace, mem, memsize);
  1251. else
  1252. CallFree(0, mem, isforeign);
  1253. }
  1254. }
  1255. #endif
  1256. if(!ret)
  1257. { /* Reallocs always happen in the mspace they happened in, so skip
  1258. locking the preferred mspace for this thread */
  1259. ret=CallRealloc(p->m[mymspace], mem, isforeign, memsize, size);
  1260. }
  1261. return ret;
  1262. }
  1263. void nedpfree(nedpool *p, void *mem) THROWSPEC
  1264. { /* Frees always happen in the mspace they happened in, so skip
  1265. locking the preferred mspace for this thread */
  1266. threadcache *tc;
  1267. int mymspace, isforeign=1;
  1268. size_t memsize;
  1269. if(!mem)
  1270. { /* If you tried this on FreeBSD you'd be sorry! */
  1271. #ifdef DEBUG
  1272. fprintf(stderr, "nedmalloc: WARNING nedpfree() called with zero. This is not portable behaviour!\n");
  1273. #endif
  1274. return;
  1275. }
  1276. memsize=nedblksize(&isforeign, mem);
  1277. assert(memsize);
  1278. if(!memsize)
  1279. {
  1280. fprintf(stderr, "nedmalloc: nedpfree() called with a block not created by nedmalloc!\n");
  1281. abort();
  1282. }
  1283. GetThreadCache(&p, &tc, &mymspace, 0);
  1284. #if THREADCACHEMAX
  1285. if(mem && tc && memsize>=sizeof(threadcacheblk) && memsize<=(THREADCACHEMAX+CHUNK_OVERHEAD))
  1286. threadcache_free(p, tc, mymspace, mem, memsize);
  1287. else
  1288. #endif
  1289. CallFree(0, mem, isforeign);
  1290. }
  1291. NEDMALLOCPTRATTR void * nedpmemalign(nedpool *p, size_t alignment, size_t bytes) THROWSPEC
  1292. {
  1293. void *ret;
  1294. threadcache *tc;
  1295. int mymspace;
  1296. GetThreadCache(&p, &tc, &mymspace, &bytes);
  1297. { /* Use this thread's mspace */
  1298. GETMSPACE(m, p, tc, mymspace, bytes,
  1299. ret=CallMalloc(m, bytes, alignment));
  1300. }
  1301. return ret;
  1302. }
  1303. struct nedmallinfo nedpmallinfo(nedpool *p) THROWSPEC
  1304. {
  1305. int n;
  1306. struct nedmallinfo ret={0};
  1307. if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
  1308. for(n=0; p->m[n]; n++)
  1309. {
  1310. #if USE_ALLOCATOR==1 && !NO_MALLINFO
  1311. struct mallinfo t=mspace_mallinfo(p->m[n]);
  1312. ret.arena+=t.arena;
  1313. ret.ordblks+=t.ordblks;
  1314. ret.hblkhd+=t.hblkhd;
  1315. ret.usmblks+=t.usmblks;
  1316. ret.uordblks+=t.uordblks;
  1317. ret.fordblks+=t.fordblks;
  1318. ret.keepcost+=t.keepcost;
  1319. #endif
  1320. }
  1321. return ret;
  1322. }
  1323. int nedpmallopt(nedpool *p, int parno, int value) THROWSPEC
  1324. {
  1325. #if USE_ALLOCATOR==1
  1326. return mspace_mallopt(parno, value);
  1327. #else
  1328. return 0;
  1329. #endif
  1330. }
  1331. NEDMALLOCNOALIASATTR void* nedmalloc_internals(size_t *granularity, size_t *magic) THROWSPEC
  1332. {
  1333. #if USE_ALLOCATOR==1
  1334. if(granularity) *granularity=mparams.granularity;
  1335. if(magic) *magic=mparams.magic;
  1336. return (void *) &syspool;
  1337. #else
  1338. if(granularity) *granularity=0;
  1339. if(magic) *magic=0;
  1340. return 0;
  1341. #endif
  1342. }
  1343. int nedpmalloc_trim(nedpool *p, size_t pad) THROWSPEC
  1344. {
  1345. int n, ret=0;
  1346. if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
  1347. for(n=0; p->m[n]; n++)
  1348. {
  1349. #if USE_ALLOCATOR==1
  1350. ret+=mspace_trim(p->m[n], pad);
  1351. #endif
  1352. }
  1353. return ret;
  1354. }
  1355. void nedpmalloc_stats(nedpool *p) THROWSPEC
  1356. {
  1357. int n;
  1358. if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
  1359. for(n=0; p->m[n]; n++)
  1360. {
  1361. #if USE_ALLOCATOR==1
  1362. mspace_malloc_stats(p->m[n]);
  1363. #endif
  1364. }
  1365. }
  1366. size_t nedpmalloc_footprint(nedpool *p) THROWSPEC
  1367. {
  1368. size_t ret=0;
  1369. int n;
  1370. if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
  1371. for(n=0; p->m[n]; n++)
  1372. {
  1373. #if USE_ALLOCATOR==1
  1374. ret+=mspace_footprint(p->m[n]);
  1375. #endif
  1376. }
  1377. return ret;
  1378. }
  1379. NEDMALLOCPTRATTR void **nedpindependent_calloc(nedpool *p, size_t elemsno, size_t elemsize, void **chunks) THROWSPEC
  1380. {
  1381. void **ret;
  1382. threadcache *tc;
  1383. int mymspace;
  1384. GetThreadCache(&p, &tc, &mymspace, &elemsize);
  1385. #if USE_ALLOCATOR==0
  1386. GETMSPACE(m, p, tc, mymspace, elemsno*elemsize,
  1387. ret=unsupported_operation("independent_calloc"));
  1388. #elif USE_ALLOCATOR==1
  1389. GETMSPACE(m, p, tc, mymspace, elemsno*elemsize,
  1390. ret=mspace_independent_calloc(m, elemsno, elemsize, chunks));
  1391. #endif
  1392. return ret;
  1393. }
  1394. NEDMALLOCPTRATTR void **nedpindependent_comalloc(nedpool *p, size_t elems, size_t *sizes, void **chunks) THROWSPEC
  1395. {
  1396. void **ret;
  1397. threadcache *tc;
  1398. int mymspace;
  1399. size_t i, *adjustedsizes=(size_t *) alloca(elems*sizeof(size_t));
  1400. if(!adjustedsizes) return 0;
  1401. for(i=0; i<elems; i++)
  1402. adjustedsizes[i]=sizes[i]<sizeof(threadcacheblk) ? sizeof(threadcacheblk) : sizes[i];
  1403. GetThreadCache(&p, &tc, &mymspace, 0);
  1404. #if USE_ALLOCATOR==0
  1405. GETMSPACE(m, p, tc, mymspace, 0,
  1406. ret=unsupported_operation("independent_comalloc"));
  1407. #elif USE_ALLOCATOR==1
  1408. GETMSPACE(m, p, tc, mymspace, 0,
  1409. ret=mspace_independent_comalloc(m, elems, adjustedsizes, chunks));
  1410. #endif
  1411. return ret;
  1412. }
  1413. #if defined(__cplusplus)
  1414. }
  1415. #endif
  1416. #ifdef _MSC_VER
  1417. #pragma warning(pop)
  1418. #endif
  1419. #endif