1 #include "SSH.h"
2 
3 namespace Upp {
4 
5 #define MLOG(x)  //  LOG(x)
6 
7 #ifdef UPP_HEAP
8 
9 static std::atomic<int64> UPP_SSH_alloc;
10 
ssh_malloc(size_t size,void ** abstract)11 static void *ssh_malloc(size_t size, void **abstract)
12 {
13 	MLOG("Alloc " << size);
14 	size_t alloc = size + sizeof(int64);
15 	int64 *aptr = (int64 *)MemoryAllocSz(alloc);
16 	*aptr++ = (int64)alloc;
17 	UPP_SSH_alloc += alloc;
18 	MLOG("UPP_SSH_MALLOC(" << (int64)size << ", alloc " << alloc << ") -> " << FormatIntHex(aptr) << ", total = " << (int64) UPP_SSH_alloc);
19 	return aptr;
20 }
21 
ssh_free(void * ptr,void ** abstract)22 static void ssh_free(void *ptr, void **abstract)
23 {
24 	if(!ptr)
25 		return;
26 	int64 *aptr = (int64 *)ptr - 1;
27 	UPP_SSH_alloc -= *aptr;
28 	MLOG("UPP_SSH_FREE(" << ptr << ", alloc " << *aptr << "), total = " << (int64) UPP_SSH_alloc);
29 	MemoryFree(aptr);
30 }
31 
ssh_realloc(void * ptr,size_t size,void ** abstract)32 static void *ssh_realloc(void *ptr, size_t size, void** abstract)
33 {
34 	if(!ptr)
35 		return NULL;
36 	int64 *aptr = (int64 *)ptr - 1;
37 	if((int64)(size + sizeof(int64)) <= *aptr) {
38 		MLOG("UPP_SSH_REALLOC(" << ptr << ", " << (int64)size << ", alloc " << *aptr << ") -> keep same block");
39 		return ptr;
40 	}
41 	size_t newalloc = size + sizeof(int64);
42 	int64 *newaptr = (int64 *)MemoryAllocSz(newalloc);
43 	if(!newaptr) {
44 		MLOG("UPP_SSH_REALLOC(" << ptr << ", " << (int64)size << ", alloc " << newalloc << ") -> fail");
45 		return NULL;
46 	}
47 	*newaptr++ = newalloc;
48 	memcpy(newaptr, ptr, min<int>((int)(*aptr - sizeof(int64)), (int)size));
49 	UPP_SSH_alloc += newalloc - *aptr;
50 	MLOG("UPP_SSH_REALLOC(" << ptr << ", " << (int64)size << ", alloc " << newalloc << ") -> "
51 		<< FormatIntHex(newaptr) << ", total = " << (int64) UPP_SSH_alloc);
52 	MemoryFree(aptr);
53 	return newaptr;
54 }
55 
56 #endif
57 }