Commit message: Avoid overflowing allocation size in calloc()
CVE: CVE-2012-2675
CWE: CWE-189
Vulnerability description: Multiple integer overflows in the (1) CallMalloc (malloc) and (2) nedpcalloc (calloc) functions in nedmalloc (nedmalloc.c) before 1.10 beta2 make it easier for context-dependent attackers to perform memory-related attacks such as buffer overflows via a large size value, which causes less memory to be allocated than expected.

Project: nedmalloc

void *nedgetvalue(nedpool **p, void *mem) THROWSPEC
{
	nedpool *np=0;
	mstate fm=nedblkmstate(mem);
	if(!fm || !fm->extp) return 0;
	np=(nedpool *) fm->extp;
	if(p) *p=np;
	return np->uservalue;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc(size_t size) THROWSPEC													{ return nedpmalloc((nedpool *) 0, size); }

Project: nedmalloc

static void threadcache_free(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace, void *RESTRICT mem, size_t size, int isforeign) THROWSPEC
{
	unsigned int bestsize;
	unsigned int idx=size2binidx(size);
	threadcacheblk *RESTRICT *RESTRICT binsptr, *RESTRICT tck=(threadcacheblk *RESTRICT) mem;
	assert(size>=sizeof(threadcacheblk) && size<=THREADCACHEMAX+CHUNK_OVERHEAD);
#ifdef DEBUG
	/* Make sure this is a valid memory block */
	assert(nedblksize(0, mem, 0));
#endif
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
	/* Calculate best fit bin size */
	bestsize=1<<(idx+4);
#if 0
	/* Finer grained bin fit */
	idx<<=1;
	if(size>bestsize)
	{
		unsigned int biggerbestsize=bestsize+bestsize<<1;
		if(size>=biggerbestsize)
		{
			idx++;
			bestsize=biggerbestsize;
		}
	}
#endif
	if(bestsize!=size)	/* dlmalloc can round up, so we round down to preserve indexing */
		size=bestsize;
	binsptr=&tc->bins[idx*2];
	assert(idx<=THREADCACHEMAXBINS);
	if(tck==*binsptr)
	{
		fprintf(stderr, "nedmalloc: Attempt to free already freed memory block %p - aborting!\n", tck);
		abort();
	}
#ifdef FULLSANITYCHECKS
	tck->magic=*(unsigned int *) "NEDN";
#endif
	tck->isforeign=isforeign;
	tck->lastUsed=++tc->frees;
	tck->size=(unsigned int) size;
	tck->next=*binsptr;
	tck->prev=0;
	if(tck->next)
		tck->next->prev=tck;
	else
		binsptr[1]=tck;
	assert(!*binsptr || (*binsptr)->size==tck->size);
	*binsptr=tck;
	assert(tck==tc->bins[idx*2]);
	assert(tc->bins[idx*2+1]==tck || binsptr[0]->next->prev==tck);
	/*printf("free: %p, %p, %p, %lu\n", p, tc, mem, (long) size);*/
	tc->freeInCache+=size;
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
#if 1
	if(tc->freeInCache>=THREADCACHEMAXFREESPACE)
		ReleaseFreeInCache(p, tc, mymspace);
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR size_t nedblksize(int *RESTRICT isforeign, void *RESTRICT mem, unsigned flags) THROWSPEC
{
	if(mem)
	{
		if(isforeign) *isforeign=1;
#if USE_MAGIC_HEADERS
		{
			size_t *_mem=(size_t *) mem-3;
			if(_mem[0]==*(size_t *) "NEDMALOC")
			{
				mstate mspace=(mstate) _mem[1];
				size_t size=_mem[2];
				if(isforeign) *isforeign=0;
				return size;
			}
		}
#elif USE_ALLOCATOR==1
		if((flags & NM_SKIP_TOLERANCE_CHECKS) || nedblkmstate(mem))
		{
			mchunkptr p=mem2chunk(mem);
			if(isforeign) *isforeign=0;
			return chunksize(p)-overhead_for(p);
		}
#ifdef DEBUG
		else
		{
			int a=1; /* Set breakpoints here if needed */
		}
#endif
#endif
#if defined(ENABLE_TOLERANT_NEDMALLOC) || USE_ALLOCATOR==0
		return sysblksize(mem);
#endif
	}
	return 0;
}

Project: nedmalloc

static NOINLINE threadcache *AllocCache(nedpool *RESTRICT p) THROWSPEC
{
	threadcache *tc=0;
	int n, end;
#if USE_LOCKS
	ACQUIRE_LOCK(&p->mutex);
#endif
	for(n=0; n<THREADCACHEMAXCACHES && p->caches[n]; n++);
	if(THREADCACHEMAXCACHES==n)
	{	/* List exhausted, so disable for this thread */
#if USE_LOCKS
		RELEASE_LOCK(&p->mutex);
#endif
		return 0;
	}
	tc=p->caches[n]=(threadcache *) CallMalloc(p->m[0], sizeof(threadcache), 0, M2_ZERO_MEMORY);
	if(!tc)
	{
#if USE_LOCKS
		RELEASE_LOCK(&p->mutex);
#endif
		return 0;
	}
#ifdef FULLSANITYCHECKS
	tc->magic1=*(unsigned int *)"NEDMALC1";
	tc->magic2=*(unsigned int *)"NEDMALC2";
#endif
	tc->threadid=
#if USE_LOCKS
		(long)(size_t)CURRENT_THREAD;
#else
		1;
#endif
	for(end=0; p->m[end]; end++);
	tc->mymspace=abs(tc->threadid) % end;
#if ENABLE_LOGGING
	{
		mchunkptr cp;
		size_t logentrieslen=2048/sizeof(logentry);		/* One page */
		tc->logentries=tc->logentriesptr=(logentry *) CallMalloc(p->m[0], logentrieslen*sizeof(logentry), 0, M2_ZERO_MEMORY|M2_ALWAYS_MMAP|M2_RESERVE_MULT(8));
		if(!tc->logentries)
		{
#if USE_LOCKS
			RELEASE_LOCK(&p->mutex);
#endif
			return 0;
		}
		cp=mem2chunk(tc->logentries);
		logentrieslen=(chunksize(cp)-overhead_for(cp))/sizeof(logentry);
		tc->logentriesend=tc->logentries+logentrieslen;
	}
#endif
#if USE_LOCKS
	RELEASE_LOCK(&p->mutex);
#endif
	if(TLSSET(p->mycache, (void *)(size_t)(n+1))) abort();
	return tc;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedpindependent_comalloc(nedpool *p, size_t elems, size_t *sizes, void **chunks) THROWSPEC
{
	void **ret;
	threadcache *tc;
	int mymspace;
    size_t i, *adjustedsizes=(size_t *) alloca(elems*sizeof(size_t));
    if(!adjustedsizes) return 0;
    for(i=0; i<elems; i++)
        adjustedsizes[i]=sizes[i]<sizeof(threadcacheblk) ? sizeof(threadcacheblk) : sizes[i];
	GetThreadCache(&p, &tc, &mymspace, 0);
#if USE_ALLOCATOR==0
	GETMSPACE(m, p, tc, mymspace, 0,
              ret=unsupported_operation("independent_comalloc"));
#elif USE_ALLOCATOR==1
	GETMSPACE(m, p, tc, mymspace, 0,
              ret=mspace_independent_comalloc(m, elems, adjustedsizes, chunks));
#endif
#if ENABLE_LOGGING
	if(ret && (ENABLE_LOGGING & LOGENTRY_POOL_MALLOC))
	{
		size_t n;
		for(n=0; n<elems; n++)
		{
			LogOperation(tc, p, LOGENTRY_POOL_MALLOC, mymspace, sizes[n], 0, 0, 0, ret[n]);
		}
	}
#endif
	return ret;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR struct nedmallinfo nedmallinfo(void) THROWSPEC																{ return nedpmallinfo((nedpool *) 0); }

Project: nedmalloc

NEDMALLOCNOALIASATTR int    nedmalloc_trim(size_t pad) THROWSPEC																{ return nedpmalloc_trim((nedpool *) 0, pad); }

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc(void *mem, size_t size) THROWSPEC										{ return nedprealloc((nedpool *) 0, mem, size); }

Project: nedmalloc

void neddestroypool(nedpool *p) THROWSPEC
{
	unsigned int n;
#if USE_LOCKS
	ACQUIRE_LOCK(&p->mutex);
#endif
	DestroyCaches(p);
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1
		destroy_mspace(p->m[n]);
#endif
		p->m[n]=0;
	}
#if USE_LOCKS
	RELEASE_LOCK(&p->mutex);
	DESTROY_LOCK(&p->mutex);
#endif
	if(TLSFREE(p->mycache)) abort();
	nedpfree(0, p);
#if USE_LOCKS
	ACQUIRE_LOCK(&poollistlock);
#endif
	assert(poollist);
	for(n=0; n<poollist->length && poollist->list[n]!=p; n++);
	assert(n!=poollist->length);
	memmove(&poollist->list[n], &poollist->list[n+1], (size_t)&poollist->list[poollist->length]-(size_t)&poollist->list[n]);
	if(!--poollist->length)
	{
		assert(!poollist->list[0]);
		nedpfree(0, poollist);
		poollist=0;
	}
#if USE_LOCKS
	RELEASE_LOCK(&poollistlock);
#endif
}

Project: nedmalloc

static void DestroyCaches(nedpool *RESTRICT p) THROWSPEC
{
	if(p->caches)
	{
		threadcache *tc;
		int n;
		nedflushlogs(p, 0);
		for(n=0; n<THREADCACHEMAXCACHES; n++)
		{
			if((tc=p->caches[n]))
			{
				tc->mymspace=-1;
				tc->threadid=0;
				CallFree(0, tc, 0);
				p->caches[n]=0;
			}
		}
	}
}

Project: nedmalloc

static NOINLINE void ReleaseFreeInCache(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace) THROWSPEC
{
	unsigned int age=THREADCACHEMAXFREESPACE/8192;
#if USE_LOCKS
	/*ACQUIRE_LOCK(&p->m[mymspace]->mutex);*/
#endif
	while(age && tc->freeInCache>=THREADCACHEMAXFREESPACE)
	{
		RemoveCacheEntries(p, tc, age);
		/*printf("*** Removing cache entries older than %u (%u)\n", age, (unsigned int) tc->freeInCache);*/
		age>>=1;
	}
#if USE_LOCKS
	/*RELEASE_LOCK(&p->m[mymspace]->mutex);*/
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedrealloc2(void *mem, size_t size, size_t alignment, unsigned flags) THROWSPEC	{ return nedprealloc2((nedpool *) 0, mem, size, alignment, flags); }

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc(nedpool *p, size_t size) THROWSPEC
{
	unsigned flags=NEDMALLOC_FORCERESERVE(p, 0, size);
	return nedpmalloc2(p, size, 0, flags);
}

Project: nedmalloc

NEDMALLOCNOALIASATTR size_t nedmalloc_footprint() THROWSPEC																		{ return nedpmalloc_footprint((nedpool *) 0); }

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedprealloc(nedpool *p, void *mem, size_t size) THROWSPEC
{
	unsigned flags=NEDMALLOC_FORCERESERVE(p, mem, size);
#if ENABLE_USERMODEPAGEALLOCATOR
	/* If the user mode page allocator is turned on in a 32 bit process,
	don't automatically reserve eight times the address space. */
	if(8==sizeof(size_t) || !OSHavePhysicalPageSupport())
#endif
	{	/* If he reallocs even once, it's probably wise to turn on address space reservation.
		If the size is larger than mmap_threshold then it'll set the reserve. */
		if(!(flags & M2_RESERVE_MASK)) flags=M2_RESERVE_MULT(8);
	}
	return nedprealloc2(p, mem, size, 0, flags);
}

Project: nedmalloc

static void tcsanitycheck(threadcacheblk *RESTRICT *RESTRICT ptr) THROWSPEC
{
	assert((ptr[0] && ptr[1]) || (!ptr[0] && !ptr[1]));
	if(ptr[0] && ptr[1])
	{
		assert(ptr[0]->isforeign || nedblkmstate(ptr[0]));
		assert(ptr[1]->isforeign || nedblkmstate(ptr[1]));
		assert(nedblksize(0, ptr[0], 0)>=sizeof(threadcacheblk));
		assert(nedblksize(0, ptr[1], 0)>=sizeof(threadcacheblk));
		assert(*(unsigned int *) "NEDN"==ptr[0]->magic);
		assert(*(unsigned int *) "NEDN"==ptr[1]->magic);
		assert(!ptr[0]->prev);
		assert(!ptr[1]->next);
		if(ptr[0]==ptr[1])
		{
			assert(!ptr[0]->next);
			assert(!ptr[1]->prev);
		}
	}
}

Project: nedmalloc

struct nedmallinfo nedpmallinfo(nedpool *p) THROWSPEC
{
	int n;
	struct nedmallinfo ret={0};
	if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1 && !NO_MALLINFO
		struct mallinfo t=mspace_mallinfo(p->m[n]);
		ret.arena+=t.arena;
		ret.ordblks+=t.ordblks;
		ret.hblkhd+=t.hblkhd;
		ret.usmblks+=t.usmblks;
		ret.uordblks+=t.uordblks;
		ret.fordblks+=t.fordblks;
		ret.keepcost+=t.keepcost;
#endif
	}
	return ret;
}

Project: nedmalloc

void   nedmalloc_stats() THROWSPEC																								{ nedpmalloc_stats((nedpool *) 0); }

Project: nedmalloc

static void *threadcache_malloc(nedpool *RESTRICT p, threadcache *RESTRICT tc, size_t *RESTRICT _size) THROWSPEC
{
	void *RESTRICT ret=0;
	size_t size=*_size, blksize=0;
	unsigned int bestsize;
	unsigned int idx=size2binidx(size);
	threadcacheblk *RESTRICT blk, *RESTRICT *RESTRICT binsptr;
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
	/* Calculate best fit bin size */
	bestsize=1<<(idx+4);
#if 0
	/* Finer grained bin fit */
	idx<<=1;
	if(size>bestsize)
	{
		idx++;
		bestsize+=bestsize>>1;
	}
	if(size>bestsize)
	{
		idx++;
		bestsize=1<<(4+(idx>>1));
	}
#else
	if(size>bestsize)
	{
		idx++;
		bestsize<<=1;
	}
#endif
	assert(bestsize>=size);
	if(size<bestsize) size=bestsize;
	assert(size<=THREADCACHEMAX);
	assert(idx<=THREADCACHEMAXBINS);
	binsptr=&tc->bins[idx*2];
	/* Try to match close, but move up a bin if necessary */
	blk=*binsptr;
	if(!blk || blk->size<size)
	{	/* Bump it up a bin */
		if(idx<THREADCACHEMAXBINS)
		{
			idx++;
			binsptr+=2;
			blk=*binsptr;
		}
	}
	if(blk)
	{
		blksize=blk->size; /*nedblksize(blk);*/
		assert(nedblksize(0, blk, 0)>=blksize);
		assert(blksize>=size);
		if(blk->next)
			blk->next->prev=0;
		*binsptr=blk->next;
		if(!*binsptr)
			binsptr[1]=0;
#ifdef FULLSANITYCHECKS
		blk->magic=0;
#endif
		assert(binsptr[0]!=blk && binsptr[1]!=blk);
		assert(nedblksize(0, blk, 0)>=sizeof(threadcacheblk) && nedblksize(0, blk, 0)<=THREADCACHEMAX+CHUNK_OVERHEAD);
		/*printf("malloc: %p, %p, %p, %lu\n", p, tc, blk, (long) _size);*/
		ret=(void *) blk;
	}
	++tc->mallocs;
	if(ret)
	{
		assert(blksize>=size);
		++tc->successes;
		tc->freeInCache-=blksize;
		assert((long) tc->freeInCache>=0);
	}
#if defined(DEBUG) && 0
	if(!(tc->mallocs & 0xfff))
	{
		printf("*** threadcache=%u, mallocs=%u (%f), free=%u (%f), freeInCache=%u\n", (unsigned int) tc->threadid, tc->mallocs,
			(float) tc->successes/tc->mallocs, tc->frees, (float) tc->successes/tc->frees, (unsigned int) tc->freeInCache);
	}
#endif
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
	*_size=size;
	return ret;
}

Project: nedmalloc

static timeCount GetTimestamp()
{
	static timeCount baseCount;
	timeCount ret;
#ifdef CLOCK_MONOTONIC
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	ret=((timeCount) ts.tv_sec*1000000000000LL)+ts.tv_nsec*1000LL;
#else
	struct timeval tv;
	gettimeofday(&tv, 0);
	ret=((timeCount) tv.tv_sec*1000000000000LL)+tv.tv_usec*1000000LL;
#endif
	if(!baseCount) baseCount=ret;
	return ret-baseCount;
}

Project: nedmalloc
File: nedmalloc.c

void nedpsetvalue(nedpool *p, void *v) THROWSPEC
{
	if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
	p->uservalue=v;
}

Project: nedmalloc

static NOINLINE mstate FindMSpace(nedpool *RESTRICT p, threadcache *RESTRICT tc, int *RESTRICT lastUsed, size_t size) THROWSPEC
{	/* Gets called when thread's last used mspace is in use. The strategy
	is to run through the list of all available mspaces looking for an
	unlocked one and if we fail, we create a new one so long as we don't
	exceed p->threads */
	int n, end;
	n=end=*lastUsed+1;
#if USE_LOCKS
	for(; p->m[n]; end=++n)
	{
		if(TRY_LOCK(&p->m[n]->mutex)) goto found;
	}
	for(n=0; n<*lastUsed && p->m[n]; n++)
	{
		if(TRY_LOCK(&p->m[n]->mutex)) goto found;
	}
	if(end<p->threads)
	{
		mstate temp;
#if USE_ALLOCATOR==0
		temp=(mstate) mspacecounter++;
#elif USE_ALLOCATOR==1
		if(!(temp=(mstate) create_mspace(size, 1)))
			goto badexit;
#endif
		/* Now we're ready to modify the lists, we lock */
		ACQUIRE_LOCK(&p->mutex);
		while(p->m[end] && end<p->threads)
			end++;
		if(end>=p->threads)
		{	/* Drat, must destroy it now */
			RELEASE_LOCK(&p->mutex);
#if USE_ALLOCATOR==1
			destroy_mspace((mstate) temp);
#endif
			goto badexit;
		}
		/* We really want to make sure this goes into memory now but we
		have to be careful of breaking aliasing rules, so write it twice */
		{
			volatile struct malloc_state **_m=(volatile struct malloc_state **) &p->m[end];
			*_m=(p->m[end]=temp);
		}
		ACQUIRE_LOCK(&p->m[end]->mutex);
		/*printf("Created mspace idx %d\n", end);*/
		RELEASE_LOCK(&p->mutex);
		n=end;
		goto found;
	}
	/* Let it lock on the last one it used */
badexit:
	ACQUIRE_LOCK(&p->m[*lastUsed]->mutex);
	return p->m[*lastUsed];
#endif
found:
	*lastUsed=n;
	if(tc)
		tc->mymspace=n;
	else
	{
		if(TLSSET(p->mycache, (void *)(size_t)(-(n+1)))) abort();
	}
	return p->m[n];
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR nedpool *nedcreatepool(size_t capacity, int threads) THROWSPEC
{
	nedpool *ret=0;
	if(!poollist)
	{
		PoolList *newpoollist=0;
		if(!(newpoollist=(PoolList *) nedpcalloc(0, 1, sizeof(PoolList)+sizeof(nedpool *)))) return 0;
#if USE_LOCKS
		INITIAL_LOCK(&poollistlock);
		ACQUIRE_LOCK(&poollistlock);
#endif
		poollist=newpoollist;
		poollist->size=sizeof(poollist->list)/sizeof(nedpool *);
	}
#if USE_LOCKS
	else
		ACQUIRE_LOCK(&poollistlock);
#endif
	if(poollist->length==poollist->size)
	{
		PoolList *newpoollist=0;
		size_t newsize=0;
		newsize=sizeof(PoolList)+(poollist->size+1)*sizeof(nedpool *);
		if(!(newpoollist=(PoolList *) nedprealloc(0, poollist, newsize))) goto badexit;
		poollist=newpoollist;
		memset(&poollist->list[poollist->size], 0, newsize-((size_t)&poollist->list[poollist->size]-(size_t)&poollist->list[0]));
		poollist->size=((newsize-((char *)&poollist->list[0]-(char *)poollist))/sizeof(nedpool *))-1;
		assert(poollist->size>poollist->length);
	}
	if(!(ret=(nedpool *) nedpcalloc(0, 1, sizeof(nedpool)))) goto badexit;
	if(!InitPool(ret, capacity, threads))
	{
		nedpfree(0, ret);
		goto badexit;
	}
	poollist->list[poollist->length++]=ret;
badexit:
	{
#if USE_LOCKS
		RELEASE_LOCK(&poollistlock);
#endif
	}
	return ret;
}

Project: nedmalloc

static FORCEINLINE void GetThreadCache(nedpool *RESTRICT *RESTRICT p, threadcache *RESTRICT *RESTRICT tc, int *RESTRICT mymspace, size_t *RESTRICT size) THROWSPEC
{
	int mycache;
#if THREADCACHEMAX
	if(size && *size<sizeof(threadcacheblk)) *size=sizeof(threadcacheblk);
#endif
	if(!*p)
		GetThreadCache_cold1(p);
	mycache=(int)(size_t) TLSGET((*p)->mycache);
	if(mycache>0)
	{	/* Already have a cache */
		*tc=(*p)->caches[mycache-1];
		*mymspace=(*tc)->mymspace;
	}
	else GetThreadCache_cold2(p, tc, mymspace, mycache);
	assert(*mymspace>=0);
#if USE_LOCKS
	assert(!(*tc) || (long)(size_t)CURRENT_THREAD==(*tc)->threadid);
#endif
#ifdef FULLSANITYCHECKS
	if(*tc)
	{
		if(*(unsigned int *)"NEDMALC1"!=(*tc)->magic1 || *(unsigned int *)"NEDMALC2"!=(*tc)->magic2)
		{
			abort();
		}
	}
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmalloc2(nedpool *p, size_t size, size_t alignment, unsigned flags) THROWSPEC
{
	void *ret=0;
	threadcache *tc;
	int mymspace;
	GetThreadCache(&p, &tc, &mymspace, &size);
#if THREADCACHEMAX
	if(alignment<=MALLOC_ALIGNMENT && !(flags & NM_FLAGS_MASK) && tc && size<=THREADCACHEMAX)
	{	/* Use the thread cache */
		if((ret=threadcache_malloc(p, tc, &size)))
		{
			if((flags & M2_ZERO_MEMORY))
				memset(ret, 0, size);
			LogOperation(tc, p, LOGENTRY_THREADCACHE_MALLOC, mymspace, size, 0, alignment, flags, ret);
		}
	}
#endif
	if(!ret)
	{	/* Use this thread's mspace */
        GETMSPACE(m, p, tc, mymspace, size,
                  ret=CallMalloc(m, size, alignment, flags));
		if(ret)
			LogOperation(tc, p, LOGENTRY_POOL_MALLOC, mymspace, size, 0, alignment, flags, ret);
	}
	LogOperation(tc, p, LOGENTRY_MALLOC, mymspace, size, 0, alignment, flags, ret);
	return ret;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpmemalign(nedpool *p, size_t alignment, size_t bytes) THROWSPEC
{
	unsigned flags=NEDMALLOC_FORCERESERVE(p, 0, bytes);
	return nedpmalloc2(p, bytes, alignment, flags);
}

Project: nedmalloc

static timeCount GetTimestamp()
{
	static LARGE_INTEGER ticksPerSec;
	static double scalefactor;
	static timeCount baseCount;
	LARGE_INTEGER val;
	timeCount ret;
	if(!scalefactor)
	{
		if(QueryPerformanceFrequency(&ticksPerSec))
			scalefactor=ticksPerSec.QuadPart/1000000000000.0;
		else
			scalefactor=1;
	}
	if(!QueryPerformanceCounter(&val))
		return (timeCount) GetTickCount() * 1000000000;
	ret=(timeCount) (val.QuadPart/scalefactor);
	if(!baseCount) baseCount=ret;
	return ret-baseCount;
}

Project: nedmalloc

static FORCEINLINE NEDMALLOCNOALIASATTR unsigned int size2binidx(size_t _size) THROWSPEC
{	/* 8=1000	16=10000	20=10100	24=11000	32=100000	48=110000	4096=1000000000000 */
	unsigned int topbit, size=(unsigned int)(_size>>4);
	/* 16=1		20=1	24=1	32=10	48=11	64=100	96=110	128=1000	4096=100000000 */

#if defined(__GNUC__)
        topbit = sizeof(size)*__CHAR_BIT__ - 1 - __builtin_clz(size);
#elif defined(_MSC_VER) && _MSC_VER>=1300
	{
            unsigned long bsrTopBit;

            _BitScanReverse(&bsrTopBit, size);

            topbit = bsrTopBit;
        }
#else
#if 0
	union {
		unsigned asInt[2];
		double asDouble;
	};
	int n;

	asDouble = (double)size + 0.5;
	topbit = (asInt[!FOX_BIGENDIAN] >> 20) - 1023;
#else
	{
		unsigned int x=size;
		x = x | (x >> 1);
		x = x | (x >> 2);
		x = x | (x >> 4);
		x = x | (x >> 8);
		x = x | (x >>16);
		x = ~x;
		x = x - ((x >> 1) & 0x55555555);
		x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
		x = (x + (x >> 4)) & 0x0F0F0F0F;
		x = x + (x << 8);
		x = x + (x << 16);
		topbit=31 - (x >> 24);
	}
#endif
#endif
	return topbit;
}

Project: nedmalloc

void neddisablethreadcache(nedpool *p) THROWSPEC
{
	nedtrimthreadcache(p, 1);
}

Project: nedmalloc

void neddestroysyspool() THROWSPEC
{
	nedpool *p=&syspool;
	int n;
#if USE_LOCKS
	ACQUIRE_LOCK(&p->mutex);
#endif
	DestroyCaches(p);
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1
		destroy_mspace(p->m[n]);
#endif
		p->m[n]=0;
	}
	/* Render syspool unusable */
	for(n=0; n<THREADCACHEMAXCACHES; n++)
		p->caches[n]=(threadcache *)(size_t)(sizeof(size_t)>4 ? 0xdeadbeefdeadbeefULL : 0xdeadbeefUL);
	for(n=0; n<MAXTHREADSINPOOL+1; n++)
		p->m[n]=(mstate)(size_t)(sizeof(size_t)>4 ? 0xdeadbeefdeadbeefULL : 0xdeadbeefUL);
	if(TLSFREE(p->mycache)) abort();
#if USE_LOCKS
	RELEASE_LOCK(&p->mutex);
	DESTROY_LOCK(&p->mutex);
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR void   nedfree2(void *mem, unsigned flags) THROWSPEC														{ nedpfree2((nedpool *) 0, mem, flags); }

Project: nedmalloc

static NOINLINE int InitPool(nedpool *RESTRICT p, size_t capacity, int threads) THROWSPEC
{	/* threads is -1 for system pool */
	ensure_initialization();
	ACQUIRE_MALLOC_GLOBAL_LOCK();
	if(p->threads) goto done;
#if USE_LOCKS
	if(INITIAL_LOCK(&p->mutex)) goto err;
#endif
	if(TLSALLOC(&p->mycache)) goto err;
#if USE_ALLOCATOR==0
	p->m[0]=(mstate) mspacecounter++;
#elif USE_ALLOCATOR==1
	if(!(p->m[0]=(mstate) create_mspace(capacity, 1))) goto err;
	p->m[0]->extp=p;
#endif
	p->threads=(threads>MAXTHREADSINPOOL) ? MAXTHREADSINPOOL : (!threads) ? DEFAULTMAXTHREADSINPOOL : threads;
done:
	RELEASE_MALLOC_GLOBAL_LOCK();
	return 1;
err:
	if(threads<0)
		abort();			/* If you can't allocate for system pool, we're screwed */
	DestroyCaches(p);
	if(p->m[0])
	{
#if USE_ALLOCATOR==1
		destroy_mspace(p->m[0]);
#endif
		p->m[0]=0;
	}
	if(p->mycache)
	{
		if(TLSFREE(p->mycache)) abort();
		p->mycache=0;
	}
	RELEASE_MALLOC_GLOBAL_LOCK();
	return 0;
}

Project: nedmalloc

void   nedpmalloc_stats(nedpool *p) THROWSPEC
{
	int n;
	if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1
		mspace_malloc_stats(p->m[n]);
#endif
	}
}

Project: nedmalloc

static void DoStackWalk(logentry *p) THROWSPEC
{
	void *backtr[NEDMALLOC_STACKBACKTRACEDEPTH];
	size_t size;
	char **strings;
	size_t i2;
	size=backtrace(backtr, NEDMALLOC_STACKBACKTRACEDEPTH);
	strings=backtrace_symbols(backtr, size);
	for(i2=0; i2<size; i2++)
	{	// Format can be <file path>(<mangled symbol>+0x<offset>) [<pc>]
		// or can be <file path> [<pc>]
		int start=0, end=strlen(strings[i2]), which=0, idx;
		for(idx=0; idx<end; idx++)
		{
			if(0==which && (' '==strings[i2][idx] || '('==strings[i2][idx]))
			{
				int len=FXMIN(idx-start, (int) sizeof(p->stack[i2].file));
				memcpy(p->stack[i2].file, strings[i2]+start, len);
				p->stack[i2].file[len]=0;
				which=(' '==strings[i2][idx]) ? 2 : 1;
				start=idx+1;
			}
			else if(1==which && ')'==strings[i2][idx])
			{
				FXString functname(strings[i2]+start, idx-start);
				FXint offset=functname.rfind("+0x");
				FXString rawsymbol(functname.left(offset));
				FXString symbol(rawsymbol.length() ? fxdemanglesymbol(rawsymbol, false) : rawsymbol);
				symbol.append(functname.mid(offset));
				int len=FXMIN(symbol.length(), (int) sizeof(p->stack[i2].functname));
				memcpy(p->stack[i2].functname, symbol.text(), len);
				p->stack[i2].functname[len]=0;
				which=2;
			}
			else if(2==which && '['==strings[i2][idx])
			{
				start=idx+1;
				which=3;
			}
			else if(3==which && ']'==strings[i2][idx])
			{
				FXString v(strings[i2]+start+2, idx-start-2);
				p->stack[i2].pc=(void *)(FXuval)v.toULong(0, 16);
			}
		}
	}
	free(strings);
}

Project: nedmalloc

void nedtrimthreadcache(nedpool *p, int disable) THROWSPEC
{
	int mycache;
	if(!p)
	{
		p=&syspool;
		if(!syspool.threads) InitPool(&syspool, 0, -1);
	}
	mycache=(int)(size_t) TLSGET(p->mycache);
	if(!mycache)
	{	/* Set to mspace 0 */
		if(disable && TLSSET(p->mycache, (void *)(size_t)-1)) abort();
	}
	else if(mycache>0)
	{	/* Set to last used mspace */
		threadcache *tc=p->caches[mycache-1];
#if defined(DEBUG)
		printf("Threadcache utilisation: %lf%% in cache with %lf%% lost to other threads\n",
			100.0*tc->successes/tc->mallocs, 100.0*((double) tc->mallocs-tc->frees)/tc->mallocs);
#endif
		if(disable && TLSSET(p->mycache, (void *)(size_t)(-tc->mymspace))) abort();
		tc->frees++;
		RemoveCacheEntries(p, tc, 0);
		assert(!tc->freeInCache);
		if(disable)
		{
			tc->mymspace=-1;
			tc->threadid=0;
			CallFree(0, p->caches[mycache-1], 0);
			p->caches[mycache-1]=0;
		}
	}
}

Project: nedmalloc

NEDMALLOCNOALIASATTR void   nedfree(void *mem) THROWSPEC																		{ nedpfree((nedpool *) 0, mem); }

Project: nedmalloc

static FORCEINLINE NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void *CallMalloc(void *RESTRICT mspace, size_t size, size_t alignment, unsigned flags) THROWSPEC
{
	void *RESTRICT ret=0;
#if USE_MAGIC_HEADERS
	size_t _alignment=alignment;
	size_t *_ret=0;
	size+=alignment+3*sizeof(size_t);
	_alignment=0;
#endif
#if USE_ALLOCATOR==0
	ret=(flags & M2_ZERO_MEMORY) ? syscalloc(1, size) : sysmalloc(size);	/* magic headers takes care of alignment */
#elif USE_ALLOCATOR==1
	ret=mspace_malloc2((mstate) mspace, size, alignment, flags);
#ifndef ENABLE_FAST_HEAP_DETECTION
	if(ret)
	{
		mchunkptr p=mem2chunk(ret);
		size_t truesize=chunksize(p) - overhead_for(p);
		if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
		if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
	}
#endif
#endif
	if(!ret) return 0;
#if DEBUG
	if(flags & M2_ZERO_MEMORY)
	{
		const char *RESTRICT n;
		for(n=(const char *)ret; n<(const char *)ret+size; n++)
		{
			assert(!*n);
		}
	}
#endif
#if USE_MAGIC_HEADERS
	_ret=(size_t *) ret;
	ret=(void *)(_ret+3);
	if(alignment) ret=(void *)(((size_t) ret+alignment-1)&~(alignment-1));
	for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *)"NEDMALOC";
	_ret[0]=(size_t) mspace;
	_ret[1]=size-3*sizeof(size_t);
#endif
	return ret;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedpcalloc(nedpool *p, size_t no, size_t size) THROWSPEC
{
	size_t bytes=no*size;
	/* Avoid multiplication overflow. */
	if(size && no!=bytes/size)
		return 0;
	unsigned flags=NEDMALLOC_FORCERESERVE(p, 0, bytes);
	return nedpmalloc2(p, bytes, 0, M2_ZERO_MEMORY|flags);
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_comalloc(size_t elems, size_t *sizes, void **chunks) THROWSPEC		{ return nedpindependent_comalloc((nedpool *) 0, elems, sizes, chunks); }

Project: nedmalloc

NEDMALLOCNOALIASATTR void*  nedmalloc_internals(size_t *granularity, size_t *magic) THROWSPEC
{
#if USE_ALLOCATOR==1
	if(granularity) *granularity=mparams.granularity;
	if(magic) *magic=mparams.magic;
	return (void *) &syspool;
#else
	if(granularity) *granularity=0;
	if(magic) *magic=0;
	return 0;
#endif
}

Project: nedmalloc

size_t nedpmalloc_footprint(nedpool *p) THROWSPEC
{
	size_t ret=0;
	int n;
	if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1
		ret+=mspace_footprint(p->m[n]);
#endif
	}
	return ret;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedpindependent_calloc(nedpool *p, size_t elemsno, size_t elemsize, void **chunks) THROWSPEC
{
	void **ret;
	threadcache *tc;
	int mymspace;
	GetThreadCache(&p, &tc, &mymspace, &elemsize);
#if USE_ALLOCATOR==0
    GETMSPACE(m, p, tc, mymspace, elemsno*elemsize,
              ret=unsupported_operation("independent_calloc"));
#elif USE_ALLOCATOR==1
    GETMSPACE(m, p, tc, mymspace, elemsno*elemsize,
              ret=mspace_independent_calloc(m, elemsno, elemsize, chunks));
#endif
#if ENABLE_LOGGING
	if(ret && (ENABLE_LOGGING & LOGENTRY_POOL_MALLOC))
	{
		size_t n;
		for(n=0; n<elemsno; n++)
		{
			LogOperation(tc, p, LOGENTRY_POOL_MALLOC, mymspace, elemsize, 0, 0, M2_ZERO_MEMORY, ret[n]);
		}
	}
#endif
	return ret;
}

Project: nedmalloc

static DWORD64 __stdcall GetModBase(HANDLE hProcess, DWORD64 dwAddr) THROWSPEC
{
	DWORD64 modulebase;
	// Try to get the module base if already loaded, otherwise load the module
	modulebase=SymGetModuleBase64(hProcess, dwAddr);
	if(modulebase)
		return modulebase;
	else
	{
		MEMORY_BASIC_INFORMATION stMBI ;
		if ( 0 != VirtualQueryEx ( hProcess, (LPCVOID)(size_t)dwAddr, &stMBI, sizeof(stMBI)))
		{
			int n;
			DWORD dwPathLen=0, dwNameLen=0 ;
			TCHAR szFile[ MAX_PATH ], szModuleName[ MAX_PATH ] ;
			MODULEINFO mi={0};
			dwPathLen = GetModuleFileName ( (HMODULE) stMBI.AllocationBase , szFile, MAX_PATH );
			dwNameLen = GetModuleBaseName (hProcess, (HMODULE) stMBI.AllocationBase , szModuleName, MAX_PATH );
			for(n=dwNameLen; n>0; n--)
			{
				if(szModuleName[n]=='.')
				{
					szModuleName[n]=0;
					break;
				}
			}
			if(!GetModuleInformation(hProcess, (HMODULE) stMBI.AllocationBase, &mi, sizeof(mi)))
			{
				//fxmessage("WARNING: GetModuleInformation() returned error code %d\n", GetLastError());
			}
			if(!SymLoadModule64 ( hProcess, NULL, (PSTR)( (dwPathLen) ? szFile : 0), (PSTR)( (dwNameLen) ? szModuleName : 0),
				(DWORD64) mi.lpBaseOfDll, mi.SizeOfImage))
			{
				//fxmessage("WARNING: SymLoadModule64() returned error code %d\n", GetLastError());
			}
			//fxmessage("%s, %p, %x, %x\n", szFile, mi.lpBaseOfDll, mi.SizeOfImage, (DWORD) mi.lpBaseOfDll+mi.SizeOfImage);
			modulebase=SymGetModuleBase64(hProcess, dwAddr);
			return modulebase;
		}
	}
	return 0;
}

Project: nedmalloc

static FORCEINLINE void CallFree(void *RESTRICT mspace, void *RESTRICT mem, int isforeign) THROWSPEC
{
#if USE_MAGIC_HEADERS
	mstate oldmspace=0;
	size_t *_mem=(size_t *) mem-3, oldsize=0;
#endif
	if(isforeign)
	{
#if USE_MAGIC_HEADERS
		assert(_mem[0]!=*(size_t *) "NEDMALOC");
#endif
#if defined(DEBUG)
		printf("*** nedmalloc frees system allocated block %p\n", mem);
#endif
		sysfree(mem);
		return;
	}
#if USE_MAGIC_HEADERS
	assert(_mem[0]==*(size_t *) "NEDMALOC");
	oldmspace=(mstate) _mem[1];
	oldsize=_mem[2];
	for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
	mem=(void *)(++_mem);
#endif
#if USE_ALLOCATOR==0
	sysfree(mem);
#elif USE_ALLOCATOR==1
	mspace_free((mstate) mspace, mem);
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR void   nedpfree(nedpool *p, void *mem) THROWSPEC
{
  nedpfree2(p, mem, 0);
}

Project: nedmalloc

static NEDMALLOCNOALIASATTR mstate nedblkmstate(void *RESTRICT mem) THROWSPEC
{
	if(mem)
	{
#if USE_MAGIC_HEADERS
		size_t *_mem=(size_t *) mem-3;
		if(_mem[0]==*(size_t *) "NEDMALOC")
		{
			return (mstate) _mem[1];
		}
		else return 0;
#else
#if USE_ALLOCATOR==0
		/* Fail everything */
		return 0;
#elif USE_ALLOCATOR==1
#ifdef ENABLE_FAST_HEAP_DETECTION
#ifdef WIN32
		/*  On Windows for RELEASE both x86 and x64 the NT heap precedes each block with an eight byte header
			which looks like:
				normal: 4 bytes of size, 4 bytes of [char < 64, char < 64, char < 64 bit 0 always set, char random ]
				mmaped: 4 bytes of size  4 bytes of [zero,      zero,      0xb,                        zero        ]

			On Windows for DEBUG both x86 and x64 the preceding four bytes is always 0xfdfdfdfd (no man's land).
		*/
#pragma pack(push, 1)
		struct _HEAP_ENTRY
		{
			USHORT Size;
			USHORT PreviousSize;
			UCHAR Cookie;			/* SegmentIndex */
			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 */
			UCHAR UnusedBytes;
			UCHAR SmallTagIndex;	/* fastbin index. Always one of 0x02, 0x03, 0x04 < 0x80 */
		} *RESTRICT he=((struct _HEAP_ENTRY *) mem)-1;
#pragma pack(pop)
		unsigned int header=((unsigned int *)mem)[-1], mask1=0x8080E100, result1, mask2=0xFFFFFF06, result2;
		result1=header & mask1;	/* Positive testing for NT heap */
		result2=header & mask2;	/* Positive testing for dlmalloc */
		if(result1==0x00000100 && result2!=0x00000102)
		{	/* This is likely a NT heap block */
			return 0;
		}
#endif
#ifdef __linux__
		/* On Linux glibc uses ptmalloc2 (really dlmalloc) just as we do, but prev_foot contains rubbish
		when the preceding block is allocated because ptmalloc2 finds the local mstate by rounding the ptr
		down to the nearest megabyte. It's like dlmalloc with FOOTERS disabled. */
		mchunkptr p=mem2chunk(mem);
		mstate fm=get_mstate_for(p);
		/* If it's a ptmalloc2 block, fm is likely to be some crazy value */
		if(!is_aligned(fm)) return 0;
		if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
		if(ok_magic(fm))
			return fm;
		else
			return 0;
		if(1) { }
#endif
		else
		{
			mchunkptr p=mem2chunk(mem);
			mstate fm=get_mstate_for(p);
			assert(ok_magic(fm));	/* If this fails, someone tried to free a block twice */
			if(ok_magic(fm))
				return fm;
		}
#else
#ifdef WIN32
#ifdef _MSC_VER
		__try
#elif defined(__MINGW32__)
		__try1
#endif
#endif
		{
			/* We try to return zero here if it isn't one of our own blocks, however
			the current block annotation scheme used by dlmalloc makes it impossible
			to be absolutely sure of avoiding a segfault.

			mchunkptr->prev_foot = mem-(2*size_t) = mstate ^ mparams.magic for PRECEDING block;
			mchunkptr->head      = mem-(1*size_t) = 8 multiple size of this block with bottom three bits = FLAG_BITS
			    FLAG_BITS = bit 0 is CINUSE (currently in use unless is mmap), bit 1 is PINUSE (previous block currently
				            in use unless mmap), bit 2 is UNUSED and currently is always zero.
			*/
			register void *RESTRICT leastusedaddress_=leastusedaddress;		/* Cache these to avoid register reloading */
			register size_t largestusedblock_=largestusedblock;
			if(!is_aligned(mem)) return 0;		/* Would fail very rarely as all allocators return aligned blocks */
			if(mem<leastusedaddress_) return 0;	/* Simple but effective */
			{
				mchunkptr p=mem2chunk(mem);
				mstate fm=0;
				int ismmapped=is_mmapped(p);
				if((!ismmapped && !is_inuse(p)) || (p->head & FLAG4_BIT)) return 0;
				/* Reduced uncertainty by 0.5^2 = 25.0% */
				/* size should never exceed largestusedblock */
				if(chunksize(p)-overhead_for(p)>largestusedblock_) return 0;
				/* Reduced uncertainty by a minimum of 0.5^3 = 12.5%, maximum 0.5^16 = 0.0015% */
				/* Having sanity checked prev_foot and head, check next block */
				if(!ismmapped && (!next_pinuse(p) || (next_chunk(p)->head & FLAG4_BIT))) return 0;
				/* Reduced uncertainty by 0.5^5 = 3.13% or 0.5^18 = 0.00038% */
#if 0
				/* If previous block is free, check that its next block pointer equals us */
				if(!ismmapped && !pinuse(p))
					if(next_chunk(prev_chunk(p))!=p) return 0;
				/* We could start comparing prev_foot's for similarity but it starts getting slow. */
#endif
				fm = get_mstate_for(p);
				if(!is_aligned(fm) || (void *)fm<leastusedaddress_) return 0;
#if 0
				/* See if mem is lower in memory than mem */
				if((size_t)mem-(size_t)fm>=(size_t)1<<(SIZE_T_BITSIZE-1)) return 0;
#endif
				assert(ok_magic(fm));	/* If this fails, someone tried to free a block twice */
				if(ok_magic(fm))
					return fm;
			}
		}
#ifdef WIN32
#ifdef _MSC_VER
		__except(1) { }
#elif defined(__MINGW32__)
		__except1(1) { }
#endif
#endif
#endif
#endif
#endif
	}
	return 0;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmalloc2(size_t size, size_t alignment, unsigned flags) THROWSPEC				{ return nedpmalloc2((nedpool *) 0, size, alignment, flags); }

Project: nedmalloc

int    nedpmallopt(nedpool *p, int parno, int value) THROWSPEC
{
#if USE_ALLOCATOR==1
	return mspace_mallopt(parno, value);
#else
	return 0;
#endif
}

Project: nedmalloc

size_t nedflushlogs(nedpool *p, char *filepath) THROWSPEC
{
	size_t count=0;
	if(!p)
	{
		p=&syspool;
		if(!syspool.threads) InitPool(&syspool, 0, -1);
	}
	if(p->caches)
	{
		threadcache *tc;
		int n;
#if ENABLE_LOGGING
		int haslogentries=0;
#endif
		for(n=0; n<THREADCACHEMAXCACHES; n++)
		{
			if((tc=p->caches[n]))
			{
				count+=tc->freeInCache;
				tc->frees++;
				RemoveCacheEntries(p, tc, 0);
				assert(!tc->freeInCache);
#if ENABLE_LOGGING
				haslogentries|=!!tc->logentries;
#endif
			}
		}
#if ENABLE_LOGGING
		if(haslogentries)
		{
			char buffer[MAX_PATH]=NEDMALLOC_LOGFILE;
			FILE *oh;
			fpos_t pos1, pos2;
			if(!filepath) filepath=buffer;
			oh=fopen(filepath, "r+");
			while(!oh)
			{
				char *bptr;
				if((oh=fopen(filepath, "w"))) break;
				if(ENOSPC==errno) break;
				bptr=strrchr(filepath, '.');
				if(bptr-filepath>=MAX_PATH-6) abort();
				memcpy(bptr, "!.csv", 6);
			}
			if(oh)
			{
				fgetpos(oh, &pos1);
				fseek(oh, 0, SEEK_END);
				fgetpos(oh, &pos2);
				if(pos1==pos2)
					fprintf(oh, "Timestamp, Pool, Operation, MSpace, Size, Block, Alignment, Flags, Returned,\"Stack Backtrace\"\n");
				for(n=0; n<THREADCACHEMAXCACHES; n++)
				{
					if((tc=p->caches[n]) && tc->logentries)
					{
						logentry *le;
						for(le=tc->logentries; le<tc->logentriesptr; le++)
						{
							const char *LogEntryTypeString=LogEntryTypeStrings[size2binidx(((size_t)le->type)<<4)];
							char stackbacktrace[16384]="?";
#if NEDMALLOC_STACKBACKTRACEDEPTH
							char *sbtp=stackbacktrace;
							int i;
							for(i=0; i<NEDMALLOC_STACKBACKTRACEDEPTH && le->stack[i].pc; i++)
							{
								sbtp+=sprintf(sbtp, "0x%p:%s:%s (%s:%u),",
									le->stack[i].pc, le->stack[i].module, le->stack[i].functname, le->stack[i].file, le->stack[i].lineno);
								if(sbtp>=stackbacktrace+sizeof(stackbacktrace)) abort();
							}
							if(NEDMALLOC_STACKBACKTRACEDEPTH==i)
								strcpy(sbtp, "<backtrace may continue ...>");
							else
								strcpy(sbtp, "<backtrace ends>");
							if(strchr(sbtp, 0)>=stackbacktrace+sizeof(stackbacktrace)) abort();
#endif
							fprintf(oh, "%llu, 0x%p, %s, %d, %Iu, 0x%p, %Iu, 0x%x, 0x%p,\"%s\"\n",
								le->timestamp, le->np, LogEntryTypeString, le->mspace, le->size, le->mem, le->alignment, le->flags, le->returned, stackbacktrace);
						}
						CallFree(0, tc->logentries, 0);
						tc->logentries=tc->logentriesptr=tc->logentriesend=0;
					}
				}
				fclose(oh);
			}
		}
#endif
	}
	return count;
}

Project: nedmalloc

static void tcfullsanitycheck(threadcache *tc) THROWSPEC
{
	threadcacheblk *RESTRICT *RESTRICT tcbptr=tc->bins;
	int n;
	for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
	{
		threadcacheblk *RESTRICT b, *RESTRICT ob=0;
		tcsanitycheck(tcbptr);
		for(b=tcbptr[0]; b; ob=b, b=b->next)
		{
			assert(b->isforeign || nedblkmstate(b));
			assert(nedblksize(0, b, 0)>=sizeof(threadcacheblk));
			assert(*(unsigned int *) "NEDN"==b->magic);
			assert(!ob || ob->next==b);
			assert(!ob || b->prev==ob);
		}
	}
}

Project: nedmalloc

static FORCEINLINE NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void *CallRealloc(void *RESTRICT mspace, void *RESTRICT mem, int isforeign, size_t oldsize, size_t newsize, size_t alignment, unsigned flags) THROWSPEC
{
	void *RESTRICT ret=0;
#if USE_MAGIC_HEADERS
	mstate oldmspace=0;
	size_t *_ret=0, *_mem=(size_t *) mem-3;
#endif
	if(isforeign)
	{	/* Transfer */
#if USE_MAGIC_HEADERS
		assert(_mem[0]!=*(size_t *) "NEDMALOC");
#endif
		if((ret=CallMalloc(mspace, newsize, alignment, flags)))
		{
#if defined(DEBUG)
			printf("*** nedmalloc frees system allocated block %p\n", mem);
#endif
			memcpy(ret, mem, oldsize<newsize ? oldsize : newsize);
			sysfree(mem);
		}
		return ret;
	}
#if USE_MAGIC_HEADERS
	assert(_mem[0]==*(size_t *) "NEDMALOC");
	newsize+=3*sizeof(size_t);
	oldmspace=(mstate) _mem[1];
	assert(oldsize>=_mem[2]);
	for(; *_mem==*(size_t *) "NEDMALOC"; *_mem--=*(size_t *) "nedmaloc");
	mem=(void *)(++_mem);
#endif
#if USE_ALLOCATOR==0
	ret=sysrealloc(mem, newsize);
#elif USE_ALLOCATOR==1
	ret=mspace_realloc2((mstate) mspace, mem, newsize, alignment, flags);
#ifndef ENABLE_FAST_HEAP_DETECTION
	if(ret)
	{
		mchunkptr p=mem2chunk(ret);
		size_t truesize=chunksize(p) - overhead_for(p);
		if(!leastusedaddress || (void *)((mstate) mspace)->least_addr<leastusedaddress) leastusedaddress=(void *)((mstate) mspace)->least_addr;
		if(!largestusedblock || truesize>largestusedblock) largestusedblock=(truesize+mparams.page_size) & ~(mparams.page_size-1);
	}
#endif
#endif
	if(!ret)
	{	/* Put it back the way it was */
#if USE_MAGIC_HEADERS
		for(; *_mem==0; *_mem++=*(size_t *) "NEDMALOC");
#endif
		return 0;
	}
#if USE_MAGIC_HEADERS
	_ret=(size_t *) ret;
	ret=(void *)(_ret+3);
	for(; _ret<(size_t *)ret-2; _ret++) *_ret=*(size_t *) "NEDMALOC";
	_ret[0]=(size_t) mspace;
	_ret[1]=newsize-3*sizeof(size_t);
#endif
	return ret;
}

Project: nedmalloc

static FORCEINLINE logentry *LogOperation(threadcache *tc, nedpool *np, LogEntryType type, int mspace, size_t size, void *mem, size_t alignment, unsigned flags, void *returned) THROWSPEC
{
#if ENABLE_LOGGING
	if(tc->logentries && NEDMALLOC_TESTLOGENTRY(tc, np, type, mspace, size, mem, alignment, flags, returned))
	{
		logentry *le;
		if(tc->logentriesptr==tc->logentriesend)
		{
			mchunkptr cp=mem2chunk(tc->logentries);
			size_t logentrieslen=chunksize(cp)-overhead_for(cp);
			le=(logentry *) CallRealloc(0, tc->logentries, 0, logentrieslen, (logentrieslen*3)/2, 0, M2_ZERO_MEMORY|M2_ALWAYS_MMAP|M2_RESERVE_MULT(8));
			if(!le) return 0;
			tc->logentriesptr=le+(tc->logentriesptr-tc->logentries);
			tc->logentries=le;
			cp=mem2chunk(tc->logentries);
			logentrieslen=(chunksize(cp)-overhead_for(cp))/sizeof(logentry);
			tc->logentriesend=tc->logentries+logentrieslen;
		}
		le=tc->logentriesptr++;
		assert(le+1<=tc->logentriesend);
		le->timestamp=GetTimestamp();
		le->np=np;
		le->type=type;
		le->mspace=mspace;
		le->size=size;
		le->mem=mem;
		le->alignment=alignment;
		le->flags=flags;
		le->returned=returned;
#if NEDMALLOC_STACKBACKTRACEDEPTH
		DoStackWalk(le);
#endif
		return le;
	}
#endif
	return 0;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR size_t nedmemsize(void *RESTRICT mem) THROWSPEC { return nedblksize(0, mem, 0); }

Project: nedmalloc

static NOINLINE void GetThreadCache_cold1(nedpool *RESTRICT *RESTRICT p) THROWSPEC
{
	*p=&syspool;
	if(!syspool.threads) InitPool(&syspool, 0, -1);
}

Project: nedmalloc

nedpool **nedpoollist() THROWSPEC
{
	nedpool **ret=0;
	if(poollist)
	{
#if USE_LOCKS
		ACQUIRE_LOCK(&poollistlock);
#endif
		if(!(ret=(nedpool **) nedmalloc((poollist->length+1)*sizeof(nedpool *)))) goto badexit;
		memcpy(ret, poollist->list, (poollist->length+1)*sizeof(nedpool *));
badexit:
		{
#if USE_LOCKS
			RELEASE_LOCK(&poollistlock);
#endif
		}
	}
	return ret;
}

Project: nedmalloc

static void *unsupported_operation(const char *opname) THROWSPEC
{
	fprintf(stderr, "nedmalloc: The operation %s is not supported under this build configuration\n", opname);
	abort();
	return 0;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR void   nedpfree2(nedpool *p, void *mem, unsigned flags) THROWSPEC
{	/* Frees always happen in the mspace they happened in, so skip
	locking the preferred mspace for this thread */
	threadcache *tc;
	int mymspace, isforeign=1;
	size_t memsize;
	if(!mem)
	{	/* If you tried this on FreeBSD you'd be sorry! */
#ifdef DEBUG
		fprintf(stderr, "nedmalloc: WARNING nedpfree() called with zero. This is not portable behaviour!\n");
#endif
		return;
	}
	memsize=nedblksize(&isforeign, mem, flags);
	assert(memsize);
	if(!memsize)
	{
		fprintf(stderr, "nedmalloc: nedpfree() called with a block not created by nedmalloc!\n");
		abort();
	}
	GetThreadCache(&p, &tc, &mymspace, 0);
#if THREADCACHEMAX
	if(mem && tc && !isforeign && memsize>=sizeof(threadcacheblk) && memsize<=(THREADCACHEMAX+CHUNK_OVERHEAD))
	{
		threadcache_free(p, tc, mymspace, mem, memsize, isforeign);
		LogOperation(tc, p, LOGENTRY_THREADCACHE_FREE, mymspace, memsize, mem, 0, 0, 0);
	}
	else
#endif
	{
		CallFree(0, mem, isforeign);
		LogOperation(tc, p, LOGENTRY_POOL_FREE, mymspace, memsize, mem, 0, 0, 0);
	}
	LogOperation(tc, p, LOGENTRY_FREE, mymspace, memsize, mem, 0, 0, 0);
}

Project: nedmalloc

static NOINLINE void RemoveCacheEntries(nedpool *RESTRICT p, threadcache *RESTRICT tc, unsigned int age) THROWSPEC
{
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
	if(tc->freeInCache)
	{
		threadcacheblk *RESTRICT *RESTRICT tcbptr=tc->bins;
		int n;
		for(n=0; n<=THREADCACHEMAXBINS; n++, tcbptr+=2)
		{
			threadcacheblk *RESTRICT *RESTRICT tcb=tcbptr+1;		/* come from oldest end of list */
			/*tcsanitycheck(tcbptr);*/
			for(; *tcb && tc->frees-(*tcb)->lastUsed>=age; )
			{
				threadcacheblk *RESTRICT f=*tcb;
				size_t blksize=f->size; /*nedblksize(f);*/
				assert(blksize<=nedblksize(0, f, 0));
				assert(blksize);
#ifdef FULLSANITYCHECKS
				assert(*(unsigned int *) "NEDN"==(*tcb)->magic);
#endif
				*tcb=(*tcb)->prev;
				if(*tcb)
					(*tcb)->next=0;
				else
					*tcbptr=0;
				tc->freeInCache-=blksize;
				assert((long) tc->freeInCache>=0);
				CallFree(0, f, f->isforeign);
				/*tcsanitycheck(tcbptr);*/
				LogOperation(tc, p, LOGENTRY_THREADCACHE_CLEAN, age, blksize, f, 0, 0, 0);
			}
		}
	}
#ifdef FULLSANITYCHECKS
	tcfullsanitycheck(tc);
#endif
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedmemalign(size_t alignment, size_t bytes) THROWSPEC								{ return nedpmemalign((nedpool *) 0, alignment, bytes); }

Project: nedmalloc
File: nedmalloc.c

static LPVOID ChkedTlsGetValue(DWORD idx)
{
	LPVOID ret=TlsGetValue(idx);
	assert(S_OK==GetLastError());
	return ret;
}

Project: nedmalloc

NEDMALLOCNOALIASATTR void nedsetvalue(void *v) THROWSPEC																		{ nedpsetvalue((nedpool *) 0, v); }

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedcalloc(size_t no, size_t size) THROWSPEC										{ return nedpcalloc((nedpool *) 0, no, size); }

Project: nedmalloc

NEDMALLOCNOALIASATTR int    nedmallopt(int parno, int value) THROWSPEC															{ return nedpmallopt((nedpool *) 0, parno, value); }

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void **nedindependent_calloc(size_t elemsno, size_t elemsize, void **chunks) THROWSPEC	{ return nedpindependent_calloc((nedpool *) 0, elemsno, elemsize, chunks); }

Project: nedmalloc

static int ExceptionFilter(unsigned int code, struct _EXCEPTION_POINTERS *ep, CONTEXT *ct) THROWSPEC
{
	*ct=*ep->ContextRecord;
	return EXCEPTION_EXECUTE_HANDLER;
}

Project: nedmalloc

static void DoStackWalk(logentry *p) THROWSPEC
{
	int i,i2;
	HANDLE mythread=(HANDLE) GetCurrentThread();
	STACKFRAME64 sf={ 0 };
	CONTEXT ct={ 0 };
	if(!sym_myprocess)
	{
		DWORD symopts;
		DuplicateHandle(GetCurrentProcess(), GetCurrentProcess(), GetCurrentProcess(), &sym_myprocess, 0, FALSE, DUPLICATE_SAME_ACCESS);
		symopts=SymGetOptions();
		SymSetOptions(symopts /*| SYMOPT_DEFERRED_LOADS*/ | SYMOPT_LOAD_LINES);
		SymInitialize(sym_myprocess, NULL, TRUE);
		atexit(DeinitSym);
	}
	ct.ContextFlags=CONTEXT_FULL;

	// Use RtlCaptureContext() if we have it as it saves an exception throw
	if((VOID (WINAPI *)(PCONTEXT)) -1==RtlCaptureContextAddr)
		RtlCaptureContextAddr=(VOID (WINAPI *)(PCONTEXT)) GetProcAddress(GetModuleHandle(L"kernel32"), "RtlCaptureContext");
	if(RtlCaptureContextAddr)
		RtlCaptureContextAddr(&ct);
	else
	{	// This is nasty, but it works
		__try
		{
			int *foo=0;
			*foo=78;
		}
		__except (ExceptionFilter(GetExceptionCode(), GetExceptionInformation(), &ct))
		{
		}
	}

	sf.AddrPC.Mode=sf.AddrStack.Mode=sf.AddrFrame.Mode=AddrModeFlat;
#if !(defined(_M_AMD64) || defined(_M_X64))
	sf.AddrPC.Offset   =ct.Eip;
	sf.AddrStack.Offset=ct.Esp;
	sf.AddrFrame.Offset=ct.Ebp;
#else
	sf.AddrPC.Offset   =ct.Rip;
	sf.AddrStack.Offset=ct.Rsp;
	sf.AddrFrame.Offset=ct.Rbp; // maybe Rdi?
#endif
	for(i2=0; i2<NEDMALLOC_STACKBACKTRACEDEPTH; i2++)
	{
		IMAGEHLP_MODULE64 ihm={ sizeof(IMAGEHLP_MODULE64) };
		char temp[MAX_PATH+sizeof(IMAGEHLP_SYMBOL64)];
		IMAGEHLP_SYMBOL64 *ihs;
		IMAGEHLP_LINE64 ihl={ sizeof(IMAGEHLP_LINE64) };
		DWORD64 offset;
		if(!StackWalk64(
#if !(defined(_M_AMD64) || defined(_M_X64))
			IMAGE_FILE_MACHINE_I386,
#else
			IMAGE_FILE_MACHINE_AMD64,
#endif
			sym_myprocess, mythread, &sf, &ct, NULL, SymFunctionTableAccess64, GetModBase, NULL))
			break;
		if(0==sf.AddrPC.Offset)
			break;
		i=i2;
		if(i)	// Skip first entry relating to this function
		{
			DWORD lineoffset=0;
			p->stack[i-1].pc=(void *)(size_t) sf.AddrPC.Offset;
			if(SymGetModuleInfo64(sym_myprocess, sf.AddrPC.Offset, &ihm))
			{
				char *leaf;
				leaf=strrchr(ihm.ImageName, '\\');
				if(!leaf) leaf=ihm.ImageName-1;
				COPY_STRING(p->stack[i-1].module, leaf+1, sizeof(p->stack[i-1].module));
			}
			else strcpy(p->stack[i-1].module, "<unknown>");
			//fxmessage("WARNING: SymGetModuleInfo64() returned error code %d\n", GetLastError());
			memset(temp, 0, MAX_PATH+sizeof(IMAGEHLP_SYMBOL64));
			ihs=(IMAGEHLP_SYMBOL64 *) temp;
			ihs->SizeOfStruct=sizeof(IMAGEHLP_SYMBOL64);
			ihs->Address=sf.AddrPC.Offset;
			ihs->MaxNameLength=MAX_PATH;

			if(SymGetSymFromAddr64(sym_myprocess, sf.AddrPC.Offset, &offset, ihs))
			{
				COPY_STRING(p->stack[i-1].functname, ihs->Name, sizeof(p->stack[i-1].functname));
				if(strlen(p->stack[i-1].functname)<sizeof(p->stack[i-1].functname)-8)
				{
					sprintf(strchr(p->stack[i-1].functname, 0), " +0x%x", offset);
				}
			}
			else
				strcpy(p->stack[i-1].functname, "<unknown>");
			if(SymGetLineFromAddr64(sym_myprocess, sf.AddrPC.Offset, &lineoffset, &ihl))
			{
				char *leaf;
				p->stack[i-1].lineno=ihl.LineNumber;

				leaf=strrchr(ihl.FileName, '\\');
				if(!leaf) leaf=ihl.FileName-1;
				COPY_STRING(p->stack[i-1].file, leaf+1, sizeof(p->stack[i-1].file));
			}
			else
				strcpy(p->stack[i-1].file, "<unknown>");
		}
	}
}

Project: nedmalloc

static NOINLINE void GetThreadCache_cold2(nedpool *RESTRICT *RESTRICT p, threadcache *RESTRICT *RESTRICT tc, int *RESTRICT mymspace, int mycache) THROWSPEC
{
	if(!mycache)
	{	/* Need to allocate a new cache */
		*tc=AllocCache(*p);
		if(!*tc)
		{	/* Disable */
			if(TLSSET((*p)->mycache, (void *)(size_t)-1)) abort();
			*mymspace=0;
		}
		else
			*mymspace=(*tc)->mymspace;
	}
	else
	{	/* Cache disabled, but we do have an assigned thread pool */
		*tc=0;
		*mymspace=-mycache-1;
	}
}

Project: nedmalloc

NEDMALLOCNOALIASATTR NEDMALLOCPTRATTR void * nedprealloc2(nedpool *p, void *mem, size_t size, size_t alignment, unsigned flags) THROWSPEC
{
	void *ret=0;
	threadcache *tc;
	int mymspace, isforeign=1;
	size_t memsize;
	if(!mem) return nedpmalloc2(p, size, alignment, flags);
#if REALLOC_ZERO_BYTES_FREES
	if(!size)
	{
		nedpfree2(p, mem, flags);
		return 0;
	}
#endif
	memsize=nedblksize(&isforeign, mem, flags);
	assert(memsize);
	if(!memsize)
	{
		fprintf(stderr, "nedmalloc: nedprealloc() called with a block not created by nedmalloc!\n");
		abort();
	}
	else if(size<=memsize && memsize-size<
#ifdef DEBUG
		32
#else
		1024
#endif
		)		/* If realloc size is within 1Kb smaller than existing, noop it */
		return mem;
	GetThreadCache(&p, &tc, &mymspace, &size);
#if THREADCACHEMAX
	if(alignment<=MALLOC_ALIGNMENT && !(flags & NM_FLAGS_MASK) && tc && size && size<=THREADCACHEMAX)
	{	/* Use the thread cache */
		if((ret=threadcache_malloc(p, tc, &size)))
		{
			size_t tocopy=memsize<size ? memsize : size;
			memcpy(ret, mem, tocopy);
			if((flags & M2_ZERO_MEMORY) && size>memsize)
				memset((void *)((size_t)ret+memsize), 0, size-memsize);
			LogOperation(tc, p, LOGENTRY_THREADCACHE_MALLOC, mymspace, size, mem, alignment, flags, ret);
			if(!isforeign && memsize>=sizeof(threadcacheblk) && memsize<=(THREADCACHEMAX+CHUNK_OVERHEAD))
			{
				threadcache_free(p, tc, mymspace, mem, memsize, isforeign);
				LogOperation(tc, p, LOGENTRY_THREADCACHE_FREE, mymspace, memsize, mem, 0, 0, 0);
			}
			else
			{
				CallFree(0, mem, isforeign);
				LogOperation(tc, p, LOGENTRY_POOL_FREE, mymspace, memsize, mem, 0, 0, 0);
			}
		}
	}
#endif
	if(!ret)
	{	/* Reallocs always happen in the mspace they happened in, so skip
		locking the preferred mspace for this thread */
		ret=CallRealloc(p->m[mymspace], mem, isforeign, memsize, size, alignment, flags);
		if(ret)
			LogOperation(tc, p, LOGENTRY_POOL_REALLOC, mymspace, size, mem, alignment, flags, ret);
	}
	LogOperation(tc, p, LOGENTRY_REALLOC, mymspace, size, mem, alignment, flags, ret);
	return ret;
}

Project: nedmalloc

int    nedpmalloc_trim(nedpool *p, size_t pad) THROWSPEC
{
	int n, ret=0;
	if(!p) { p=&syspool; if(!syspool.threads) InitPool(&syspool, 0, -1); }
	for(n=0; p->m[n]; n++)
	{
#if USE_ALLOCATOR==1
		ret+=mspace_trim(p->m[n], pad);
#endif
	}
	return ret;
}

Project: nedmalloc

static FORCEINLINE mstate GetMSpace(nedpool *RESTRICT p, threadcache *RESTRICT tc, int mymspace, size_t size) THROWSPEC
{	/* Returns a locked and ready for use mspace */
	mstate m=p->m[mymspace];
	assert(m);
#if USE_LOCKS && USE_ALLOCATOR==1
	if(!TRY_LOCK(&p->m[mymspace]->mutex)) m=FindMSpace(p, tc, &mymspace, size);
	/*assert(IS_LOCKED(&p->m[mymspace]->mutex));*/
#endif
	return m;
}