From 9b1cdba106790ce70ebbb163c1d34dd14c22c5be Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 13 Jan 2024 23:30:14 +1100 Subject: [PATCH 001/128] Added logs --- libpsn00b/libc/malloc.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index d3425d0c..4d6dbefa 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -85,8 +85,10 @@ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { for (; prev; prev = prev->next) { if (prev->next) { uintptr_t next_bot = (uintptr_t) prev->next; + printf("[FindFit] Bottom of next block: %p\n", (void*)next_bot); next_bot -= (uintptr_t) prev->ptr + prev->size; - + printf("[FindFit] Offset to free block: %p\n", (void*)prev->ptr + prev->size); + printf("[FindFit] Size of free block: %p\n", next_bot); if (next_bot >= size) return prev; } From 9d0bd9ffc1d5fc89232653e9c0255c8c2558115d Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 13 Jan 2024 23:53:48 +1100 Subject: [PATCH 002/128] Added logged fix --- libpsn00b/libc/malloc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 4d6dbefa..74a50870 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -199,7 +199,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // New memory block shorter? if (prev->size >= _size) { TrackHeapUsage(size - prev->size); - prev->size = _size; + prev->size = _size - sizeof(BlockHeader); if (!prev->next) sbrk((ptr - sbrk(0)) + _size); @@ -214,14 +214,14 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { return 0; TrackHeapUsage(size - prev->size); - prev->size = _size; + prev->size = _size - sizeof(BlockHeader); return ptr; } // Do we have free memory after it? if (((prev->next)->ptr - ptr) > _size) { TrackHeapUsage(size - prev->size); - prev->size = _size; + prev->size = _size - sizeof(BlockHeader); return ptr; } From 56d7f5305924a50e99e4a1963b87e9a5790a6340 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sun, 14 Jan 2024 00:02:24 +1100 Subject: [PATCH 003/128] Removed logs --- libpsn00b/libc/malloc.c | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 74a50870..ed12e0bb 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -85,10 +85,8 @@ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { for (; prev; prev = prev->next) { if (prev->next) { uintptr_t next_bot = (uintptr_t) prev->next; - printf("[FindFit] Bottom of next block: %p\n", (void*)next_bot); next_bot -= (uintptr_t) prev->ptr + prev->size; - printf("[FindFit] Offset to free block: %p\n", (void*)prev->ptr + prev->size); - printf("[FindFit] Size of free block: %p\n", next_bot); + if (next_bot >= size) return prev; } From 97472875d5cd1cb76260788c1ad8134dc44a6cd4 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 00:17:28 +1100 Subject: [PATCH 004/128] Fixed size extend check in realloc --- libpsn00b/libc/malloc.c | 422 ++++++++++++++++++++-------------------- 1 file changed, 211 insertions(+), 211 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index ed12e0bb..06f70755 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -17,263 +17,263 @@ #include #include -#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) +#define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) /* Private types */ typedef struct _BlockHeader { - struct _BlockHeader *prev, *next; - void *ptr; - size_t size; + struct _BlockHeader *prev, *next; + void *ptr; + size_t size; } BlockHeader; /* Internal globals */ -static void *_heap_start, *_heap_end, *_heap_limit; -static size_t _heap_alloc, _heap_alloc_max; +static void *_heap_start, *_heap_end, *_heap_limit; +static size_t _heap_alloc, _heap_alloc_max; -static void *_alloc_start; -static BlockHeader *_alloc_head, *_alloc_tail; +static void *_alloc_start; +static BlockHeader *_alloc_head, *_alloc_tail; /* Heap management API */ __attribute__((weak)) void InitHeap(void *addr, size_t size) { - _heap_start = addr; - _heap_end = addr; - _heap_limit = (void *) ((uintptr_t) addr + size); + _heap_start = addr; + _heap_end = addr; + _heap_limit = (void *)((uintptr_t)addr + size); - _heap_alloc = 0; - _heap_alloc_max = 0; + _heap_alloc = 0; + _heap_alloc_max = 0; - _alloc_start = addr; - _alloc_head = 0; - _alloc_tail = 0; + _alloc_start = addr; + _alloc_head = 0; + _alloc_tail = 0; } __attribute__((weak)) void *sbrk(ptrdiff_t incr) { - void *old_end = _heap_end; - void *new_end = (void *) _align((uintptr_t) old_end + incr, 8); + void *old_end = _heap_end; + void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); - if (new_end > _heap_limit) - return 0; + if (new_end > _heap_limit) + return 0; - _heap_end = new_end; - return old_end; + _heap_end = new_end; + return old_end; } __attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { - _heap_alloc += alloc_incr; + _heap_alloc += alloc_incr; - if (_heap_alloc > _heap_alloc_max) - _heap_alloc_max = _heap_alloc; + if (_heap_alloc > _heap_alloc_max) + _heap_alloc_max = _heap_alloc; } __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { - usage->total = _heap_limit - _heap_start; - usage->heap = _heap_end - _heap_start; - usage->stack = _heap_limit - _heap_end; + usage->total = _heap_limit - _heap_start; + usage->heap = _heap_end - _heap_start; + usage->stack = _heap_limit - _heap_end; - usage->alloc = _heap_alloc; - usage->alloc_max = _heap_alloc_max; + usage->alloc = _heap_alloc; + usage->alloc_max = _heap_alloc_max; } /* Memory allocator */ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { - BlockHeader *prev = head; + BlockHeader *prev = head; - for (; prev; prev = prev->next) { - if (prev->next) { - uintptr_t next_bot = (uintptr_t) prev->next; - next_bot -= (uintptr_t) prev->ptr + prev->size; + for (; prev; prev = prev->next) { + if (prev->next) { + uintptr_t next_bot = (uintptr_t)prev->next; + next_bot -= (uintptr_t)prev->ptr + prev->size; - if (next_bot >= size) - return prev; - } - } + if (next_bot >= size) + return prev; + } + } - return prev; + return prev; } __attribute__((weak)) void *malloc(size_t size) { - if (!size) - return 0; - - size_t _size = _align(size + sizeof(BlockHeader), 8); - - // Nothing's initialized yet? Let's just initialize the bottom of our heap, - // flag it as allocated. - if (!_alloc_head) { - //if (!_alloc_start) - //_alloc_start = sbrk(0); - - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = 0; - - _alloc_head = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; - } - - // We *may* have the bottom of our heap that has shifted, because of a free. - // So let's check first if we have free space there, because I'm nervous - // about having an incomplete data structure. - if (((uintptr_t) _alloc_start + _size) < ((uintptr_t) _alloc_head)) { - BlockHeader *new = (BlockHeader *) _alloc_start; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = _alloc_head; - - _alloc_head->prev = new; - _alloc_head = new; - - TrackHeapUsage(size); - return ptr; - } - - // No luck at the beginning of the heap, let's walk the heap to find a fit. - BlockHeader *prev = _find_fit(_alloc_head, _size); - if (prev) { - BlockHeader *new = (BlockHeader *) ((uintptr_t) prev->ptr + prev->size); - - void *ptr = (void *)((uintptr_t) new + sizeof(BlockHeader)); - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = prev; - new->next = prev->next; - - (new->next)->prev = new; - prev->next = new; - - TrackHeapUsage(size); - return ptr; - } - - // Time to extend the size of the heap. - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = _alloc_tail; - new->next = 0; - - _alloc_tail->next = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; + if (!size) + return 0; + + size_t _size = _align(size + sizeof(BlockHeader), 8); + + // Nothing's initialized yet? Let's just initialize the bottom of our heap, + // flag it as allocated. + if (!_alloc_head) { + // if (!_alloc_start) + //_alloc_start = sbrk(0); + + BlockHeader *new = (BlockHeader *)sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = 0; + + _alloc_head = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; + } + + // We *may* have the bottom of our heap that has shifted, because of a free. + // So let's check first if we have free space there, because I'm nervous + // about having an incomplete data structure. + if (((uintptr_t)_alloc_start + _size) < ((uintptr_t)_alloc_head)) { + BlockHeader *new = (BlockHeader *)_alloc_start; + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = _alloc_head; + + _alloc_head->prev = new; + _alloc_head = new; + + TrackHeapUsage(size); + return ptr; + } + + // No luck at the beginning of the heap, let's walk the heap to find a fit. + BlockHeader *prev = _find_fit(_alloc_head, _size); + if (prev) { + BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); + + void *ptr = (void*)&new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = prev; + new->next = prev->next; + + (new->next)->prev = new; + prev->next = new; + + TrackHeapUsage(size); + return ptr; + } + + // Time to extend the size of the heap. + BlockHeader *new = (BlockHeader *)sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = _alloc_tail; + new->next = 0; + + _alloc_tail->next = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; } __attribute__((weak)) void *calloc(size_t num, size_t size) { - return malloc(num * size); + return malloc(num * size); } __attribute__((weak)) void *realloc(void *ptr, size_t size) { - if (!size) { - free(ptr); - return 0; - } - if (!ptr) - return malloc(size); - - size_t _size = _align(size + sizeof(BlockHeader), 8); - BlockHeader *prev = (BlockHeader *) ((uintptr_t) ptr - sizeof(BlockHeader)); - - // New memory block shorter? - if (prev->size >= _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - - if (!prev->next) - sbrk((ptr - sbrk(0)) + _size); - - return ptr; - } - - // New memory block larger; is it the last one? - if (!prev->next) { - void *new = sbrk(_size - prev->size); - if (!new) - return 0; - - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // Do we have free memory after it? - if (((prev->next)->ptr - ptr) > _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // No luck. - void *new = malloc(size); - if (!new) - return 0; - - __builtin_memcpy(new, ptr, prev->size); - free(ptr); - return new; + if (!size) { + free(ptr); + return 0; + } + if (!ptr) + return malloc(size); + + size_t _size = _align(size + sizeof(BlockHeader), 8); + BlockHeader *prev = (BlockHeader *)((uintptr_t)ptr - sizeof(BlockHeader)); + + // New memory block shorter? + if (prev->size >= _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + + if (!prev->next) + sbrk((ptr - sbrk(0)) + _size); + + return ptr; + } + + // New memory block larger; is it the last one? + if (!prev->next) { + void *new = sbrk(_size - prev->size); + if (!new) + return 0; + + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // Do we have free memory after it? + if (((prev->next)->ptr - ptr - sizeof(BlockHeader)) > _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // No luck. + void *new = malloc(size); + if (!new) + return 0; + + __builtin_memcpy(new, ptr, prev->size); + free(ptr); + return new; } __attribute__((weak)) void free(void *ptr) { - if (!ptr || !_alloc_head) - return; - - // First block; bumping head ahead. - if (ptr == _alloc_head->ptr) { - size_t size = _alloc_head->size; - size += (uintptr_t) _alloc_head->ptr - (uintptr_t) _alloc_head; - _alloc_head = _alloc_head->next; - - if (_alloc_head) { - _alloc_head->prev = 0; - } else { - _alloc_tail = 0; - sbrk(-size); - } - - TrackHeapUsage(-(_alloc_head->size)); - return; - } - - // Finding the proper block - BlockHeader *cur = _alloc_head; - - for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { - if (!cur->next) - return; - } - - if (cur->next) { - // In the middle, just unlink it - (cur->next)->prev = cur->prev; - } else { - // At the end, shrink heap - void *top = sbrk(0); - size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; - _alloc_tail = cur->prev; - - sbrk(-size); - } - - TrackHeapUsage(-(cur->size)); - (cur->prev)->next = cur->next; + if (!ptr || !_alloc_head) + return; + + // First block; bumping head ahead. + if (ptr == _alloc_head->ptr) { + size_t size = _alloc_head->size; + size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; + _alloc_head = _alloc_head->next; + + if (_alloc_head) { + _alloc_head->prev = 0; + } else { + _alloc_tail = 0; + sbrk(-size); + } + + TrackHeapUsage(-(_alloc_head->size)); + return; + } + + // Finding the proper block + BlockHeader *cur = _alloc_head; + + for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { + if (!cur->next) + return; + } + + if (cur->next) { + // In the middle, just unlink it + (cur->next)->prev = cur->prev; + } else { + // At the end, shrink heap + void *top = sbrk(0); + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + _alloc_tail = cur->prev; + + sbrk(-size); + } + + TrackHeapUsage(-(cur->size)); + (cur->prev)->next = cur->next; } From ada15b36b41761123a9662e503e53267f2937b0f Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 00:51:50 +1100 Subject: [PATCH 005/128] Fixed size usage overlapping BlockHeaders --- libpsn00b/libc/malloc.c | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 06f70755..0b04be07 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -100,6 +100,7 @@ __attribute__((weak)) void *malloc(size_t size) { return 0; size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size_nh = _size - sizeof(BlockHeader); // Nothing's initialized yet? Let's just initialize the bottom of our heap, // flag it as allocated. @@ -113,14 +114,14 @@ __attribute__((weak)) void *malloc(size_t size) { void *ptr = (void *)&new[1]; new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); + new->size = _size_nh; new->prev = 0; new->next = 0; _alloc_head = new; _alloc_tail = new; - TrackHeapUsage(size); + TrackHeapUsage(_size); return ptr; } @@ -132,14 +133,14 @@ __attribute__((weak)) void *malloc(size_t size) { void *ptr = (void *)&new[1]; new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); + new->size = _size_nh; new->prev = 0; new->next = _alloc_head; _alloc_head->prev = new; _alloc_head = new; - TrackHeapUsage(size); + TrackHeapUsage(_size); return ptr; } @@ -148,16 +149,16 @@ __attribute__((weak)) void *malloc(size_t size) { if (prev) { BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); - void *ptr = (void*)&new[1]; + void *ptr = (void *)&new[1]; new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); + new->size = _size_nh; new->prev = prev; new->next = prev->next; (new->next)->prev = new; prev->next = new; - TrackHeapUsage(size); + TrackHeapUsage(_size); return ptr; } @@ -168,14 +169,14 @@ __attribute__((weak)) void *malloc(size_t size) { void *ptr = (void *)&new[1]; new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); + new->size = _size_nh; new->prev = _alloc_tail; new->next = 0; _alloc_tail->next = new; _alloc_tail = new; - TrackHeapUsage(size); + TrackHeapUsage(_size); return ptr; } @@ -192,34 +193,36 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { return malloc(size); size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size_nh = _size - sizeof(BlockHeader); BlockHeader *prev = (BlockHeader *)((uintptr_t)ptr - sizeof(BlockHeader)); // New memory block shorter? - if (prev->size >= _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); + if (prev->size >= _size_nh) { + TrackHeapUsage(_size_nh - prev->size); + prev->size = _size_nh; if (!prev->next) - sbrk((ptr - sbrk(0)) + _size); + sbrk((ptr - sbrk(0)) + _size_nh); return ptr; } // New memory block larger; is it the last one? if (!prev->next) { - void *new = sbrk(_size - prev->size); + void *new = sbrk(_size_nh - prev->size); if (!new) return 0; - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); + TrackHeapUsage(_size_nh - prev->size); + prev->size = _size_nh; return ptr; } // Do we have free memory after it? - if (((prev->next)->ptr - ptr - sizeof(BlockHeader)) > _size) { + if (((prev->next)->ptr - ptr - sizeof(BlockHeader)) > + _size - sizeof(BlockHeader)) { TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); + prev->size = _size_nh; return ptr; } From 738f90dfc69165bb43a6c7db1383052012935f14 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 01:10:07 +1100 Subject: [PATCH 006/128] Fixed usage of sizing and sbrk invocations --- libpsn00b/libc/malloc.c | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 0b04be07..b0be4767 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -219,9 +219,8 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { } // Do we have free memory after it? - if (((prev->next)->ptr - ptr - sizeof(BlockHeader)) > - _size - sizeof(BlockHeader)) { - TrackHeapUsage(size - prev->size); + if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) > _size_nh) { + TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; } @@ -250,10 +249,10 @@ __attribute__((weak)) void free(void *ptr) { _alloc_head->prev = 0; } else { _alloc_tail = 0; - sbrk(-size); + sbrk(-size - sizeof(BlockHeader)); } - TrackHeapUsage(-(_alloc_head->size)); + TrackHeapUsage(-(_alloc_head->size) - sizeof(BlockHeader)); return; } @@ -271,12 +270,12 @@ __attribute__((weak)) void free(void *ptr) { } else { // At the end, shrink heap void *top = sbrk(0); - size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; _alloc_tail = cur->prev; sbrk(-size); } - TrackHeapUsage(-(cur->size)); + TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); (cur->prev)->next = cur->next; } From 66d1e78e023f092e26a177d9b0b79a22f60d2e00 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 01:30:09 +1100 Subject: [PATCH 007/128] Fixed condition for realloc resizing to contiguously available free mem --- libpsn00b/libc/malloc.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index b0be4767..32852095 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -201,8 +201,11 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; - if (!prev->next) + // This is the last block, move the break back to accomodate shrinking + if (!prev->next) { + // We have overriden prev->size, need to calculate it from break sbrk((ptr - sbrk(0)) + _size_nh); + } return ptr; } @@ -219,7 +222,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { } // Do we have free memory after it? - if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) > _size_nh) { + if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; From 9ca3ccc900e85e449df6da5aef3663bf6513042e Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 01:39:25 +1100 Subject: [PATCH 008/128] Optimisations to free implementation --- libpsn00b/libc/malloc.c | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 32852095..5872eb22 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -244,18 +244,17 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { - size_t size = _alloc_head->size; - size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; + size_t size = _alloc_head->size + sizeof(BlockHeader); _alloc_head = _alloc_head->next; if (_alloc_head) { _alloc_head->prev = 0; } else { _alloc_tail = 0; - sbrk(-size - sizeof(BlockHeader)); + sbrk(-size); } - TrackHeapUsage(-(_alloc_head->size) - sizeof(BlockHeader)); + TrackHeapUsage(-size); return; } @@ -267,9 +266,11 @@ __attribute__((weak)) void free(void *ptr) { return; } + size_t heap_change; if (cur->next) { // In the middle, just unlink it (cur->next)->prev = cur->prev; + heap_change = -(cur->size) - sizeof(BlockHeader); } else { // At the end, shrink heap void *top = sbrk(0); @@ -277,8 +278,9 @@ __attribute__((weak)) void free(void *ptr) { _alloc_tail = cur->prev; sbrk(-size); + heap_change = -size; } - TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); + TrackHeapUsage(heap_change); (cur->prev)->next = cur->next; } From 3172c52166a731e0ec742b1d7fb8350e70fe861a Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 21:03:03 +1100 Subject: [PATCH 009/128] Added debug logs --- libpsn00b/libc/malloc.c | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 5872eb22..31f12c52 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -15,6 +15,7 @@ #include #include +#include #include #define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) @@ -81,12 +82,14 @@ __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { static BlockHeader *_find_fit(BlockHeader *head, size_t size) { BlockHeader *prev = head; - + printf("[FindFit] size: %d\n", size); for (; prev; prev = prev->next) { if (prev->next) { uintptr_t next_bot = (uintptr_t)prev->next; + printf("[FindFit] next_bot: %d\n", next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - + printf("[FindFit] offset: %p, next_bot: %d\n", prev->ptr + prev->size, + next_bot); if (next_bot >= size) return prev; } @@ -198,24 +201,26 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // New memory block shorter? if (prev->size >= _size_nh) { + printf("[Realloc] new size shorter: %d >= %d\n", prev->size, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; // This is the last block, move the break back to accomodate shrinking if (!prev->next) { // We have overriden prev->size, need to calculate it from break - sbrk((ptr - sbrk(0)) + _size_nh); + void *new_break = sbrk((ptr - sbrk(0)) + _size_nh); + printf("[Realloc] last block, shrink break: %p\n", new_break); } - return ptr; } // New memory block larger; is it the last one? if (!prev->next) { + printf("[Realloc] new block larger\n"); void *new = sbrk(_size_nh - prev->size); if (!new) return 0; - + printf("[Realloc] new break: %d => %p\n", _size_nh - prev->size, new); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -223,6 +228,10 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // Do we have free memory after it? if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { + printf("[Realloc] free mem after: %d >= %d\n", + (prev->next)->ptr - sizeof(BlockHeader) - ptr, + _size_nh + ); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -232,7 +241,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { void *new = malloc(size); if (!new) return 0; - + printf("[Realloc] new malloc addr: %p\n", new); __builtin_memcpy(new, ptr, prev->size); free(ptr); return new; @@ -270,7 +279,7 @@ __attribute__((weak)) void free(void *ptr) { if (cur->next) { // In the middle, just unlink it (cur->next)->prev = cur->prev; - heap_change = -(cur->size) - sizeof(BlockHeader); + heap_change = -(cur->size) - sizeof(BlockHeader); } else { // At the end, shrink heap void *top = sbrk(0); @@ -278,7 +287,7 @@ __attribute__((weak)) void free(void *ptr) { _alloc_tail = cur->prev; sbrk(-size); - heap_change = -size; + heap_change = -size; } TrackHeapUsage(heap_change); From 4d814f0d589c9190bbba12eaea3e39643ff13e74 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 21:30:45 +1100 Subject: [PATCH 010/128] Added debug logs --- libpsn00b/libc/malloc.c | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 31f12c52..f6c000eb 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -132,6 +132,8 @@ __attribute__((weak)) void *malloc(size_t size) { // So let's check first if we have free space there, because I'm nervous // about having an incomplete data structure. if (((uintptr_t)_alloc_start + _size) < ((uintptr_t)_alloc_head)) { + printf("[Malloc] bottom heap shifted: %p < %p\n", _alloc_start + _size, + _alloc_head); BlockHeader *new = (BlockHeader *)_alloc_start; void *ptr = (void *)&new[1]; @@ -151,6 +153,7 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader *prev = _find_fit(_alloc_head, _size); if (prev) { BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); + printf("[Malloc] found fit: %p\n", new); void *ptr = (void *)&new[1]; new->ptr = ptr; @@ -169,7 +172,7 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader *new = (BlockHeader *)sbrk(_size); if (!new) return 0; - + printf("[Malloc] extended heap: %p\n", new); void *ptr = (void *)&new[1]; new->ptr = ptr; new->size = _size_nh; @@ -228,10 +231,8 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // Do we have free memory after it? if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { - printf("[Realloc] free mem after: %d >= %d\n", - (prev->next)->ptr - sizeof(BlockHeader) - ptr, - _size_nh - ); + printf("[Realloc] free mem after: %d >= %d\n", + (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -253,14 +254,18 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { + printf("[Free] first block, bump head forward\n"); size_t size = _alloc_head->size + sizeof(BlockHeader); + printf("[Free] size: %d\n", size); _alloc_head = _alloc_head->next; - + printf("[Free] new head: %p\n", _alloc_head); if (_alloc_head) { _alloc_head->prev = 0; + printf("[Free] New head exists, setting prev to null\n"); } else { + printf("[Free] No new head exists, nulling tail\n"); _alloc_tail = 0; - sbrk(-size); + // sbrk(-size); } TrackHeapUsage(-size); @@ -269,27 +274,34 @@ __attribute__((weak)) void free(void *ptr) { // Finding the proper block BlockHeader *cur = _alloc_head; - + printf("[Free] find block, base: %p\n", cur); for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { if (!cur->next) return; } + printf("[Free] found: %p\n", cur); size_t heap_change; if (cur->next) { // In the middle, just unlink it + printf("[Free] has next, setting next->prev to cur->prev: %p\n", cur->prev); (cur->next)->prev = cur->prev; heap_change = -(cur->size) - sizeof(BlockHeader); } else { // At the end, shrink heap + printf("[Free] at end of heap\n"); void *top = sbrk(0); + printf("[Free] heap top: %p\n", top); size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; + printf("[Free] size: %d\n", size); _alloc_tail = cur->prev; + printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); heap_change = -size; } - + printf("[Free] heap_change: %d\n", heap_change); TrackHeapUsage(heap_change); (cur->prev)->next = cur->next; + printf("[Free] setting prev->next to cur->next: %p\n", cur->next); } From 37faa71dc11d5f940a379ed33e7c279031fd01f8 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 21:58:41 +1100 Subject: [PATCH 011/128] Added debug logs --- libpsn00b/libc/malloc.c | 1 + 1 file changed, 1 insertion(+) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index f6c000eb..6ac33b6a 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -54,6 +54,7 @@ __attribute__((weak)) void InitHeap(void *addr, size_t size) { __attribute__((weak)) void *sbrk(ptrdiff_t incr) { void *old_end = _heap_end; void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); + printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); if (new_end > _heap_limit) return 0; From b91b1d00fae85770ee3e44d125eb987b06c9e848 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 22:07:31 +1100 Subject: [PATCH 012/128] Added debug logs --- libpsn00b/libc/malloc.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 6ac33b6a..dd32101e 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -54,7 +54,8 @@ __attribute__((weak)) void InitHeap(void *addr, size_t size) { __attribute__((weak)) void *sbrk(ptrdiff_t incr) { void *old_end = _heap_end; void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); - printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); + printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, + new_end); if (new_end > _heap_limit) return 0; @@ -83,13 +84,13 @@ __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { static BlockHeader *_find_fit(BlockHeader *head, size_t size) { BlockHeader *prev = head; - printf("[FindFit] size: %d\n", size); + printf("[FindFit] size: %x\n", size); for (; prev; prev = prev->next) { if (prev->next) { uintptr_t next_bot = (uintptr_t)prev->next; - printf("[FindFit] next_bot: %d\n", next_bot); + printf("[FindFit] next_bot: %x\n", next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - printf("[FindFit] offset: %p, next_bot: %d\n", prev->ptr + prev->size, + printf("[FindFit] offset: %p, next_bot: %x\n", prev->ptr + prev->size, next_bot); if (next_bot >= size) return prev; @@ -205,7 +206,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // New memory block shorter? if (prev->size >= _size_nh) { - printf("[Realloc] new size shorter: %d >= %d\n", prev->size, _size_nh); + printf("[Realloc] new size shorter: %x >= %x\n", prev->size, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; @@ -224,7 +225,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { void *new = sbrk(_size_nh - prev->size); if (!new) return 0; - printf("[Realloc] new break: %d => %p\n", _size_nh - prev->size, new); + printf("[Realloc] new break: %x => %p\n", _size_nh - prev->size, new); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -232,7 +233,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // Do we have free memory after it? if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { - printf("[Realloc] free mem after: %d >= %d\n", + printf("[Realloc] free mem after: %x >= %x\n", (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; @@ -257,7 +258,7 @@ __attribute__((weak)) void free(void *ptr) { if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); size_t size = _alloc_head->size + sizeof(BlockHeader); - printf("[Free] size: %d\n", size); + printf("[Free] size: %x\n", size); _alloc_head = _alloc_head->next; printf("[Free] new head: %p\n", _alloc_head); if (_alloc_head) { @@ -294,14 +295,14 @@ __attribute__((weak)) void free(void *ptr) { void *top = sbrk(0); printf("[Free] heap top: %p\n", top); size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; - printf("[Free] size: %d\n", size); + printf("[Free] size: %x\n", size); _alloc_tail = cur->prev; printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); heap_change = -size; } - printf("[Free] heap_change: %d\n", heap_change); + printf("[Free] heap_change: %x\n", heap_change); TrackHeapUsage(heap_change); (cur->prev)->next = cur->next; printf("[Free] setting prev->next to cur->next: %p\n", cur->next); From 8c919d8d8a5960eb1823d82e35457ea453aac796 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Mon, 15 Jan 2024 22:22:25 +1100 Subject: [PATCH 013/128] Added debug logs --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index dd32101e..bdb8dbb2 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -90,7 +90,7 @@ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { uintptr_t next_bot = (uintptr_t)prev->next; printf("[FindFit] next_bot: %x\n", next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - printf("[FindFit] offset: %p, next_bot: %x\n", prev->ptr + prev->size, + printf("[FindFit] ptr: %p, size: %x, offset: %p, next_bot: %x\n", prev->ptr, prev->size, prev->ptr + prev->size, next_bot); if (next_bot >= size) return prev; From e6f258fbb74028bb3b5d921bfe6defa3fd6c9cb1 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 00:30:18 +1100 Subject: [PATCH 014/128] Added debug logs --- libpsn00b/libc/malloc.c | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index bdb8dbb2..ca34ccb0 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -84,19 +84,21 @@ __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { static BlockHeader *_find_fit(BlockHeader *head, size_t size) { BlockHeader *prev = head; - printf("[FindFit] size: %x\n", size); + printf("[FindFit] size: 0x%x\n", size); for (; prev; prev = prev->next) { if (prev->next) { uintptr_t next_bot = (uintptr_t)prev->next; - printf("[FindFit] next_bot: %x\n", next_bot); + printf("[FindFit] next_bot: %p\n", (void *)next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - printf("[FindFit] ptr: %p, size: %x, offset: %p, next_bot: %x\n", prev->ptr, prev->size, prev->ptr + prev->size, - next_bot); - if (next_bot >= size) + printf("[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", + prev->ptr, prev->size, prev->ptr + prev->size, (void *)next_bot); + if (next_bot >= size) { + printf("[FindFit] found %p\n", prev); return prev; + } } } - + printf("[FindFit] Not found: %p\n", prev); return prev; } @@ -143,6 +145,7 @@ __attribute__((weak)) void *malloc(size_t size) { new->size = _size_nh; new->prev = 0; new->next = _alloc_head; + printf("[Malloc] new->next: %p\n", new->next); _alloc_head->prev = new; _alloc_head = new; @@ -162,9 +165,11 @@ __attribute__((weak)) void *malloc(size_t size) { new->size = _size_nh; new->prev = prev; new->next = prev->next; + printf("[Malloc] fit, new->next: %p\n", new->next); (new->next)->prev = new; prev->next = new; + printf("[Malloc] fit, prev->next: %p\n", prev->next); TrackHeapUsage(_size); return ptr; @@ -182,6 +187,7 @@ __attribute__((weak)) void *malloc(size_t size) { new->next = 0; _alloc_tail->next = new; + printf("[Malloc] extend, _alloc_tail->next: %p\n", _alloc_tail->next); _alloc_tail = new; TrackHeapUsage(_size); @@ -206,7 +212,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // New memory block shorter? if (prev->size >= _size_nh) { - printf("[Realloc] new size shorter: %x >= %x\n", prev->size, _size_nh); + printf("[Realloc] new size shorter: 0x%x >= 0x%x\n", prev->size, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; @@ -225,7 +231,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { void *new = sbrk(_size_nh - prev->size); if (!new) return 0; - printf("[Realloc] new break: %x => %p\n", _size_nh - prev->size, new); + printf("[Realloc] new break: 0x%x => %p\n", _size_nh - prev->size, new); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -233,7 +239,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // Do we have free memory after it? if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { - printf("[Realloc] free mem after: %x >= %x\n", + printf("[Realloc] free mem after: 0x%x >= 0x%x\n", (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; @@ -258,7 +264,7 @@ __attribute__((weak)) void free(void *ptr) { if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); size_t size = _alloc_head->size + sizeof(BlockHeader); - printf("[Free] size: %x\n", size); + printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; printf("[Free] new head: %p\n", _alloc_head); if (_alloc_head) { @@ -295,15 +301,16 @@ __attribute__((weak)) void free(void *ptr) { void *top = sbrk(0); printf("[Free] heap top: %p\n", top); size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; - printf("[Free] size: %x\n", size); + printf("[Free] size: 0x%x\n", size); _alloc_tail = cur->prev; printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); heap_change = -size; } - printf("[Free] heap_change: %x\n", heap_change); + printf("[Free] heap_change: 0x%x\n", heap_change); TrackHeapUsage(heap_change); (cur->prev)->next = cur->next; + printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); printf("[Free] setting prev->next to cur->next: %p\n", cur->next); } From 343d768e5ebaa1b85e3d98f8a6b68634326673b1 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 19:10:34 +1100 Subject: [PATCH 015/128] Readded free sbrk --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index ca34ccb0..812180f7 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -273,7 +273,7 @@ __attribute__((weak)) void free(void *ptr) { } else { printf("[Free] No new head exists, nulling tail\n"); _alloc_tail = 0; - // sbrk(-size); + sbrk(-size); } TrackHeapUsage(-size); From 8ebf6f81b5a0d56353c21a37e7a5637d5490b6d7 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 19:44:17 +1100 Subject: [PATCH 016/128] Removed free changes --- libpsn00b/libc/malloc.c | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 812180f7..a30c1471 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -289,12 +289,10 @@ __attribute__((weak)) void free(void *ptr) { } printf("[Free] found: %p\n", cur); - size_t heap_change; if (cur->next) { // In the middle, just unlink it printf("[Free] has next, setting next->prev to cur->prev: %p\n", cur->prev); (cur->next)->prev = cur->prev; - heap_change = -(cur->size) - sizeof(BlockHeader); } else { // At the end, shrink heap printf("[Free] at end of heap\n"); @@ -306,10 +304,9 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); - heap_change = -size; } printf("[Free] heap_change: 0x%x\n", heap_change); - TrackHeapUsage(heap_change); + TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); (cur->prev)->next = cur->next; printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); printf("[Free] setting prev->next to cur->next: %p\n", cur->next); From 2eb6961b271167b35439f32dfb8af0b4ed6aa536 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 19:50:34 +1100 Subject: [PATCH 017/128] Removed free changes --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index a30c1471..52ff04a4 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -305,7 +305,7 @@ __attribute__((weak)) void free(void *ptr) { sbrk(-size); } - printf("[Free] heap_change: 0x%x\n", heap_change); + printf("[Free] heap_change: 0x%x\n", -(cur->size) - sizeof(BlockHeader)); TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); (cur->prev)->next = cur->next; printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); From 4a7d0cb1a4ce5160cf8bf26ea89de5742ca95cc4 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 20:18:12 +1100 Subject: [PATCH 018/128] Removed free changes --- libpsn00b/libc/malloc.c | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 52ff04a4..926a85b9 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -263,7 +263,8 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = _alloc_head->size + sizeof(BlockHeader); + size_t size = _alloc_head->size; // + sizeof(BlockHeader); + size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; printf("[Free] new head: %p\n", _alloc_head); @@ -273,10 +274,10 @@ __attribute__((weak)) void free(void *ptr) { } else { printf("[Free] No new head exists, nulling tail\n"); _alloc_tail = 0; - sbrk(-size); + sbrk(-size - sizeof(BlockHeader)); } - TrackHeapUsage(-size); + TrackHeapUsage(-(_alloc_head->size) - sizeof(BlockHeader)); return; } @@ -301,8 +302,8 @@ __attribute__((weak)) void free(void *ptr) { size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; printf("[Free] size: 0x%x\n", size); _alloc_tail = cur->prev; - printf("[Free] new tail: %p\n", _alloc_tail); + printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); } printf("[Free] heap_change: 0x%x\n", -(cur->size) - sizeof(BlockHeader)); From f79418315f8ece89e3ade5852ddb95fa430b1a0c Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 20:27:32 +1100 Subject: [PATCH 019/128] Removed free changes --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 926a85b9..8cf7e84f 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -263,7 +263,7 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = _alloc_head->size; // + sizeof(BlockHeader); + size_t size = _alloc_head->size + sizeof(BlockHeader); size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; From 14e8b88cf684990a01eaf25a40ea7f7ea061cf0e Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Wed, 17 Jan 2024 20:56:09 +1100 Subject: [PATCH 020/128] Removed free changes --- libpsn00b/libc/malloc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 8cf7e84f..ac4f8fef 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -263,7 +263,7 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = _alloc_head->size + sizeof(BlockHeader); + size_t size = _alloc_head->size; size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; @@ -274,10 +274,10 @@ __attribute__((weak)) void free(void *ptr) { } else { printf("[Free] No new head exists, nulling tail\n"); _alloc_tail = 0; - sbrk(-size - sizeof(BlockHeader)); + sbrk(-size); } - TrackHeapUsage(-(_alloc_head->size) - sizeof(BlockHeader)); + TrackHeapUsage(-size); return; } From a7ad145d623a3f985e973bd3525fd0379880ed41 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 19:28:28 +1100 Subject: [PATCH 021/128] Fixed size shift in free --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index ac4f8fef..f8c1cacc 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -299,7 +299,7 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] at end of heap\n"); void *top = sbrk(0); printf("[Free] heap top: %p\n", top); - size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; printf("[Free] size: 0x%x\n", size); _alloc_tail = cur->prev; From 6701b74b01a47e5576a9c27a30183ac7d6292ce0 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 19:38:47 +1100 Subject: [PATCH 022/128] Fixed size shift in free --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index f8c1cacc..ac4f8fef 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -299,7 +299,7 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] at end of heap\n"); void *top = sbrk(0); printf("[Free] heap top: %p\n", top); - size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; printf("[Free] size: 0x%x\n", size); _alloc_tail = cur->prev; From 3b24503fe1fdf34b02b90af3db2f9b92f91a6b70 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 20:45:25 +1100 Subject: [PATCH 023/128] Migrated to TLSF --- .idea/.gitignore | 8 + .../.cmake/api/v1/query/cache-v2 | 0 .../.cmake/api/v1/query/cmakeFiles-v1 | 0 .../.cmake/api/v1/query/codemodel-v2 | 0 .../.cmake/api/v1/query/toolchains-v1 | 0 cmake-build-debug/CMakeCache.txt | 249 ++++ .../CMakeFiles/3.27.8/CMakeSystem.cmake | 15 + .../CMakeFiles/CMakeConfigureLog.yaml | 11 + .../CMakeFiles/clion-Debug-log.txt | 15 + .../CMakeFiles/clion-environment.txt | 3 + .../CMakeFiles/cmake.check_cache | 1 + libpsn00b/libc/malloc.c | 297 +--- libpsn00b/libc/malloc_old | 279 ++++ libpsn00b/libc/tlsf.c | 1264 +++++++++++++++++ libpsn00b/libc/tlsf.h | 92 ++ 15 files changed, 1945 insertions(+), 289 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 cmake-build-debug/.cmake/api/v1/query/cache-v2 create mode 100644 cmake-build-debug/.cmake/api/v1/query/cmakeFiles-v1 create mode 100644 cmake-build-debug/.cmake/api/v1/query/codemodel-v2 create mode 100644 cmake-build-debug/.cmake/api/v1/query/toolchains-v1 create mode 100644 cmake-build-debug/CMakeCache.txt create mode 100644 cmake-build-debug/CMakeFiles/3.27.8/CMakeSystem.cmake create mode 100644 cmake-build-debug/CMakeFiles/CMakeConfigureLog.yaml create mode 100644 cmake-build-debug/CMakeFiles/clion-Debug-log.txt create mode 100644 cmake-build-debug/CMakeFiles/clion-environment.txt create mode 100644 cmake-build-debug/CMakeFiles/cmake.check_cache create mode 100644 libpsn00b/libc/malloc_old create mode 100644 libpsn00b/libc/tlsf.c create mode 100644 libpsn00b/libc/tlsf.h diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/cmake-build-debug/.cmake/api/v1/query/cache-v2 b/cmake-build-debug/.cmake/api/v1/query/cache-v2 new file mode 100644 index 00000000..e69de29b diff --git a/cmake-build-debug/.cmake/api/v1/query/cmakeFiles-v1 b/cmake-build-debug/.cmake/api/v1/query/cmakeFiles-v1 new file mode 100644 index 00000000..e69de29b diff --git a/cmake-build-debug/.cmake/api/v1/query/codemodel-v2 b/cmake-build-debug/.cmake/api/v1/query/codemodel-v2 new file mode 100644 index 00000000..e69de29b diff --git a/cmake-build-debug/.cmake/api/v1/query/toolchains-v1 b/cmake-build-debug/.cmake/api/v1/query/toolchains-v1 new file mode 100644 index 00000000..e69de29b diff --git a/cmake-build-debug/CMakeCache.txt b/cmake-build-debug/CMakeCache.txt new file mode 100644 index 00000000..ec8a0e4d --- /dev/null +++ b/cmake-build-debug/CMakeCache.txt @@ -0,0 +1,249 @@ +# This is the CMakeCache file. +# For build in directory: /Users/jackkilrain/PSn00bSDK/cmake-build-debug +# It was generated by CMake: /Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//No help, variable specified on the command line. +CMAKE_BUILD_TYPE:UNINITIALIZED=Debug + +//Enable colored diagnostics throughout. +CMAKE_COLOR_DIAGNOSTICS:BOOL=ON + +//Enable/Disable output of compile commands during generation. +CMAKE_EXPORT_COMPILE_COMMANDS:BOOL= + +//Value Computed by CMake. +CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/Users/jackkilrain/PSn00bSDK/cmake-build-debug/CMakeFiles/pkgRedirects + +//User executables (bin) +CMAKE_INSTALL_BINDIR:PATH=bin + +//Read-only architecture-independent data (DATAROOTDIR) +CMAKE_INSTALL_DATADIR:PATH= + +//Read-only architecture-independent data root (share) +CMAKE_INSTALL_DATAROOTDIR:PATH=share + +//Documentation root (DATAROOTDIR/doc/PROJECT_NAME) +CMAKE_INSTALL_DOCDIR:PATH= + +//C header files (include) +CMAKE_INSTALL_INCLUDEDIR:PATH=include + +//Info documentation (DATAROOTDIR/info) +CMAKE_INSTALL_INFODIR:PATH= + +//Object code libraries (lib) +CMAKE_INSTALL_LIBDIR:PATH=lib + +//Program executables (libexec) +CMAKE_INSTALL_LIBEXECDIR:PATH=libexec + +//Locale-dependent data (DATAROOTDIR/locale) +CMAKE_INSTALL_LOCALEDIR:PATH= + +//Modifiable single-machine data (var) +CMAKE_INSTALL_LOCALSTATEDIR:PATH=var + +//Man documentation (DATAROOTDIR/man) +CMAKE_INSTALL_MANDIR:PATH= + +//Path to a program. +CMAKE_INSTALL_NAME_TOOL:FILEPATH=/usr/bin/install_name_tool + +//C header files for non-gcc (/usr/include) +CMAKE_INSTALL_OLDINCLUDEDIR:PATH=/usr/include + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr/local + +//Run-time variable data (LOCALSTATEDIR/run) +CMAKE_INSTALL_RUNSTATEDIR:PATH= + +//System admin executables (sbin) +CMAKE_INSTALL_SBINDIR:PATH=sbin + +//Modifiable architecture-independent data (com) +CMAKE_INSTALL_SHAREDSTATEDIR:PATH=com + +//Read-only single-machine data (etc) +CMAKE_INSTALL_SYSCONFDIR:PATH=etc + +//make program +CMAKE_MAKE_PROGRAM:FILEPATH=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/ninja/mac/x64/ninja + +//Build architectures for OSX +CMAKE_OSX_ARCHITECTURES:STRING= + +//Minimum OS X version to target for deployment (at runtime); newer +// APIs weak linked. Set to empty string for default value. +CMAKE_OSX_DEPLOYMENT_TARGET:STRING= + +//The product will be built against the headers and libraries located +// inside the indicated SDK. +CMAKE_OSX_SYSROOT:PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.2.sdk + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC=Open source PlayStation 1 SDK + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC=http://lameguy64.net/?page=psn00bsdk + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=PSn00bSDK + +//Value Computed by CMake +CMAKE_PROJECT_VERSION:STATIC=0.24 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_MAJOR:STATIC=0 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_MINOR:STATIC=24 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_PATCH:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_TWEAK:STATIC= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//CMake generator to use for building libpsn00b and examples +LIBPSN00B_GENERATOR:STRING=Ninja + +//Disable libflac integration when building mkpsxiso +MKPSXISO_NO_LIBFLAC:BOOL=OFF + +//Git commit hash (used by CI) +PSN00BSDK_GIT_COMMIT:STRING= + +//Git tag or branch name (used by CI) +PSN00BSDK_GIT_TAG:STRING= + +//GCC toolchain target triplet +PSN00BSDK_TARGET:STRING=mipsel-none-elf + +//Path to the GCC toolchain's installation directory (if not in +// PATH) +PSN00BSDK_TC:PATH= + +//Value Computed by CMake +PSn00bSDK_BINARY_DIR:STATIC=/Users/jackkilrain/PSn00bSDK/cmake-build-debug + +//Value Computed by CMake +PSn00bSDK_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +PSn00bSDK_SOURCE_DIR:STATIC=/Users/jackkilrain/PSn00bSDK + +//Skip building SDK examples (not required for installation) +SKIP_EXAMPLES:BOOL=OFF + + +######################## +# INTERNAL cache entries +######################## + +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/Users/jackkilrain/PSn00bSDK/cmake-build-debug +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=27 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=8 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/ctest +//ADVANCED property for variable: CMAKE_EXPORT_COMPILE_COMMANDS +CMAKE_EXPORT_COMPILE_COMMANDS-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Ninja +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/Users/jackkilrain/PSn00bSDK +//ADVANCED property for variable: CMAKE_INSTALL_BINDIR +CMAKE_INSTALL_BINDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_DATADIR +CMAKE_INSTALL_DATADIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_DATAROOTDIR +CMAKE_INSTALL_DATAROOTDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_DOCDIR +CMAKE_INSTALL_DOCDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_INCLUDEDIR +CMAKE_INSTALL_INCLUDEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_INFODIR +CMAKE_INSTALL_INFODIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_LIBDIR +CMAKE_INSTALL_LIBDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_LIBEXECDIR +CMAKE_INSTALL_LIBEXECDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_LOCALEDIR +CMAKE_INSTALL_LOCALEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_LOCALSTATEDIR +CMAKE_INSTALL_LOCALSTATEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_MANDIR +CMAKE_INSTALL_MANDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_NAME_TOOL +CMAKE_INSTALL_NAME_TOOL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_OLDINCLUDEDIR +CMAKE_INSTALL_OLDINCLUDEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_RUNSTATEDIR +CMAKE_INSTALL_RUNSTATEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_SBINDIR +CMAKE_INSTALL_SBINDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_SHAREDSTATEDIR +CMAKE_INSTALL_SHAREDSTATEDIR-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_INSTALL_SYSCONFDIR +CMAKE_INSTALL_SYSCONFDIR-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/share/cmake-3.27 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 +//CMAKE_INSTALL_PREFIX during last run +_GNUInstallDirs_LAST_CMAKE_INSTALL_PREFIX:INTERNAL=/usr/local + diff --git a/cmake-build-debug/CMakeFiles/3.27.8/CMakeSystem.cmake b/cmake-build-debug/CMakeFiles/3.27.8/CMakeSystem.cmake new file mode 100644 index 00000000..43c65e75 --- /dev/null +++ b/cmake-build-debug/CMakeFiles/3.27.8/CMakeSystem.cmake @@ -0,0 +1,15 @@ +set(CMAKE_HOST_SYSTEM "Darwin-23.2.0") +set(CMAKE_HOST_SYSTEM_NAME "Darwin") +set(CMAKE_HOST_SYSTEM_VERSION "23.2.0") +set(CMAKE_HOST_SYSTEM_PROCESSOR "x86_64") + + + +set(CMAKE_SYSTEM "Darwin-23.2.0") +set(CMAKE_SYSTEM_NAME "Darwin") +set(CMAKE_SYSTEM_VERSION "23.2.0") +set(CMAKE_SYSTEM_PROCESSOR "x86_64") + +set(CMAKE_CROSSCOMPILING "FALSE") + +set(CMAKE_SYSTEM_LOADED 1) diff --git a/cmake-build-debug/CMakeFiles/CMakeConfigureLog.yaml b/cmake-build-debug/CMakeFiles/CMakeConfigureLog.yaml new file mode 100644 index 00000000..3855ef7c --- /dev/null +++ b/cmake-build-debug/CMakeFiles/CMakeConfigureLog.yaml @@ -0,0 +1,11 @@ + +--- +events: + - + kind: "message-v1" + backtrace: + - "/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/share/cmake-3.27/Modules/CMakeDetermineSystem.cmake:211 (message)" + - "CMakeLists.txt:12 (project)" + message: | + The system is: Darwin - 23.2.0 - x86_64 +... diff --git a/cmake-build-debug/CMakeFiles/clion-Debug-log.txt b/cmake-build-debug/CMakeFiles/clion-Debug-log.txt new file mode 100644 index 00000000..f81b7341 --- /dev/null +++ b/cmake-build-debug/CMakeFiles/clion-Debug-log.txt @@ -0,0 +1,15 @@ +"/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/cmake" -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_MAKE_PROGRAM=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/ninja/mac/x64/ninja" -G Ninja -S /Users/jackkilrain/PSn00bSDK -B /Users/jackkilrain/PSn00bSDK/cmake-build-debug +CMake Warning (dev) at /Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/share/cmake-3.27/Modules/GNUInstallDirs.cmake:243 (message): + Unable to determine default CMAKE_INSTALL_LIBDIR directory because no + target architecture is known. Please enable at least one language before + including GNUInstallDirs. +Call Stack (most recent call first): + CMakeLists.txt:22 (include) +This warning is for project developers. Use -Wno-dev to suppress it. + +CMake Error at CMakeLists.txt:125 (message): + The mkpsxiso directory is empty. Run 'git submodule update --init + --recursive' to populate it. + + +-- Configuring incomplete, errors occurred! diff --git a/cmake-build-debug/CMakeFiles/clion-environment.txt b/cmake-build-debug/CMakeFiles/clion-environment.txt new file mode 100644 index 00000000..a114582f --- /dev/null +++ b/cmake-build-debug/CMakeFiles/clion-environment.txt @@ -0,0 +1,3 @@ +ToolSet: 1.0 (local)Options: + +Options:-DCMAKE_MAKE_PROGRAM=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/ninja/mac/x64/ninja \ No newline at end of file diff --git a/cmake-build-debug/CMakeFiles/cmake.check_cache b/cmake-build-debug/CMakeFiles/cmake.check_cache new file mode 100644 index 00000000..3dccd731 --- /dev/null +++ b/cmake-build-debug/CMakeFiles/cmake.check_cache @@ -0,0 +1 @@ +# This file is generated by cmake for dependency checking of the CMakeCache.txt file diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index ac4f8fef..d902173a 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -1,314 +1,33 @@ -/* - * PSn00bSDK default memory allocator - * (C) 2022 Nicolas Noble, spicyjpeg - * - * This code is based on psyqo's malloc implementation, available here: - * https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c - * - * Heap management and memory allocation are completely separate, with the - * latter being built on top of the former. This makes it possible to override - * only InitHeap() and sbrk() while still using the default allocator, or - * override malloc()/realloc()/free() while using the default heap manager. - * Custom allocators should call TrackHeapUsage() to let the heap manager know - * how much memory is allocated at a given time. - */ +#include "tlsf.h" -#include -#include -#include -#include - -#define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) - -/* Private types */ - -typedef struct _BlockHeader { - struct _BlockHeader *prev, *next; - void *ptr; - size_t size; -} BlockHeader; - -/* Internal globals */ - -static void *_heap_start, *_heap_end, *_heap_limit; -static size_t _heap_alloc, _heap_alloc_max; - -static void *_alloc_start; -static BlockHeader *_alloc_head, *_alloc_tail; - -/* Heap management API */ +tlsf_t tlsf; __attribute__((weak)) void InitHeap(void *addr, size_t size) { - _heap_start = addr; - _heap_end = addr; - _heap_limit = (void *)((uintptr_t)addr + size); - - _heap_alloc = 0; - _heap_alloc_max = 0; - - _alloc_start = addr; - _alloc_head = 0; - _alloc_tail = 0; -} - -__attribute__((weak)) void *sbrk(ptrdiff_t incr) { - void *old_end = _heap_end; - void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); - printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, - new_end); - - if (new_end > _heap_limit) - return 0; - - _heap_end = new_end; - return old_end; + tlsf = tlsf_create_with_pool(addr, size); } __attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { - _heap_alloc += alloc_incr; - if (_heap_alloc > _heap_alloc_max) - _heap_alloc_max = _heap_alloc; } __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { - usage->total = _heap_limit - _heap_start; - usage->heap = _heap_end - _heap_start; - usage->stack = _heap_limit - _heap_end; - usage->alloc = _heap_alloc; - usage->alloc_max = _heap_alloc_max; } /* Memory allocator */ -static BlockHeader *_find_fit(BlockHeader *head, size_t size) { - BlockHeader *prev = head; - printf("[FindFit] size: 0x%x\n", size); - for (; prev; prev = prev->next) { - if (prev->next) { - uintptr_t next_bot = (uintptr_t)prev->next; - printf("[FindFit] next_bot: %p\n", (void *)next_bot); - next_bot -= (uintptr_t)prev->ptr + prev->size; - printf("[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", - prev->ptr, prev->size, prev->ptr + prev->size, (void *)next_bot); - if (next_bot >= size) { - printf("[FindFit] found %p\n", prev); - return prev; - } - } - } - printf("[FindFit] Not found: %p\n", prev); - return prev; -} - __attribute__((weak)) void *malloc(size_t size) { - if (!size) - return 0; - - size_t _size = _align(size + sizeof(BlockHeader), 8); - size_t _size_nh = _size - sizeof(BlockHeader); - - // Nothing's initialized yet? Let's just initialize the bottom of our heap, - // flag it as allocated. - if (!_alloc_head) { - // if (!_alloc_start) - //_alloc_start = sbrk(0); - - BlockHeader *new = (BlockHeader *)sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *)&new[1]; - new->ptr = ptr; - new->size = _size_nh; - new->prev = 0; - new->next = 0; - - _alloc_head = new; - _alloc_tail = new; - - TrackHeapUsage(_size); - return ptr; - } - - // We *may* have the bottom of our heap that has shifted, because of a free. - // So let's check first if we have free space there, because I'm nervous - // about having an incomplete data structure. - if (((uintptr_t)_alloc_start + _size) < ((uintptr_t)_alloc_head)) { - printf("[Malloc] bottom heap shifted: %p < %p\n", _alloc_start + _size, - _alloc_head); - BlockHeader *new = (BlockHeader *)_alloc_start; - - void *ptr = (void *)&new[1]; - new->ptr = ptr; - new->size = _size_nh; - new->prev = 0; - new->next = _alloc_head; - printf("[Malloc] new->next: %p\n", new->next); - - _alloc_head->prev = new; - _alloc_head = new; - - TrackHeapUsage(_size); - return ptr; - } - - // No luck at the beginning of the heap, let's walk the heap to find a fit. - BlockHeader *prev = _find_fit(_alloc_head, _size); - if (prev) { - BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); - printf("[Malloc] found fit: %p\n", new); - - void *ptr = (void *)&new[1]; - new->ptr = ptr; - new->size = _size_nh; - new->prev = prev; - new->next = prev->next; - printf("[Malloc] fit, new->next: %p\n", new->next); - - (new->next)->prev = new; - prev->next = new; - printf("[Malloc] fit, prev->next: %p\n", prev->next); - - TrackHeapUsage(_size); - return ptr; - } - - // Time to extend the size of the heap. - BlockHeader *new = (BlockHeader *)sbrk(_size); - if (!new) - return 0; - printf("[Malloc] extended heap: %p\n", new); - void *ptr = (void *)&new[1]; - new->ptr = ptr; - new->size = _size_nh; - new->prev = _alloc_tail; - new->next = 0; - - _alloc_tail->next = new; - printf("[Malloc] extend, _alloc_tail->next: %p\n", _alloc_tail->next); - _alloc_tail = new; - - TrackHeapUsage(_size); - return ptr; + return tlsf_malloc(tlsf_t, size); } __attribute__((weak)) void *calloc(size_t num, size_t size) { - return malloc(num * size); + return tlsf_malloc(tlsf, num * size); } __attribute__((weak)) void *realloc(void *ptr, size_t size) { - if (!size) { - free(ptr); - return 0; - } - if (!ptr) - return malloc(size); - - size_t _size = _align(size + sizeof(BlockHeader), 8); - size_t _size_nh = _size - sizeof(BlockHeader); - BlockHeader *prev = (BlockHeader *)((uintptr_t)ptr - sizeof(BlockHeader)); - - // New memory block shorter? - if (prev->size >= _size_nh) { - printf("[Realloc] new size shorter: 0x%x >= 0x%x\n", prev->size, _size_nh); - TrackHeapUsage(_size_nh - prev->size); - prev->size = _size_nh; - - // This is the last block, move the break back to accomodate shrinking - if (!prev->next) { - // We have overriden prev->size, need to calculate it from break - void *new_break = sbrk((ptr - sbrk(0)) + _size_nh); - printf("[Realloc] last block, shrink break: %p\n", new_break); - } - return ptr; - } - - // New memory block larger; is it the last one? - if (!prev->next) { - printf("[Realloc] new block larger\n"); - void *new = sbrk(_size_nh - prev->size); - if (!new) - return 0; - printf("[Realloc] new break: 0x%x => %p\n", _size_nh - prev->size, new); - TrackHeapUsage(_size_nh - prev->size); - prev->size = _size_nh; - return ptr; - } - - // Do we have free memory after it? - if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { - printf("[Realloc] free mem after: 0x%x >= 0x%x\n", - (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); - TrackHeapUsage(_size_nh - prev->size); - prev->size = _size_nh; - return ptr; - } - - // No luck. - void *new = malloc(size); - if (!new) - return 0; - printf("[Realloc] new malloc addr: %p\n", new); - __builtin_memcpy(new, ptr, prev->size); - free(ptr); - return new; + return tlsf_realloc(tlsf, ptr, size); } __attribute__((weak)) void free(void *ptr) { - if (!ptr || !_alloc_head) - return; - - // First block; bumping head ahead. - if (ptr == _alloc_head->ptr) { - printf("[Free] first block, bump head forward\n"); - size_t size = _alloc_head->size; - size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; - printf("[Free] size: 0x%x\n", size); - _alloc_head = _alloc_head->next; - printf("[Free] new head: %p\n", _alloc_head); - if (_alloc_head) { - _alloc_head->prev = 0; - printf("[Free] New head exists, setting prev to null\n"); - } else { - printf("[Free] No new head exists, nulling tail\n"); - _alloc_tail = 0; - sbrk(-size); - } - - TrackHeapUsage(-size); - return; - } - - // Finding the proper block - BlockHeader *cur = _alloc_head; - printf("[Free] find block, base: %p\n", cur); - for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { - if (!cur->next) - return; - } - printf("[Free] found: %p\n", cur); - - if (cur->next) { - // In the middle, just unlink it - printf("[Free] has next, setting next->prev to cur->prev: %p\n", cur->prev); - (cur->next)->prev = cur->prev; - } else { - // At the end, shrink heap - printf("[Free] at end of heap\n"); - void *top = sbrk(0); - printf("[Free] heap top: %p\n", top); - size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; - printf("[Free] size: 0x%x\n", size); - _alloc_tail = cur->prev; - - printf("[Free] new tail: %p\n", _alloc_tail); - sbrk(-size); - } - printf("[Free] heap_change: 0x%x\n", -(cur->size) - sizeof(BlockHeader)); - TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); - (cur->prev)->next = cur->next; - printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); - printf("[Free] setting prev->next to cur->next: %p\n", cur->next); -} + tlsf_free(tlsf, ptr); +} \ No newline at end of file diff --git a/libpsn00b/libc/malloc_old b/libpsn00b/libc/malloc_old new file mode 100644 index 00000000..a884c2d4 --- /dev/null +++ b/libpsn00b/libc/malloc_old @@ -0,0 +1,279 @@ +/* + * PSn00bSDK default memory allocator + * (C) 2022 Nicolas Noble, spicyjpeg + * + * This code is based on psyqo's malloc implementation, available here: + * https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c + * + * Heap management and memory allocation are completely separate, with the + * latter being built on top of the former. This makes it possible to override + * only InitHeap() and sbrk() while still using the default allocator, or + * override malloc()/realloc()/free() while using the default heap manager. + * Custom allocators should call TrackHeapUsage() to let the heap manager know + * how much memory is allocated at a given time. + */ + +#include +#include +#include + +#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) + +/* Private types */ + +typedef struct _BlockHeader { + struct _BlockHeader *prev, *next; + void *ptr; + size_t size; +} BlockHeader; + +/* Internal globals */ + +static void *_heap_start, *_heap_end, *_heap_limit; +static size_t _heap_alloc, _heap_alloc_max; + +static void *_alloc_start; +static BlockHeader *_alloc_head, *_alloc_tail; + +/* Heap management API */ + +__attribute__((weak)) void InitHeap(void *addr, size_t size) { + _heap_start = addr; + _heap_end = addr; + _heap_limit = (void *) ((uintptr_t) addr + size); + + _heap_alloc = 0; + _heap_alloc_max = 0; + + _alloc_start = addr; + _alloc_head = 0; + _alloc_tail = 0; +} + +__attribute__((weak)) void *sbrk(ptrdiff_t incr) { + void *old_end = _heap_end; + void *new_end = (void *) _align((uintptr_t) old_end + incr, 8); + + if (new_end > _heap_limit) + return 0; + + _heap_end = new_end; + return old_end; +} + +__attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { + _heap_alloc += alloc_incr; + + if (_heap_alloc > _heap_alloc_max) + _heap_alloc_max = _heap_alloc; +} + +__attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { + usage->total = _heap_limit - _heap_start; + usage->heap = _heap_end - _heap_start; + usage->stack = _heap_limit - _heap_end; + + usage->alloc = _heap_alloc; + usage->alloc_max = _heap_alloc_max; +} + +/* Memory allocator */ + +static BlockHeader *_find_fit(BlockHeader *head, size_t size) { + BlockHeader *prev = head; + + for (; prev; prev = prev->next) { + if (prev->next) { + uintptr_t next_bot = (uintptr_t) prev->next; + next_bot -= (uintptr_t) prev->ptr + prev->size; + + if (next_bot >= size) + return prev; + } + } + + return prev; +} + +__attribute__((weak)) void *malloc(size_t size) { + if (!size) + return 0; + + size_t _size = _align(size + sizeof(BlockHeader), 8); + + // Nothing's initialized yet? Let's just initialize the bottom of our heap, + // flag it as allocated. + if (!_alloc_head) { + //if (!_alloc_start) + //_alloc_start = sbrk(0); + + BlockHeader *new = (BlockHeader *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = 0; + + _alloc_head = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; + } + + // We *may* have the bottom of our heap that has shifted, because of a free. + // So let's check first if we have free space there, because I'm nervous + // about having an incomplete data structure. + if (((uintptr_t) _alloc_start + _size) < ((uintptr_t) _alloc_head)) { + BlockHeader *new = (BlockHeader *) _alloc_start; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = _alloc_head; + + _alloc_head->prev = new; + _alloc_head = new; + + TrackHeapUsage(size); + return ptr; + } + + // No luck at the beginning of the heap, let's walk the heap to find a fit. + BlockHeader *prev = _find_fit(_alloc_head, _size); + if (prev) { + BlockHeader *new = (BlockHeader *) ((uintptr_t) prev->ptr + prev->size); + + void *ptr = (void *)((uintptr_t) new + sizeof(BlockHeader)); + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = prev; + new->next = prev->next; + + (new->next)->prev = new; + prev->next = new; + + TrackHeapUsage(size); + return ptr; + } + + // Time to extend the size of the heap. + BlockHeader *new = (BlockHeader *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = _alloc_tail; + new->next = 0; + + _alloc_tail->next = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; +} + +__attribute__((weak)) void *calloc(size_t num, size_t size) { + return malloc(num * size); +} + +__attribute__((weak)) void *realloc(void *ptr, size_t size) { + if (!size) { + free(ptr); + return 0; + } + if (!ptr) + return malloc(size); + + size_t _size = _align(size + sizeof(BlockHeader), 8); + BlockHeader *prev = (BlockHeader *) ((uintptr_t) ptr - sizeof(BlockHeader)); + + // New memory block shorter? + if (prev->size >= _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + + if (!prev->next) + sbrk((ptr - sbrk(0)) + _size); + + return ptr; + } + + // New memory block larger; is it the last one? + if (!prev->next) { + void *new = sbrk(_size - prev->size); + if (!new) + return 0; + + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // Do we have free memory after it? + if (((prev->next)->ptr - ptr) > _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // No luck. + void *new = malloc(size); + if (!new) + return 0; + + __builtin_memcpy(new, ptr, prev->size); + free(ptr); + return new; +} + +__attribute__((weak)) void free(void *ptr) { + if (!ptr || !_alloc_head) + return; + + // First block; bumping head ahead. + if (ptr == _alloc_head->ptr) { + size_t size = _alloc_head->size; + size += (uintptr_t) _alloc_head->ptr - (uintptr_t) _alloc_head; + _alloc_head = _alloc_head->next; + + if (_alloc_head) { + _alloc_head->prev = 0; + } else { + _alloc_tail = 0; + sbrk(-size); + } + + TrackHeapUsage(-(_alloc_head->size)); + return; + } + + // Finding the proper block + BlockHeader *cur = _alloc_head; + + for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { + if (!cur->next) + return; + } + + if (cur->next) { + // In the middle, just unlink it + (cur->next)->prev = cur->prev; + } else { + // At the end, shrink heap + void *top = sbrk(0); + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + _alloc_tail = cur->prev; + + sbrk(-size); + } + + TrackHeapUsage(-(cur->size)); + (cur->prev)->next = cur->next; +} \ No newline at end of file diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c new file mode 100644 index 00000000..2c0169a4 --- /dev/null +++ b/libpsn00b/libc/tlsf.c @@ -0,0 +1,1264 @@ +#include +#include +#include +#include +#include +#include + +#include "tlsf.h" + +#if defined(__cplusplus) +#define tlsf_decl inline +#else +#define tlsf_decl static +#endif + +/* +** Architecture-specific bit manipulation routines. +** +** TLSF achieves O(1) cost for malloc and free operations by limiting +** the search for a free block to a free list of guaranteed size +** adequate to fulfill the request, combined with efficient free list +** queries using bitmasks and architecture-specific bit-manipulation +** routines. +** +** Most modern processors provide instructions to count leading zeroes +** in a word, find the lowest and highest set bit, etc. These +** specific implementations will be used when available, falling back +** to a reasonably efficient generic implementation. +** +** NOTE: TLSF spec relies on ffs/fls returning value 0..31. +** ffs/fls return 1-32 by default, returning 0 for error. +*/ + +/* +** Detect whether or not we are building for a 32- or 64-bit (LP/LLP) +** architecture. There is no reliable portable method at compile-time. +*/ +#if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) \ + || defined (_WIN64) || defined (__LP64__) || defined (__LLP64__) +#define TLSF_64BIT +#endif + +/* +** gcc 3.4 and above have builtin support, specialized for architecture. +** Some compilers masquerade as gcc; patchlevel test filters them out. +*/ +#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ + && defined (__GNUC_PATCHLEVEL__) + +#if defined (__SNC__) +/* SNC for Playstation 3. */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __builtin_clz(reverse); + return bit - 1; +} + +#else + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + return __builtin_ffs(word) - 1; +} + +#endif + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __builtin_clz(word) : 0; + return bit - 1; +} + +#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) +/* Microsoft Visual C++ support on x86/X64 architectures. */ + +#include + +#pragma intrinsic(_BitScanReverse) +#pragma intrinsic(_BitScanForward) + +tlsf_decl int tlsf_fls(unsigned int word) +{ + unsigned long index; + return _BitScanReverse(&index, word) ? index : -1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + unsigned long index; + return _BitScanForward(&index, word) ? index : -1; +} + +#elif defined (_MSC_VER) && defined (_M_PPC) +/* Microsoft Visual C++ support on PowerPC architectures. */ + +#include + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = 32 - _CountLeadingZeros(word); + return bit - 1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - _CountLeadingZeros(reverse); + return bit - 1; +} + +#elif defined (__ARMCC_VERSION) +/* RealView Compilation Tools for ARM */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __clz(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __clz(word) : 0; + return bit - 1; +} + +#elif defined (__ghs__) +/* Green Hills support for PowerPC */ + +#include + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __CLZ32(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __CLZ32(word) : 0; + return bit - 1; +} + +#else +/* Fall back to generic implementation. */ + +tlsf_decl int tlsf_fls_generic(unsigned int word) +{ + int bit = 32; + + if (!word) bit -= 1; + if (!(word & 0xffff0000)) { word <<= 16; bit -= 16; } + if (!(word & 0xff000000)) { word <<= 8; bit -= 8; } + if (!(word & 0xf0000000)) { word <<= 4; bit -= 4; } + if (!(word & 0xc0000000)) { word <<= 2; bit -= 2; } + if (!(word & 0x80000000)) { word <<= 1; bit -= 1; } + + return bit; +} + +/* Implement ffs in terms of fls. */ +tlsf_decl int tlsf_ffs(unsigned int word) +{ + return tlsf_fls_generic(word & (~word + 1)) - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + return tlsf_fls_generic(word) - 1; +} + +#endif + +/* Possibly 64-bit version of tlsf_fls. */ +#if defined (TLSF_64BIT) +tlsf_decl int tlsf_fls_sizet(size_t size) +{ + int high = (int)(size >> 32); + int bits = 0; + if (high) + { + bits = 32 + tlsf_fls(high); + } + else + { + bits = tlsf_fls((int)size & 0xffffffff); + + } + return bits; +} +#else +#define tlsf_fls_sizet tlsf_fls +#endif + +#undef tlsf_decl + +/* +** Constants. +*/ + +/* Public constants: may be modified. */ +enum tlsf_public +{ + /* log2 of number of linear subdivisions of block sizes. Larger + ** values require more memory in the control structure. Values of + ** 4 or 5 are typical. + */ + SL_INDEX_COUNT_LOG2 = 5, +}; + +/* Private constants: do not modify. */ +enum tlsf_private +{ +#if defined (TLSF_64BIT) + /* All allocation sizes and addresses are aligned to 8 bytes. */ + ALIGN_SIZE_LOG2 = 3, +#else + /* All allocation sizes and addresses are aligned to 4 bytes. */ + ALIGN_SIZE_LOG2 = 2, +#endif + ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2), + + /* + ** We support allocations of sizes up to (1 << FL_INDEX_MAX) bits. + ** However, because we linearly subdivide the second-level lists, and + ** our minimum size granularity is 4 bytes, it doesn't make sense to + ** create first-level lists for sizes smaller than SL_INDEX_COUNT * 4, + ** or (1 << (SL_INDEX_COUNT_LOG2 + 2)) bytes, as there we will be + ** trying to split size ranges into more slots than we have available. + ** Instead, we calculate the minimum threshold size, and place all + ** blocks below that size into the 0th first-level list. + */ + +#if defined (TLSF_64BIT) + /* + ** TODO: We can increase this to support larger sizes, at the expense + ** of more overhead in the TLSF structure. + */ + FL_INDEX_MAX = 32, +#else + FL_INDEX_MAX = 30, +#endif + SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2), + FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2), + FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1), + + SMALL_BLOCK_SIZE = (1 << FL_INDEX_SHIFT), +}; + +/* +** Cast and min/max macros. +*/ + +#define tlsf_cast(t, exp) ((t) (exp)) +#define tlsf_min(a, b) ((a) < (b) ? (a) : (b)) +#define tlsf_max(a, b) ((a) > (b) ? (a) : (b)) + +/* +** Set assert macro, if it has not been provided by the user. +*/ +#if !defined (tlsf_assert) +#define tlsf_assert assert +#endif + +/* +** Static assertion mechanism. +*/ + +#define _tlsf_glue2(x, y) x ## y +#define _tlsf_glue(x, y) _tlsf_glue2(x, y) +#define tlsf_static_assert(exp) \ + typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1] + +/* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */ +tlsf_static_assert(sizeof(int) * CHAR_BIT == 32); +tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32); +tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64); + +/* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */ +tlsf_static_assert(sizeof(unsigned int) * CHAR_BIT >= SL_INDEX_COUNT); + +/* Ensure we've properly tuned our sizes. */ +tlsf_static_assert(ALIGN_SIZE == SMALL_BLOCK_SIZE / SL_INDEX_COUNT); + +/* +** Data structures and associated constants. +*/ + +/* +** Block header structure. +** +** There are several implementation subtleties involved: +** - The prev_phys_block field is only valid if the previous block is free. +** - The prev_phys_block field is actually stored at the end of the +** previous block. It appears at the beginning of this structure only to +** simplify the implementation. +** - The next_free / prev_free fields are only valid if the block is free. +*/ +typedef struct block_header_t +{ + /* Points to the previous physical block. */ + struct block_header_t* prev_phys_block; + + /* The size of this block, excluding the block header. */ + size_t size; + + /* Next and previous free blocks. */ + struct block_header_t* next_free; + struct block_header_t* prev_free; +} block_header_t; + +/* +** Since block sizes are always at least a multiple of 4, the two least +** significant bits of the size field are used to store the block status: +** - bit 0: whether block is busy or free +** - bit 1: whether previous block is busy or free +*/ +static const size_t block_header_free_bit = 1 << 0; +static const size_t block_header_prev_free_bit = 1 << 1; + +/* +** The size of the block header exposed to used blocks is the size field. +** The prev_phys_block field is stored *inside* the previous free block. +*/ +static const size_t block_header_overhead = sizeof(size_t); + +/* User data starts directly after the size field in a used block. */ +static const size_t block_start_offset = + offsetof(block_header_t, size) + sizeof(size_t); + +/* +** A free block must be large enough to store its header minus the size of +** the prev_phys_block field, and no larger than the number of addressable +** bits for FL_INDEX. +*/ +static const size_t block_size_min = + sizeof(block_header_t) - sizeof(block_header_t*); +static const size_t block_size_max = tlsf_cast(size_t, 1) << FL_INDEX_MAX; + + +/* The TLSF control structure. */ +typedef struct control_t +{ + /* Empty lists point at this block to indicate they are free. */ + block_header_t block_null; + + /* Bitmaps for free lists. */ + unsigned int fl_bitmap; + unsigned int sl_bitmap[FL_INDEX_COUNT]; + + /* Head of free lists. */ + block_header_t* blocks[FL_INDEX_COUNT][SL_INDEX_COUNT]; +} control_t; + +/* A type used for casting when doing pointer arithmetic. */ +typedef ptrdiff_t tlsfptr_t; + +/* +** block_header_t member functions. +*/ + +static size_t block_size(const block_header_t* block) +{ + return block->size & ~(block_header_free_bit | block_header_prev_free_bit); +} + +static void block_set_size(block_header_t* block, size_t size) +{ + const size_t oldsize = block->size; + block->size = size | (oldsize & (block_header_free_bit | block_header_prev_free_bit)); +} + +static int block_is_last(const block_header_t* block) +{ + return block_size(block) == 0; +} + +static int block_is_free(const block_header_t* block) +{ + return tlsf_cast(int, block->size & block_header_free_bit); +} + +static void block_set_free(block_header_t* block) +{ + block->size |= block_header_free_bit; +} + +static void block_set_used(block_header_t* block) +{ + block->size &= ~block_header_free_bit; +} + +static int block_is_prev_free(const block_header_t* block) +{ + return tlsf_cast(int, block->size & block_header_prev_free_bit); +} + +static void block_set_prev_free(block_header_t* block) +{ + block->size |= block_header_prev_free_bit; +} + +static void block_set_prev_used(block_header_t* block) +{ + block->size &= ~block_header_prev_free_bit; +} + +static block_header_t* block_from_ptr(const void* ptr) +{ + return tlsf_cast(block_header_t*, + tlsf_cast(unsigned char*, ptr) - block_start_offset); +} + +static void* block_to_ptr(const block_header_t* block) +{ + return tlsf_cast(void*, + tlsf_cast(unsigned char*, block) + block_start_offset); +} + +/* Return location of next block after block of given size. */ +static block_header_t* offset_to_block(const void* ptr, size_t size) +{ + return tlsf_cast(block_header_t*, tlsf_cast(tlsfptr_t, ptr) + size); +} + +/* Return location of previous block. */ +static block_header_t* block_prev(const block_header_t* block) +{ + tlsf_assert(block_is_prev_free(block) && "previous block must be free"); + return block->prev_phys_block; +} + +/* Return location of next existing block. */ +static block_header_t* block_next(const block_header_t* block) +{ + block_header_t* next = offset_to_block(block_to_ptr(block), + block_size(block) - block_header_overhead); + tlsf_assert(!block_is_last(block)); + return next; +} + +/* Link a new block with its physical neighbor, return the neighbor. */ +static block_header_t* block_link_next(block_header_t* block) +{ + block_header_t* next = block_next(block); + next->prev_phys_block = block; + return next; +} + +static void block_mark_as_free(block_header_t* block) +{ + /* Link the block to the next block, first. */ + block_header_t* next = block_link_next(block); + block_set_prev_free(next); + block_set_free(block); +} + +static void block_mark_as_used(block_header_t* block) +{ + block_header_t* next = block_next(block); + block_set_prev_used(next); + block_set_used(block); +} + +static size_t align_up(size_t x, size_t align) +{ + tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); + return (x + (align - 1)) & ~(align - 1); +} + +static size_t align_down(size_t x, size_t align) +{ + tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); + return x - (x & (align - 1)); +} + +static void* align_ptr(const void* ptr, size_t align) +{ + const tlsfptr_t aligned = + (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1); + tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); + return tlsf_cast(void*, aligned); +} + +/* +** Adjust an allocation size to be aligned to word size, and no smaller +** than internal minimum. +*/ +static size_t adjust_request_size(size_t size, size_t align) +{ + size_t adjust = 0; + if (size) + { + const size_t aligned = align_up(size, align); + + /* aligned sized must not exceed block_size_max or we'll go out of bounds on sl_bitmap */ + if (aligned < block_size_max) + { + adjust = tlsf_max(aligned, block_size_min); + } + } + return adjust; +} + +/* +** TLSF utility functions. In most cases, these are direct translations of +** the documentation found in the white paper. +*/ + +static void mapping_insert(size_t size, int* fli, int* sli) +{ + int fl, sl; + if (size < SMALL_BLOCK_SIZE) + { + /* Store small blocks in first list. */ + fl = 0; + sl = tlsf_cast(int, size) / (SMALL_BLOCK_SIZE / SL_INDEX_COUNT); + } + else + { + fl = tlsf_fls_sizet(size); + sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2); + fl -= (FL_INDEX_SHIFT - 1); + } + *fli = fl; + *sli = sl; +} + +/* This version rounds up to the next block size (for allocations) */ +static void mapping_search(size_t size, int* fli, int* sli) +{ + if (size >= SMALL_BLOCK_SIZE) + { + const size_t round = (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1; + size += round; + } + mapping_insert(size, fli, sli); +} + +static block_header_t* search_suitable_block(control_t* control, int* fli, int* sli) +{ + int fl = *fli; + int sl = *sli; + + /* + ** First, search for a block in the list associated with the given + ** fl/sl index. + */ + unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl); + if (!sl_map) + { + /* No block exists. Search in the next largest first-level list. */ + const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1)); + if (!fl_map) + { + /* No free blocks available, memory has been exhausted. */ + return 0; + } + + fl = tlsf_ffs(fl_map); + *fli = fl; + sl_map = control->sl_bitmap[fl]; + } + tlsf_assert(sl_map && "internal error - second level bitmap is null"); + sl = tlsf_ffs(sl_map); + *sli = sl; + + /* Return the first block in the free list. */ + return control->blocks[fl][sl]; +} + +/* Remove a free block from the free list.*/ +static void remove_free_block(control_t* control, block_header_t* block, int fl, int sl) +{ + block_header_t* prev = block->prev_free; + block_header_t* next = block->next_free; + tlsf_assert(prev && "prev_free field can not be null"); + tlsf_assert(next && "next_free field can not be null"); + next->prev_free = prev; + prev->next_free = next; + + /* If this block is the head of the free list, set new head. */ + if (control->blocks[fl][sl] == block) + { + control->blocks[fl][sl] = next; + + /* If the new head is null, clear the bitmap. */ + if (next == &control->block_null) + { + control->sl_bitmap[fl] &= ~(1U << sl); + + /* If the second bitmap is now empty, clear the fl bitmap. */ + if (!control->sl_bitmap[fl]) + { + control->fl_bitmap &= ~(1U << fl); + } + } + } +} + +/* Insert a free block into the free block list. */ +static void insert_free_block(control_t* control, block_header_t* block, int fl, int sl) +{ + block_header_t* current = control->blocks[fl][sl]; + tlsf_assert(current && "free list cannot have a null entry"); + tlsf_assert(block && "cannot insert a null entry into the free list"); + block->next_free = current; + block->prev_free = &control->block_null; + current->prev_free = block; + + tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE) + && "block not aligned properly"); + /* + ** Insert the new block at the head of the list, and mark the first- + ** and second-level bitmaps appropriately. + */ + control->blocks[fl][sl] = block; + control->fl_bitmap |= (1U << fl); + control->sl_bitmap[fl] |= (1U << sl); +} + +/* Remove a given block from the free list. */ +static void block_remove(control_t* control, block_header_t* block) +{ + int fl, sl; + mapping_insert(block_size(block), &fl, &sl); + remove_free_block(control, block, fl, sl); +} + +/* Insert a given block into the free list. */ +static void block_insert(control_t* control, block_header_t* block) +{ + int fl, sl; + mapping_insert(block_size(block), &fl, &sl); + insert_free_block(control, block, fl, sl); +} + +static int block_can_split(block_header_t* block, size_t size) +{ + return block_size(block) >= sizeof(block_header_t) + size; +} + +/* Split a block into two, the second of which is free. */ +static block_header_t* block_split(block_header_t* block, size_t size) +{ + /* Calculate the amount of space left in the remaining block. */ + block_header_t* remaining = + offset_to_block(block_to_ptr(block), size - block_header_overhead); + + const size_t remain_size = block_size(block) - (size + block_header_overhead); + + tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE) + && "remaining block not aligned properly"); + + tlsf_assert(block_size(block) == remain_size + size + block_header_overhead); + block_set_size(remaining, remain_size); + tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size"); + + block_set_size(block, size); + block_mark_as_free(remaining); + + return remaining; +} + +/* Absorb a free block's storage into an adjacent previous free block. */ +static block_header_t* block_absorb(block_header_t* prev, block_header_t* block) +{ + tlsf_assert(!block_is_last(prev) && "previous block can't be last"); + /* Note: Leaves flags untouched. */ + prev->size += block_size(block) + block_header_overhead; + block_link_next(prev); + return prev; +} + +/* Merge a just-freed block with an adjacent previous free block. */ +static block_header_t* block_merge_prev(control_t* control, block_header_t* block) +{ + if (block_is_prev_free(block)) + { + block_header_t* prev = block_prev(block); + tlsf_assert(prev && "prev physical block can't be null"); + tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such"); + block_remove(control, prev); + block = block_absorb(prev, block); + } + + return block; +} + +/* Merge a just-freed block with an adjacent free block. */ +static block_header_t* block_merge_next(control_t* control, block_header_t* block) +{ + block_header_t* next = block_next(block); + tlsf_assert(next && "next physical block can't be null"); + + if (block_is_free(next)) + { + tlsf_assert(!block_is_last(block) && "previous block can't be last"); + block_remove(control, next); + block = block_absorb(block, next); + } + + return block; +} + +/* Trim any trailing block space off the end of a block, return to pool. */ +static void block_trim_free(control_t* control, block_header_t* block, size_t size) +{ + tlsf_assert(block_is_free(block) && "block must be free"); + if (block_can_split(block, size)) + { + block_header_t* remaining_block = block_split(block, size); + block_link_next(block); + block_set_prev_free(remaining_block); + block_insert(control, remaining_block); + } +} + +/* Trim any trailing block space off the end of a used block, return to pool. */ +static void block_trim_used(control_t* control, block_header_t* block, size_t size) +{ + tlsf_assert(!block_is_free(block) && "block must be used"); + if (block_can_split(block, size)) + { + /* If the next block is free, we must coalesce. */ + block_header_t* remaining_block = block_split(block, size); + block_set_prev_used(remaining_block); + + remaining_block = block_merge_next(control, remaining_block); + block_insert(control, remaining_block); + } +} + +static block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size) +{ + block_header_t* remaining_block = block; + if (block_can_split(block, size)) + { + /* We want the 2nd block. */ + remaining_block = block_split(block, size - block_header_overhead); + block_set_prev_free(remaining_block); + + block_link_next(block); + block_insert(control, block); + } + + return remaining_block; +} + +static block_header_t* block_locate_free(control_t* control, size_t size) +{ + int fl = 0, sl = 0; + block_header_t* block = 0; + + if (size) + { + mapping_search(size, &fl, &sl); + + /* + ** mapping_search can futz with the size, so for excessively large sizes it can sometimes wind up + ** with indices that are off the end of the block array. + ** So, we protect against that here, since this is the only callsite of mapping_search. + ** Note that we don't need to check sl, since it comes from a modulo operation that guarantees it's always in range. + */ + if (fl < FL_INDEX_COUNT) + { + block = search_suitable_block(control, &fl, &sl); + } + } + + if (block) + { + tlsf_assert(block_size(block) >= size); + remove_free_block(control, block, fl, sl); + } + + return block; +} + +static void* block_prepare_used(control_t* control, block_header_t* block, size_t size) +{ + void* p = 0; + if (block) + { + tlsf_assert(size && "size must be non-zero"); + block_trim_free(control, block, size); + block_mark_as_used(block); + p = block_to_ptr(block); + } + return p; +} + +/* Clear structure and point all empty lists at the null block. */ +static void control_construct(control_t* control) +{ + int i, j; + + control->block_null.next_free = &control->block_null; + control->block_null.prev_free = &control->block_null; + + control->fl_bitmap = 0; + for (i = 0; i < FL_INDEX_COUNT; ++i) + { + control->sl_bitmap[i] = 0; + for (j = 0; j < SL_INDEX_COUNT; ++j) + { + control->blocks[i][j] = &control->block_null; + } + } +} + +/* +** Debugging utilities. +*/ + +typedef struct integrity_t +{ + int prev_status; + int status; +} integrity_t; + +#define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } } + +static void integrity_walker(void* ptr, size_t size, int used, void* user) +{ + block_header_t* block = block_from_ptr(ptr); + integrity_t* integ = tlsf_cast(integrity_t*, user); + const int this_prev_status = block_is_prev_free(block) ? 1 : 0; + const int this_status = block_is_free(block) ? 1 : 0; + const size_t this_block_size = block_size(block); + + int status = 0; + (void)used; + tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect"); + tlsf_insist(size == this_block_size && "block size incorrect"); + + integ->prev_status = this_status; + integ->status += status; +} + +int tlsf_check(tlsf_t tlsf) +{ + int i, j; + + control_t* control = tlsf_cast(control_t*, tlsf); + int status = 0; + + /* Check that the free lists and bitmaps are accurate. */ + for (i = 0; i < FL_INDEX_COUNT; ++i) + { + for (j = 0; j < SL_INDEX_COUNT; ++j) + { + const int fl_map = control->fl_bitmap & (1U << i); + const int sl_list = control->sl_bitmap[i]; + const int sl_map = sl_list & (1U << j); + const block_header_t* block = control->blocks[i][j]; + + /* Check that first- and second-level lists agree. */ + if (!fl_map) + { + tlsf_insist(!sl_map && "second-level map must be null"); + } + + if (!sl_map) + { + tlsf_insist(block == &control->block_null && "block list must be null"); + continue; + } + + /* Check that there is at least one free block. */ + tlsf_insist(sl_list && "no free blocks in second-level map"); + tlsf_insist(block != &control->block_null && "block should not be null"); + + while (block != &control->block_null) + { + int fli, sli; + tlsf_insist(block_is_free(block) && "block should be free"); + tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced"); + tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced"); + tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free"); + tlsf_insist(block_size(block) >= block_size_min && "block not minimum size"); + + mapping_insert(block_size(block), &fli, &sli); + tlsf_insist(fli == i && sli == j && "block size indexed in wrong list"); + block = block->next_free; + } + } + } + + return status; +} + +#undef tlsf_insist + +static void default_walker(void* ptr, size_t size, int used, void* user) +{ + (void)user; + printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr)); +} + +void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user) +{ + tlsf_walker pool_walker = walker ? walker : default_walker; + block_header_t* block = + offset_to_block(pool, -(int)block_header_overhead); + + while (block && !block_is_last(block)) + { + pool_walker( + block_to_ptr(block), + block_size(block), + !block_is_free(block), + user); + block = block_next(block); + } +} + +size_t tlsf_block_size(void* ptr) +{ + size_t size = 0; + if (ptr) + { + const block_header_t* block = block_from_ptr(ptr); + size = block_size(block); + } + return size; +} + +int tlsf_check_pool(pool_t pool) +{ + /* Check that the blocks are physically correct. */ + integrity_t integ = { 0, 0 }; + tlsf_walk_pool(pool, integrity_walker, &integ); + + return integ.status; +} + +/* +** Size of the TLSF structures in a given memory block passed to +** tlsf_create, equal to the size of a control_t +*/ +size_t tlsf_size(void) +{ + return sizeof(control_t); +} + +size_t tlsf_align_size(void) +{ + return ALIGN_SIZE; +} + +size_t tlsf_block_size_min(void) +{ + return block_size_min; +} + +size_t tlsf_block_size_max(void) +{ + return block_size_max; +} + +/* +** Overhead of the TLSF structures in a given memory block passed to +** tlsf_add_pool, equal to the overhead of a free block and the +** sentinel block. +*/ +size_t tlsf_pool_overhead(void) +{ + return 2 * block_header_overhead; +} + +size_t tlsf_alloc_overhead(void) +{ + return block_header_overhead; +} + +pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) +{ + block_header_t* block; + block_header_t* next; + + const size_t pool_overhead = tlsf_pool_overhead(); + const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE); + + if (((ptrdiff_t)mem % ALIGN_SIZE) != 0) + { + printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n", + (unsigned int)ALIGN_SIZE); + return 0; + } + + if (pool_bytes < block_size_min || pool_bytes > block_size_max) + { +#if defined (TLSF_64BIT) + printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n", + (unsigned int)(pool_overhead + block_size_min), + (unsigned int)((pool_overhead + block_size_max) / 256)); +#else + printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n", + (unsigned int)(pool_overhead + block_size_min), + (unsigned int)(pool_overhead + block_size_max)); +#endif + return 0; + } + + /* + ** Create the main free block. Offset the start of the block slightly + ** so that the prev_phys_block field falls outside of the pool - + ** it will never be used. + */ + block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead); + block_set_size(block, pool_bytes); + block_set_free(block); + block_set_prev_used(block); + block_insert(tlsf_cast(control_t*, tlsf), block); + + /* Split the block to create a zero-size sentinel block. */ + next = block_link_next(block); + block_set_size(next, 0); + block_set_used(next); + block_set_prev_free(next); + + return mem; +} + +void tlsf_remove_pool(tlsf_t tlsf, pool_t pool) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + block_header_t* block = offset_to_block(pool, -(int)block_header_overhead); + + int fl = 0, sl = 0; + + tlsf_assert(block_is_free(block) && "block should be free"); + tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free"); + tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero"); + + mapping_insert(block_size(block), &fl, &sl); + remove_free_block(control, block, fl, sl); +} + +/* +** TLSF main interface. +*/ + +#if _DEBUG +int test_ffs_fls() +{ + /* Verify ffs/fls work properly. */ + int rv = 0; + rv += (tlsf_ffs(0) == -1) ? 0 : 0x1; + rv += (tlsf_fls(0) == -1) ? 0 : 0x2; + rv += (tlsf_ffs(1) == 0) ? 0 : 0x4; + rv += (tlsf_fls(1) == 0) ? 0 : 0x8; + rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10; + rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20; + rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40; + rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80; + +#if defined (TLSF_64BIT) + rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100; + rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200; + rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400; +#endif + + if (rv) + { + printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv); + } + return rv; +} +#endif + +tlsf_t tlsf_create(void* mem) +{ +#if _DEBUG + if (test_ffs_fls()) + { + return 0; + } +#endif + + if (((tlsfptr_t)mem % ALIGN_SIZE) != 0) + { + printf("tlsf_create: Memory must be aligned to %u bytes.\n", + (unsigned int)ALIGN_SIZE); + return 0; + } + + control_construct(tlsf_cast(control_t*, mem)); + + return tlsf_cast(tlsf_t, mem); +} + +tlsf_t tlsf_create_with_pool(void* mem, size_t bytes) +{ + tlsf_t tlsf = tlsf_create(mem); + tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size()); + return tlsf; +} + +void tlsf_destroy(tlsf_t tlsf) +{ + /* Nothing to do. */ + (void)tlsf; +} + +pool_t tlsf_get_pool(tlsf_t tlsf) +{ + return tlsf_cast(pool_t, (char*)tlsf + tlsf_size()); +} + +void* tlsf_malloc(tlsf_t tlsf, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + const size_t adjust = adjust_request_size(size, ALIGN_SIZE); + block_header_t* block = block_locate_free(control, adjust); + return block_prepare_used(control, block, adjust); +} + +void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + const size_t adjust = adjust_request_size(size, ALIGN_SIZE); + + /* + ** We must allocate an additional minimum block size bytes so that if + ** our free block will leave an alignment gap which is smaller, we can + ** trim a leading free block and release it back to the pool. We must + ** do this because the previous physical block is in use, therefore + ** the prev_phys_block field is not valid, and we can't simply adjust + ** the size of that block. + */ + const size_t gap_minimum = sizeof(block_header_t); + const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align); + + /* + ** If alignment is less than or equals base alignment, we're done. + ** If we requested 0 bytes, return null, as tlsf_malloc(0) does. + */ + const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust; + + block_header_t* block = block_locate_free(control, aligned_size); + + /* This can't be a static assert. */ + tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead); + + if (block) + { + void* ptr = block_to_ptr(block); + void* aligned = align_ptr(ptr, align); + size_t gap = tlsf_cast(size_t, + tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); + + /* If gap size is too small, offset to next aligned boundary. */ + if (gap && gap < gap_minimum) + { + const size_t gap_remain = gap_minimum - gap; + const size_t offset = tlsf_max(gap_remain, align); + const void* next_aligned = tlsf_cast(void*, + tlsf_cast(tlsfptr_t, aligned) + offset); + + aligned = align_ptr(next_aligned, align); + gap = tlsf_cast(size_t, + tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); + } + + if (gap) + { + tlsf_assert(gap >= gap_minimum && "gap size too small"); + block = block_trim_free_leading(control, block, gap); + } + } + + return block_prepare_used(control, block, adjust); +} + +void tlsf_free(tlsf_t tlsf, void* ptr) +{ + /* Don't attempt to free a NULL pointer. */ + if (ptr) + { + control_t* control = tlsf_cast(control_t*, tlsf); + block_header_t* block = block_from_ptr(ptr); + tlsf_assert(!block_is_free(block) && "block already marked as free"); + block_mark_as_free(block); + block = block_merge_prev(control, block); + block = block_merge_next(control, block); + block_insert(control, block); + } +} + +/* +** The TLSF block information provides us with enough information to +** provide a reasonably intelligent implementation of realloc, growing or +** shrinking the currently allocated block as required. +** +** This routine handles the somewhat esoteric edge cases of realloc: +** - a non-zero size with a null pointer will behave like malloc +** - a zero size with a non-null pointer will behave like free +** - a request that cannot be satisfied will leave the original buffer +** untouched +** - an extended buffer size will leave the newly-allocated area with +** contents undefined +*/ +void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + void* p = 0; + + /* Zero-size requests are treated as free. */ + if (ptr && size == 0) + { + tlsf_free(tlsf, ptr); + } + /* Requests with NULL pointers are treated as malloc. */ + else if (!ptr) + { + p = tlsf_malloc(tlsf, size); + } + else + { + block_header_t* block = block_from_ptr(ptr); + block_header_t* next = block_next(block); + + const size_t cursize = block_size(block); + const size_t combined = cursize + block_size(next) + block_header_overhead; + const size_t adjust = adjust_request_size(size, ALIGN_SIZE); + + tlsf_assert(!block_is_free(block) && "block already marked as free"); + + /* + ** If the next block is used, or when combined with the current + ** block, does not offer enough space, we must reallocate and copy. + */ + if (adjust > cursize && (!block_is_free(next) || adjust > combined)) + { + p = tlsf_malloc(tlsf, size); + if (p) + { + const size_t minsize = tlsf_min(cursize, size); + memcpy(p, ptr, minsize); + tlsf_free(tlsf, ptr); + } + } + else + { + /* Do we need to expand to the next block? */ + if (adjust > cursize) + { + block_merge_next(control, block); + block_mark_as_used(block); + } + + /* Trim the resulting block and return the original pointer. */ + block_trim_used(control, block, adjust); + p = ptr; + } + } + + return p; +} \ No newline at end of file diff --git a/libpsn00b/libc/tlsf.h b/libpsn00b/libc/tlsf.h new file mode 100644 index 00000000..399f80ad --- /dev/null +++ b/libpsn00b/libc/tlsf.h @@ -0,0 +1,92 @@ +#pragma once + +#ifndef INCLUDED_tlsf +#define INCLUDED_tlsf + +/* +** Two Level Segregated Fit memory allocator, version 3.1. +** Written by Matthew Conte +** http://tlsf.baisoku.org +** +** Based on the original documentation by Miguel Masmano: +** http://www.gii.upv.es/tlsf/main/docs +** +** This implementation was written to the specification +** of the document, therefore no GPL restrictions apply. +** +** Copyright (c) 2006-2016, Matthew Conte +** All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in the +** documentation and/or other materials provided with the distribution. +** * Neither the name of the copyright holder nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +** DISCLAIMED. IN NO EVENT SHALL MATTHEW CONTE BE LIABLE FOR ANY +** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include + +#if defined(__cplusplus) +extern "C" { +#endif + +/* tlsf_t: a TLSF structure. Can contain 1 to N pools. */ +/* pool_t: a block of memory that TLSF can manage. */ +typedef void* tlsf_t; +typedef void* pool_t; + +/* Create/destroy a memory pool. */ +tlsf_t tlsf_create(void* mem); +tlsf_t tlsf_create_with_pool(void* mem, size_t bytes); +void tlsf_destroy(tlsf_t tlsf); +pool_t tlsf_get_pool(tlsf_t tlsf); + +/* Add/remove memory pools. */ +pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes); +void tlsf_remove_pool(tlsf_t tlsf, pool_t pool); + +/* malloc/memalign/realloc/free replacements. */ +void* tlsf_malloc(tlsf_t tlsf, size_t bytes); +void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t bytes); +void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size); +void tlsf_free(tlsf_t tlsf, void* ptr); + +/* Returns internal block size, not original request size */ +size_t tlsf_block_size(void* ptr); + +/* Overheads/limits of internal structures. */ +size_t tlsf_size(void); +size_t tlsf_align_size(void); +size_t tlsf_block_size_min(void); +size_t tlsf_block_size_max(void); +size_t tlsf_pool_overhead(void); +size_t tlsf_alloc_overhead(void); + +/* Debugging. */ +typedef void (*tlsf_walker)(void* ptr, size_t size, int used, void* user); +void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user); +/* Returns nonzero if any internal consistency check fails. */ +int tlsf_check(tlsf_t tlsf); +int tlsf_check_pool(pool_t pool); + +#if defined(__cplusplus) +}; +#endif + +#endif \ No newline at end of file From e0fde1d3c510e4ffcceec41bb112acb5be668777 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 20:47:36 +1100 Subject: [PATCH 024/128] Migrated to TLSF --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index d902173a..d7e6444a 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -17,7 +17,7 @@ __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { /* Memory allocator */ __attribute__((weak)) void *malloc(size_t size) { - return tlsf_malloc(tlsf_t, size); + return tlsf_malloc(tlsf, size); } __attribute__((weak)) void *calloc(size_t num, size_t size) { From 6277b2c386fe2ed1619dff43638c9879b681a999 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 20:50:11 +1100 Subject: [PATCH 025/128] Migrated to TLSF --- libpsn00b/libc/malloc.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index d7e6444a..47fbf346 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -1,5 +1,11 @@ #include "tlsf.h" +typedef struct _BlockHeader { + struct _BlockHeader *prev, *next; + void *ptr; + size_t size; +} BlockHeader; + tlsf_t tlsf; __attribute__((weak)) void InitHeap(void *addr, size_t size) { From f3da2823c996103c5119d83444f64a044904a2f5 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 20:54:42 +1100 Subject: [PATCH 026/128] Migrated to TLSF --- libpsn00b/libc/malloc.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 47fbf346..14dc3d5f 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -1,5 +1,9 @@ #include "tlsf.h" +#include +#include +#include + typedef struct _BlockHeader { struct _BlockHeader *prev, *next; void *ptr; From e9c66a9a816f4fcb6b10cc85aeb38fbe3a48d7a5 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:14:38 +1100 Subject: [PATCH 027/128] Migrated to TLSF --- libpsn00b/libc/tlsf.c | 212 +++++++++++++++++++++--------------------- 1 file changed, 106 insertions(+), 106 deletions(-) diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c index 2c0169a4..eeb64c3d 100644 --- a/libpsn00b/libc/tlsf.c +++ b/libpsn00b/libc/tlsf.c @@ -40,111 +40,111 @@ #define TLSF_64BIT #endif -/* -** gcc 3.4 and above have builtin support, specialized for architecture. -** Some compilers masquerade as gcc; patchlevel test filters them out. -*/ -#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ - && defined (__GNUC_PATCHLEVEL__) - -#if defined (__SNC__) -/* SNC for Playstation 3. */ - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __builtin_clz(reverse); - return bit - 1; -} - -#else - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - return __builtin_ffs(word) - 1; -} - -#endif - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __builtin_clz(word) : 0; - return bit - 1; -} - -#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) -/* Microsoft Visual C++ support on x86/X64 architectures. */ - -#include - -#pragma intrinsic(_BitScanReverse) -#pragma intrinsic(_BitScanForward) - -tlsf_decl int tlsf_fls(unsigned int word) -{ - unsigned long index; - return _BitScanReverse(&index, word) ? index : -1; -} - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - unsigned long index; - return _BitScanForward(&index, word) ? index : -1; -} - -#elif defined (_MSC_VER) && defined (_M_PPC) -/* Microsoft Visual C++ support on PowerPC architectures. */ - -#include - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = 32 - _CountLeadingZeros(word); - return bit - 1; -} - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - _CountLeadingZeros(reverse); - return bit - 1; -} - -#elif defined (__ARMCC_VERSION) -/* RealView Compilation Tools for ARM */ - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __clz(reverse); - return bit - 1; -} - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __clz(word) : 0; - return bit - 1; -} - -#elif defined (__ghs__) -/* Green Hills support for PowerPC */ - -#include - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __CLZ32(reverse); - return bit - 1; -} - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __CLZ32(word) : 0; - return bit - 1; -} - -#else +// /* +// ** gcc 3.4 and above have builtin support, specialized for architecture. +// ** Some compilers masquerade as gcc; patchlevel test filters them out. +// */ +// #if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ +// && defined (__GNUC_PATCHLEVEL__) +// +// #if defined (__SNC__) +// /* SNC for Playstation 3. */ +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// const unsigned int reverse = word & (~word + 1); +// const int bit = 32 - __builtin_clz(reverse); +// return bit - 1; +// } +// +// #else +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// return __builtin_ffs(word) - 1; +// } +// +// #endif +// +// tlsf_decl int tlsf_fls(unsigned int word) +// { +// const int bit = word ? 32 - __builtin_clz(word) : 0; +// return bit - 1; +// } +// +// #elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) +// /* Microsoft Visual C++ support on x86/X64 architectures. */ +// +// #include +// +// #pragma intrinsic(_BitScanReverse) +// #pragma intrinsic(_BitScanForward) +// +// tlsf_decl int tlsf_fls(unsigned int word) +// { +// unsigned long index; +// return _BitScanReverse(&index, word) ? index : -1; +// } +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// unsigned long index; +// return _BitScanForward(&index, word) ? index : -1; +// } +// +// #elif defined (_MSC_VER) && defined (_M_PPC) +// /* Microsoft Visual C++ support on PowerPC architectures. */ +// +// #include +// +// tlsf_decl int tlsf_fls(unsigned int word) +// { +// const int bit = 32 - _CountLeadingZeros(word); +// return bit - 1; +// } +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// const unsigned int reverse = word & (~word + 1); +// const int bit = 32 - _CountLeadingZeros(reverse); +// return bit - 1; +// } +// +// #elif defined (__ARMCC_VERSION) +// /* RealView Compilation Tools for ARM */ +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// const unsigned int reverse = word & (~word + 1); +// const int bit = 32 - __clz(reverse); +// return bit - 1; +// } +// +// tlsf_decl int tlsf_fls(unsigned int word) +// { +// const int bit = word ? 32 - __clz(word) : 0; +// return bit - 1; +// } +// +// #elif defined (__ghs__) +// /* Green Hills support for PowerPC */ +// +// #include +// +// tlsf_decl int tlsf_ffs(unsigned int word) +// { +// const unsigned int reverse = word & (~word + 1); +// const int bit = 32 - __CLZ32(reverse); +// return bit - 1; +// } +// +// tlsf_decl int tlsf_fls(unsigned int word) +// { +// const int bit = word ? 32 - __CLZ32(word) : 0; +// return bit - 1; +// } +// +// #else /* Fall back to generic implementation. */ tlsf_decl int tlsf_fls_generic(unsigned int word) @@ -172,7 +172,7 @@ tlsf_decl int tlsf_fls(unsigned int word) return tlsf_fls_generic(word) - 1; } -#endif +// #endif /* Possibly 64-bit version of tlsf_fls. */ #if defined (TLSF_64BIT) From de5f81e9c46f3aa0859f9c9656f03998b11dfc4b Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:25:35 +1100 Subject: [PATCH 028/128] Migrated to TLSF --- libpsn00b/libc/tlsf.c | 214 +++++++++++++++++++++--------------------- 1 file changed, 107 insertions(+), 107 deletions(-) diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c index eeb64c3d..27cdacc0 100644 --- a/libpsn00b/libc/tlsf.c +++ b/libpsn00b/libc/tlsf.c @@ -40,111 +40,111 @@ #define TLSF_64BIT #endif -// /* -// ** gcc 3.4 and above have builtin support, specialized for architecture. -// ** Some compilers masquerade as gcc; patchlevel test filters them out. -// */ -// #if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ -// && defined (__GNUC_PATCHLEVEL__) -// -// #if defined (__SNC__) -// /* SNC for Playstation 3. */ -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// const unsigned int reverse = word & (~word + 1); -// const int bit = 32 - __builtin_clz(reverse); -// return bit - 1; -// } -// -// #else -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// return __builtin_ffs(word) - 1; -// } -// -// #endif -// -// tlsf_decl int tlsf_fls(unsigned int word) -// { -// const int bit = word ? 32 - __builtin_clz(word) : 0; -// return bit - 1; -// } -// -// #elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) -// /* Microsoft Visual C++ support on x86/X64 architectures. */ -// -// #include -// -// #pragma intrinsic(_BitScanReverse) -// #pragma intrinsic(_BitScanForward) -// -// tlsf_decl int tlsf_fls(unsigned int word) -// { -// unsigned long index; -// return _BitScanReverse(&index, word) ? index : -1; -// } -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// unsigned long index; -// return _BitScanForward(&index, word) ? index : -1; -// } -// -// #elif defined (_MSC_VER) && defined (_M_PPC) -// /* Microsoft Visual C++ support on PowerPC architectures. */ -// -// #include -// -// tlsf_decl int tlsf_fls(unsigned int word) -// { -// const int bit = 32 - _CountLeadingZeros(word); -// return bit - 1; -// } -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// const unsigned int reverse = word & (~word + 1); -// const int bit = 32 - _CountLeadingZeros(reverse); -// return bit - 1; -// } -// -// #elif defined (__ARMCC_VERSION) -// /* RealView Compilation Tools for ARM */ -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// const unsigned int reverse = word & (~word + 1); -// const int bit = 32 - __clz(reverse); -// return bit - 1; -// } -// -// tlsf_decl int tlsf_fls(unsigned int word) -// { -// const int bit = word ? 32 - __clz(word) : 0; -// return bit - 1; -// } -// -// #elif defined (__ghs__) -// /* Green Hills support for PowerPC */ -// -// #include -// -// tlsf_decl int tlsf_ffs(unsigned int word) -// { -// const unsigned int reverse = word & (~word + 1); -// const int bit = 32 - __CLZ32(reverse); -// return bit - 1; -// } -// -// tlsf_decl int tlsf_fls(unsigned int word) -// { -// const int bit = word ? 32 - __CLZ32(word) : 0; -// return bit - 1; -// } -// -// #else +/* +** gcc 3.4 and above have builtin support, specialized for architecture. +** Some compilers masquerade as gcc; patchlevel test filters them out. +*/ +#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ + && defined (__GNUC_PATCHLEVEL__) + +#if defined (__SNC__) +/* SNC for Playstation 3. */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __builtin_clz(reverse); + return bit - 1; +} + +#else + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + return __builtin_ffs(word) - 1; +} + +#endif + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __builtin_clz(word) : 0; + return bit - 1; +} + +#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) +/* Microsoft Visual C++ support on x86/X64 architectures. */ + +#include + +#pragma intrinsic(_BitScanReverse) +#pragma intrinsic(_BitScanForward) + +tlsf_decl int tlsf_fls(unsigned int word) +{ + unsigned long index; + return _BitScanReverse(&index, word) ? index : -1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + unsigned long index; + return _BitScanForward(&index, word) ? index : -1; +} + +#elif defined (_MSC_VER) && defined (_M_PPC) +/* Microsoft Visual C++ support on PowerPC architectures. */ + +#include + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = 32 - _CountLeadingZeros(word); + return bit - 1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - _CountLeadingZeros(reverse); + return bit - 1; +} + +#elif defined (__ARMCC_VERSION) +/* RealView Compilation Tools for ARM */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __clz(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __clz(word) : 0; + return bit - 1; +} + +#elif defined (__ghs__) +/* Green Hills support for PowerPC */ + +#include + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __CLZ32(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __CLZ32(word) : 0; + return bit - 1; +} + +#else /* Fall back to generic implementation. */ tlsf_decl int tlsf_fls_generic(unsigned int word) @@ -172,7 +172,7 @@ tlsf_decl int tlsf_fls(unsigned int word) return tlsf_fls_generic(word) - 1; } -// #endif +#endif /* Possibly 64-bit version of tlsf_fls. */ #if defined (TLSF_64BIT) @@ -219,7 +219,7 @@ enum tlsf_private ALIGN_SIZE_LOG2 = 3, #else /* All allocation sizes and addresses are aligned to 4 bytes. */ - ALIGN_SIZE_LOG2 = 2, + ALIGN_SIZE_LOG2 = 3, #endif ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2), From 65255f7348f63a828757e504f30336c0de006edf Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:29:22 +1100 Subject: [PATCH 029/128] Migrated to TLSF --- libpsn00b/libc/tlsf.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c index 27cdacc0..17f657b6 100644 --- a/libpsn00b/libc/tlsf.c +++ b/libpsn00b/libc/tlsf.c @@ -7,6 +7,8 @@ #include "tlsf.h" +#define TLSF_64BIT + #if defined(__cplusplus) #define tlsf_decl inline #else @@ -219,7 +221,7 @@ enum tlsf_private ALIGN_SIZE_LOG2 = 3, #else /* All allocation sizes and addresses are aligned to 4 bytes. */ - ALIGN_SIZE_LOG2 = 3, + ALIGN_SIZE_LOG2 = 2, #endif ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2), From ab7ba50186ec563864aa6782ffd5763e5f72211a Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:32:15 +1100 Subject: [PATCH 030/128] Migrated to TLSF --- libpsn00b/libc/tlsf.c | 2 -- 1 file changed, 2 deletions(-) diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c index 17f657b6..2c0169a4 100644 --- a/libpsn00b/libc/tlsf.c +++ b/libpsn00b/libc/tlsf.c @@ -7,8 +7,6 @@ #include "tlsf.h" -#define TLSF_64BIT - #if defined(__cplusplus) #define tlsf_decl inline #else From b6ef6b9bacf8c2ebbdbc6da419968c46b9077144 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:42:30 +1100 Subject: [PATCH 031/128] Migrated to TLSF --- libpsn00b/libc/malloc.c | 256 +++++++- libpsn00b/libc/malloc_old | 279 -------- libpsn00b/libc/tlsf.c | 1264 ------------------------------------- libpsn00b/libc/tlsf.h | 92 --- 4 files changed, 246 insertions(+), 1645 deletions(-) delete mode 100644 libpsn00b/libc/malloc_old delete mode 100644 libpsn00b/libc/tlsf.c delete mode 100644 libpsn00b/libc/tlsf.h diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 14dc3d5f..a884c2d4 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -1,43 +1,279 @@ -#include "tlsf.h" +/* + * PSn00bSDK default memory allocator + * (C) 2022 Nicolas Noble, spicyjpeg + * + * This code is based on psyqo's malloc implementation, available here: + * https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c + * + * Heap management and memory allocation are completely separate, with the + * latter being built on top of the former. This makes it possible to override + * only InitHeap() and sbrk() while still using the default allocator, or + * override malloc()/realloc()/free() while using the default heap manager. + * Custom allocators should call TrackHeapUsage() to let the heap manager know + * how much memory is allocated at a given time. + */ #include #include #include +#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) + +/* Private types */ + typedef struct _BlockHeader { - struct _BlockHeader *prev, *next; - void *ptr; - size_t size; + struct _BlockHeader *prev, *next; + void *ptr; + size_t size; } BlockHeader; -tlsf_t tlsf; +/* Internal globals */ + +static void *_heap_start, *_heap_end, *_heap_limit; +static size_t _heap_alloc, _heap_alloc_max; + +static void *_alloc_start; +static BlockHeader *_alloc_head, *_alloc_tail; + +/* Heap management API */ __attribute__((weak)) void InitHeap(void *addr, size_t size) { - tlsf = tlsf_create_with_pool(addr, size); + _heap_start = addr; + _heap_end = addr; + _heap_limit = (void *) ((uintptr_t) addr + size); + + _heap_alloc = 0; + _heap_alloc_max = 0; + + _alloc_start = addr; + _alloc_head = 0; + _alloc_tail = 0; +} + +__attribute__((weak)) void *sbrk(ptrdiff_t incr) { + void *old_end = _heap_end; + void *new_end = (void *) _align((uintptr_t) old_end + incr, 8); + + if (new_end > _heap_limit) + return 0; + + _heap_end = new_end; + return old_end; } __attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { + _heap_alloc += alloc_incr; + if (_heap_alloc > _heap_alloc_max) + _heap_alloc_max = _heap_alloc; } __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { + usage->total = _heap_limit - _heap_start; + usage->heap = _heap_end - _heap_start; + usage->stack = _heap_limit - _heap_end; + usage->alloc = _heap_alloc; + usage->alloc_max = _heap_alloc_max; } /* Memory allocator */ +static BlockHeader *_find_fit(BlockHeader *head, size_t size) { + BlockHeader *prev = head; + + for (; prev; prev = prev->next) { + if (prev->next) { + uintptr_t next_bot = (uintptr_t) prev->next; + next_bot -= (uintptr_t) prev->ptr + prev->size; + + if (next_bot >= size) + return prev; + } + } + + return prev; +} + __attribute__((weak)) void *malloc(size_t size) { - return tlsf_malloc(tlsf, size); + if (!size) + return 0; + + size_t _size = _align(size + sizeof(BlockHeader), 8); + + // Nothing's initialized yet? Let's just initialize the bottom of our heap, + // flag it as allocated. + if (!_alloc_head) { + //if (!_alloc_start) + //_alloc_start = sbrk(0); + + BlockHeader *new = (BlockHeader *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = 0; + + _alloc_head = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; + } + + // We *may* have the bottom of our heap that has shifted, because of a free. + // So let's check first if we have free space there, because I'm nervous + // about having an incomplete data structure. + if (((uintptr_t) _alloc_start + _size) < ((uintptr_t) _alloc_head)) { + BlockHeader *new = (BlockHeader *) _alloc_start; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = 0; + new->next = _alloc_head; + + _alloc_head->prev = new; + _alloc_head = new; + + TrackHeapUsage(size); + return ptr; + } + + // No luck at the beginning of the heap, let's walk the heap to find a fit. + BlockHeader *prev = _find_fit(_alloc_head, _size); + if (prev) { + BlockHeader *new = (BlockHeader *) ((uintptr_t) prev->ptr + prev->size); + + void *ptr = (void *)((uintptr_t) new + sizeof(BlockHeader)); + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = prev; + new->next = prev->next; + + (new->next)->prev = new; + prev->next = new; + + TrackHeapUsage(size); + return ptr; + } + + // Time to extend the size of the heap. + BlockHeader *new = (BlockHeader *) sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *) &new[1]; + new->ptr = ptr; + new->size = _size - sizeof(BlockHeader); + new->prev = _alloc_tail; + new->next = 0; + + _alloc_tail->next = new; + _alloc_tail = new; + + TrackHeapUsage(size); + return ptr; } __attribute__((weak)) void *calloc(size_t num, size_t size) { - return tlsf_malloc(tlsf, num * size); + return malloc(num * size); } __attribute__((weak)) void *realloc(void *ptr, size_t size) { - return tlsf_realloc(tlsf, ptr, size); + if (!size) { + free(ptr); + return 0; + } + if (!ptr) + return malloc(size); + + size_t _size = _align(size + sizeof(BlockHeader), 8); + BlockHeader *prev = (BlockHeader *) ((uintptr_t) ptr - sizeof(BlockHeader)); + + // New memory block shorter? + if (prev->size >= _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + + if (!prev->next) + sbrk((ptr - sbrk(0)) + _size); + + return ptr; + } + + // New memory block larger; is it the last one? + if (!prev->next) { + void *new = sbrk(_size - prev->size); + if (!new) + return 0; + + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // Do we have free memory after it? + if (((prev->next)->ptr - ptr) > _size) { + TrackHeapUsage(size - prev->size); + prev->size = _size - sizeof(BlockHeader); + return ptr; + } + + // No luck. + void *new = malloc(size); + if (!new) + return 0; + + __builtin_memcpy(new, ptr, prev->size); + free(ptr); + return new; } __attribute__((weak)) void free(void *ptr) { - tlsf_free(tlsf, ptr); + if (!ptr || !_alloc_head) + return; + + // First block; bumping head ahead. + if (ptr == _alloc_head->ptr) { + size_t size = _alloc_head->size; + size += (uintptr_t) _alloc_head->ptr - (uintptr_t) _alloc_head; + _alloc_head = _alloc_head->next; + + if (_alloc_head) { + _alloc_head->prev = 0; + } else { + _alloc_tail = 0; + sbrk(-size); + } + + TrackHeapUsage(-(_alloc_head->size)); + return; + } + + // Finding the proper block + BlockHeader *cur = _alloc_head; + + for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { + if (!cur->next) + return; + } + + if (cur->next) { + // In the middle, just unlink it + (cur->next)->prev = cur->prev; + } else { + // At the end, shrink heap + void *top = sbrk(0); + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; + _alloc_tail = cur->prev; + + sbrk(-size); + } + + TrackHeapUsage(-(cur->size)); + (cur->prev)->next = cur->next; } \ No newline at end of file diff --git a/libpsn00b/libc/malloc_old b/libpsn00b/libc/malloc_old deleted file mode 100644 index a884c2d4..00000000 --- a/libpsn00b/libc/malloc_old +++ /dev/null @@ -1,279 +0,0 @@ -/* - * PSn00bSDK default memory allocator - * (C) 2022 Nicolas Noble, spicyjpeg - * - * This code is based on psyqo's malloc implementation, available here: - * https://github.com/grumpycoders/pcsx-redux/blob/main/src/mips/psyqo/src/alloc.c - * - * Heap management and memory allocation are completely separate, with the - * latter being built on top of the former. This makes it possible to override - * only InitHeap() and sbrk() while still using the default allocator, or - * override malloc()/realloc()/free() while using the default heap manager. - * Custom allocators should call TrackHeapUsage() to let the heap manager know - * how much memory is allocated at a given time. - */ - -#include -#include -#include - -#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) - -/* Private types */ - -typedef struct _BlockHeader { - struct _BlockHeader *prev, *next; - void *ptr; - size_t size; -} BlockHeader; - -/* Internal globals */ - -static void *_heap_start, *_heap_end, *_heap_limit; -static size_t _heap_alloc, _heap_alloc_max; - -static void *_alloc_start; -static BlockHeader *_alloc_head, *_alloc_tail; - -/* Heap management API */ - -__attribute__((weak)) void InitHeap(void *addr, size_t size) { - _heap_start = addr; - _heap_end = addr; - _heap_limit = (void *) ((uintptr_t) addr + size); - - _heap_alloc = 0; - _heap_alloc_max = 0; - - _alloc_start = addr; - _alloc_head = 0; - _alloc_tail = 0; -} - -__attribute__((weak)) void *sbrk(ptrdiff_t incr) { - void *old_end = _heap_end; - void *new_end = (void *) _align((uintptr_t) old_end + incr, 8); - - if (new_end > _heap_limit) - return 0; - - _heap_end = new_end; - return old_end; -} - -__attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { - _heap_alloc += alloc_incr; - - if (_heap_alloc > _heap_alloc_max) - _heap_alloc_max = _heap_alloc; -} - -__attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { - usage->total = _heap_limit - _heap_start; - usage->heap = _heap_end - _heap_start; - usage->stack = _heap_limit - _heap_end; - - usage->alloc = _heap_alloc; - usage->alloc_max = _heap_alloc_max; -} - -/* Memory allocator */ - -static BlockHeader *_find_fit(BlockHeader *head, size_t size) { - BlockHeader *prev = head; - - for (; prev; prev = prev->next) { - if (prev->next) { - uintptr_t next_bot = (uintptr_t) prev->next; - next_bot -= (uintptr_t) prev->ptr + prev->size; - - if (next_bot >= size) - return prev; - } - } - - return prev; -} - -__attribute__((weak)) void *malloc(size_t size) { - if (!size) - return 0; - - size_t _size = _align(size + sizeof(BlockHeader), 8); - - // Nothing's initialized yet? Let's just initialize the bottom of our heap, - // flag it as allocated. - if (!_alloc_head) { - //if (!_alloc_start) - //_alloc_start = sbrk(0); - - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = 0; - - _alloc_head = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; - } - - // We *may* have the bottom of our heap that has shifted, because of a free. - // So let's check first if we have free space there, because I'm nervous - // about having an incomplete data structure. - if (((uintptr_t) _alloc_start + _size) < ((uintptr_t) _alloc_head)) { - BlockHeader *new = (BlockHeader *) _alloc_start; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = _alloc_head; - - _alloc_head->prev = new; - _alloc_head = new; - - TrackHeapUsage(size); - return ptr; - } - - // No luck at the beginning of the heap, let's walk the heap to find a fit. - BlockHeader *prev = _find_fit(_alloc_head, _size); - if (prev) { - BlockHeader *new = (BlockHeader *) ((uintptr_t) prev->ptr + prev->size); - - void *ptr = (void *)((uintptr_t) new + sizeof(BlockHeader)); - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = prev; - new->next = prev->next; - - (new->next)->prev = new; - prev->next = new; - - TrackHeapUsage(size); - return ptr; - } - - // Time to extend the size of the heap. - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = _alloc_tail; - new->next = 0; - - _alloc_tail->next = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; -} - -__attribute__((weak)) void *calloc(size_t num, size_t size) { - return malloc(num * size); -} - -__attribute__((weak)) void *realloc(void *ptr, size_t size) { - if (!size) { - free(ptr); - return 0; - } - if (!ptr) - return malloc(size); - - size_t _size = _align(size + sizeof(BlockHeader), 8); - BlockHeader *prev = (BlockHeader *) ((uintptr_t) ptr - sizeof(BlockHeader)); - - // New memory block shorter? - if (prev->size >= _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - - if (!prev->next) - sbrk((ptr - sbrk(0)) + _size); - - return ptr; - } - - // New memory block larger; is it the last one? - if (!prev->next) { - void *new = sbrk(_size - prev->size); - if (!new) - return 0; - - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // Do we have free memory after it? - if (((prev->next)->ptr - ptr) > _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // No luck. - void *new = malloc(size); - if (!new) - return 0; - - __builtin_memcpy(new, ptr, prev->size); - free(ptr); - return new; -} - -__attribute__((weak)) void free(void *ptr) { - if (!ptr || !_alloc_head) - return; - - // First block; bumping head ahead. - if (ptr == _alloc_head->ptr) { - size_t size = _alloc_head->size; - size += (uintptr_t) _alloc_head->ptr - (uintptr_t) _alloc_head; - _alloc_head = _alloc_head->next; - - if (_alloc_head) { - _alloc_head->prev = 0; - } else { - _alloc_tail = 0; - sbrk(-size); - } - - TrackHeapUsage(-(_alloc_head->size)); - return; - } - - // Finding the proper block - BlockHeader *cur = _alloc_head; - - for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { - if (!cur->next) - return; - } - - if (cur->next) { - // In the middle, just unlink it - (cur->next)->prev = cur->prev; - } else { - // At the end, shrink heap - void *top = sbrk(0); - size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; - _alloc_tail = cur->prev; - - sbrk(-size); - } - - TrackHeapUsage(-(cur->size)); - (cur->prev)->next = cur->next; -} \ No newline at end of file diff --git a/libpsn00b/libc/tlsf.c b/libpsn00b/libc/tlsf.c deleted file mode 100644 index 2c0169a4..00000000 --- a/libpsn00b/libc/tlsf.c +++ /dev/null @@ -1,1264 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "tlsf.h" - -#if defined(__cplusplus) -#define tlsf_decl inline -#else -#define tlsf_decl static -#endif - -/* -** Architecture-specific bit manipulation routines. -** -** TLSF achieves O(1) cost for malloc and free operations by limiting -** the search for a free block to a free list of guaranteed size -** adequate to fulfill the request, combined with efficient free list -** queries using bitmasks and architecture-specific bit-manipulation -** routines. -** -** Most modern processors provide instructions to count leading zeroes -** in a word, find the lowest and highest set bit, etc. These -** specific implementations will be used when available, falling back -** to a reasonably efficient generic implementation. -** -** NOTE: TLSF spec relies on ffs/fls returning value 0..31. -** ffs/fls return 1-32 by default, returning 0 for error. -*/ - -/* -** Detect whether or not we are building for a 32- or 64-bit (LP/LLP) -** architecture. There is no reliable portable method at compile-time. -*/ -#if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) \ - || defined (_WIN64) || defined (__LP64__) || defined (__LLP64__) -#define TLSF_64BIT -#endif - -/* -** gcc 3.4 and above have builtin support, specialized for architecture. -** Some compilers masquerade as gcc; patchlevel test filters them out. -*/ -#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ - && defined (__GNUC_PATCHLEVEL__) - -#if defined (__SNC__) -/* SNC for Playstation 3. */ - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __builtin_clz(reverse); - return bit - 1; -} - -#else - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - return __builtin_ffs(word) - 1; -} - -#endif - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __builtin_clz(word) : 0; - return bit - 1; -} - -#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) -/* Microsoft Visual C++ support on x86/X64 architectures. */ - -#include - -#pragma intrinsic(_BitScanReverse) -#pragma intrinsic(_BitScanForward) - -tlsf_decl int tlsf_fls(unsigned int word) -{ - unsigned long index; - return _BitScanReverse(&index, word) ? index : -1; -} - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - unsigned long index; - return _BitScanForward(&index, word) ? index : -1; -} - -#elif defined (_MSC_VER) && defined (_M_PPC) -/* Microsoft Visual C++ support on PowerPC architectures. */ - -#include - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = 32 - _CountLeadingZeros(word); - return bit - 1; -} - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - _CountLeadingZeros(reverse); - return bit - 1; -} - -#elif defined (__ARMCC_VERSION) -/* RealView Compilation Tools for ARM */ - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __clz(reverse); - return bit - 1; -} - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __clz(word) : 0; - return bit - 1; -} - -#elif defined (__ghs__) -/* Green Hills support for PowerPC */ - -#include - -tlsf_decl int tlsf_ffs(unsigned int word) -{ - const unsigned int reverse = word & (~word + 1); - const int bit = 32 - __CLZ32(reverse); - return bit - 1; -} - -tlsf_decl int tlsf_fls(unsigned int word) -{ - const int bit = word ? 32 - __CLZ32(word) : 0; - return bit - 1; -} - -#else -/* Fall back to generic implementation. */ - -tlsf_decl int tlsf_fls_generic(unsigned int word) -{ - int bit = 32; - - if (!word) bit -= 1; - if (!(word & 0xffff0000)) { word <<= 16; bit -= 16; } - if (!(word & 0xff000000)) { word <<= 8; bit -= 8; } - if (!(word & 0xf0000000)) { word <<= 4; bit -= 4; } - if (!(word & 0xc0000000)) { word <<= 2; bit -= 2; } - if (!(word & 0x80000000)) { word <<= 1; bit -= 1; } - - return bit; -} - -/* Implement ffs in terms of fls. */ -tlsf_decl int tlsf_ffs(unsigned int word) -{ - return tlsf_fls_generic(word & (~word + 1)) - 1; -} - -tlsf_decl int tlsf_fls(unsigned int word) -{ - return tlsf_fls_generic(word) - 1; -} - -#endif - -/* Possibly 64-bit version of tlsf_fls. */ -#if defined (TLSF_64BIT) -tlsf_decl int tlsf_fls_sizet(size_t size) -{ - int high = (int)(size >> 32); - int bits = 0; - if (high) - { - bits = 32 + tlsf_fls(high); - } - else - { - bits = tlsf_fls((int)size & 0xffffffff); - - } - return bits; -} -#else -#define tlsf_fls_sizet tlsf_fls -#endif - -#undef tlsf_decl - -/* -** Constants. -*/ - -/* Public constants: may be modified. */ -enum tlsf_public -{ - /* log2 of number of linear subdivisions of block sizes. Larger - ** values require more memory in the control structure. Values of - ** 4 or 5 are typical. - */ - SL_INDEX_COUNT_LOG2 = 5, -}; - -/* Private constants: do not modify. */ -enum tlsf_private -{ -#if defined (TLSF_64BIT) - /* All allocation sizes and addresses are aligned to 8 bytes. */ - ALIGN_SIZE_LOG2 = 3, -#else - /* All allocation sizes and addresses are aligned to 4 bytes. */ - ALIGN_SIZE_LOG2 = 2, -#endif - ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2), - - /* - ** We support allocations of sizes up to (1 << FL_INDEX_MAX) bits. - ** However, because we linearly subdivide the second-level lists, and - ** our minimum size granularity is 4 bytes, it doesn't make sense to - ** create first-level lists for sizes smaller than SL_INDEX_COUNT * 4, - ** or (1 << (SL_INDEX_COUNT_LOG2 + 2)) bytes, as there we will be - ** trying to split size ranges into more slots than we have available. - ** Instead, we calculate the minimum threshold size, and place all - ** blocks below that size into the 0th first-level list. - */ - -#if defined (TLSF_64BIT) - /* - ** TODO: We can increase this to support larger sizes, at the expense - ** of more overhead in the TLSF structure. - */ - FL_INDEX_MAX = 32, -#else - FL_INDEX_MAX = 30, -#endif - SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2), - FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2), - FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1), - - SMALL_BLOCK_SIZE = (1 << FL_INDEX_SHIFT), -}; - -/* -** Cast and min/max macros. -*/ - -#define tlsf_cast(t, exp) ((t) (exp)) -#define tlsf_min(a, b) ((a) < (b) ? (a) : (b)) -#define tlsf_max(a, b) ((a) > (b) ? (a) : (b)) - -/* -** Set assert macro, if it has not been provided by the user. -*/ -#if !defined (tlsf_assert) -#define tlsf_assert assert -#endif - -/* -** Static assertion mechanism. -*/ - -#define _tlsf_glue2(x, y) x ## y -#define _tlsf_glue(x, y) _tlsf_glue2(x, y) -#define tlsf_static_assert(exp) \ - typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1] - -/* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */ -tlsf_static_assert(sizeof(int) * CHAR_BIT == 32); -tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32); -tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64); - -/* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */ -tlsf_static_assert(sizeof(unsigned int) * CHAR_BIT >= SL_INDEX_COUNT); - -/* Ensure we've properly tuned our sizes. */ -tlsf_static_assert(ALIGN_SIZE == SMALL_BLOCK_SIZE / SL_INDEX_COUNT); - -/* -** Data structures and associated constants. -*/ - -/* -** Block header structure. -** -** There are several implementation subtleties involved: -** - The prev_phys_block field is only valid if the previous block is free. -** - The prev_phys_block field is actually stored at the end of the -** previous block. It appears at the beginning of this structure only to -** simplify the implementation. -** - The next_free / prev_free fields are only valid if the block is free. -*/ -typedef struct block_header_t -{ - /* Points to the previous physical block. */ - struct block_header_t* prev_phys_block; - - /* The size of this block, excluding the block header. */ - size_t size; - - /* Next and previous free blocks. */ - struct block_header_t* next_free; - struct block_header_t* prev_free; -} block_header_t; - -/* -** Since block sizes are always at least a multiple of 4, the two least -** significant bits of the size field are used to store the block status: -** - bit 0: whether block is busy or free -** - bit 1: whether previous block is busy or free -*/ -static const size_t block_header_free_bit = 1 << 0; -static const size_t block_header_prev_free_bit = 1 << 1; - -/* -** The size of the block header exposed to used blocks is the size field. -** The prev_phys_block field is stored *inside* the previous free block. -*/ -static const size_t block_header_overhead = sizeof(size_t); - -/* User data starts directly after the size field in a used block. */ -static const size_t block_start_offset = - offsetof(block_header_t, size) + sizeof(size_t); - -/* -** A free block must be large enough to store its header minus the size of -** the prev_phys_block field, and no larger than the number of addressable -** bits for FL_INDEX. -*/ -static const size_t block_size_min = - sizeof(block_header_t) - sizeof(block_header_t*); -static const size_t block_size_max = tlsf_cast(size_t, 1) << FL_INDEX_MAX; - - -/* The TLSF control structure. */ -typedef struct control_t -{ - /* Empty lists point at this block to indicate they are free. */ - block_header_t block_null; - - /* Bitmaps for free lists. */ - unsigned int fl_bitmap; - unsigned int sl_bitmap[FL_INDEX_COUNT]; - - /* Head of free lists. */ - block_header_t* blocks[FL_INDEX_COUNT][SL_INDEX_COUNT]; -} control_t; - -/* A type used for casting when doing pointer arithmetic. */ -typedef ptrdiff_t tlsfptr_t; - -/* -** block_header_t member functions. -*/ - -static size_t block_size(const block_header_t* block) -{ - return block->size & ~(block_header_free_bit | block_header_prev_free_bit); -} - -static void block_set_size(block_header_t* block, size_t size) -{ - const size_t oldsize = block->size; - block->size = size | (oldsize & (block_header_free_bit | block_header_prev_free_bit)); -} - -static int block_is_last(const block_header_t* block) -{ - return block_size(block) == 0; -} - -static int block_is_free(const block_header_t* block) -{ - return tlsf_cast(int, block->size & block_header_free_bit); -} - -static void block_set_free(block_header_t* block) -{ - block->size |= block_header_free_bit; -} - -static void block_set_used(block_header_t* block) -{ - block->size &= ~block_header_free_bit; -} - -static int block_is_prev_free(const block_header_t* block) -{ - return tlsf_cast(int, block->size & block_header_prev_free_bit); -} - -static void block_set_prev_free(block_header_t* block) -{ - block->size |= block_header_prev_free_bit; -} - -static void block_set_prev_used(block_header_t* block) -{ - block->size &= ~block_header_prev_free_bit; -} - -static block_header_t* block_from_ptr(const void* ptr) -{ - return tlsf_cast(block_header_t*, - tlsf_cast(unsigned char*, ptr) - block_start_offset); -} - -static void* block_to_ptr(const block_header_t* block) -{ - return tlsf_cast(void*, - tlsf_cast(unsigned char*, block) + block_start_offset); -} - -/* Return location of next block after block of given size. */ -static block_header_t* offset_to_block(const void* ptr, size_t size) -{ - return tlsf_cast(block_header_t*, tlsf_cast(tlsfptr_t, ptr) + size); -} - -/* Return location of previous block. */ -static block_header_t* block_prev(const block_header_t* block) -{ - tlsf_assert(block_is_prev_free(block) && "previous block must be free"); - return block->prev_phys_block; -} - -/* Return location of next existing block. */ -static block_header_t* block_next(const block_header_t* block) -{ - block_header_t* next = offset_to_block(block_to_ptr(block), - block_size(block) - block_header_overhead); - tlsf_assert(!block_is_last(block)); - return next; -} - -/* Link a new block with its physical neighbor, return the neighbor. */ -static block_header_t* block_link_next(block_header_t* block) -{ - block_header_t* next = block_next(block); - next->prev_phys_block = block; - return next; -} - -static void block_mark_as_free(block_header_t* block) -{ - /* Link the block to the next block, first. */ - block_header_t* next = block_link_next(block); - block_set_prev_free(next); - block_set_free(block); -} - -static void block_mark_as_used(block_header_t* block) -{ - block_header_t* next = block_next(block); - block_set_prev_used(next); - block_set_used(block); -} - -static size_t align_up(size_t x, size_t align) -{ - tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); - return (x + (align - 1)) & ~(align - 1); -} - -static size_t align_down(size_t x, size_t align) -{ - tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); - return x - (x & (align - 1)); -} - -static void* align_ptr(const void* ptr, size_t align) -{ - const tlsfptr_t aligned = - (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1); - tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); - return tlsf_cast(void*, aligned); -} - -/* -** Adjust an allocation size to be aligned to word size, and no smaller -** than internal minimum. -*/ -static size_t adjust_request_size(size_t size, size_t align) -{ - size_t adjust = 0; - if (size) - { - const size_t aligned = align_up(size, align); - - /* aligned sized must not exceed block_size_max or we'll go out of bounds on sl_bitmap */ - if (aligned < block_size_max) - { - adjust = tlsf_max(aligned, block_size_min); - } - } - return adjust; -} - -/* -** TLSF utility functions. In most cases, these are direct translations of -** the documentation found in the white paper. -*/ - -static void mapping_insert(size_t size, int* fli, int* sli) -{ - int fl, sl; - if (size < SMALL_BLOCK_SIZE) - { - /* Store small blocks in first list. */ - fl = 0; - sl = tlsf_cast(int, size) / (SMALL_BLOCK_SIZE / SL_INDEX_COUNT); - } - else - { - fl = tlsf_fls_sizet(size); - sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2); - fl -= (FL_INDEX_SHIFT - 1); - } - *fli = fl; - *sli = sl; -} - -/* This version rounds up to the next block size (for allocations) */ -static void mapping_search(size_t size, int* fli, int* sli) -{ - if (size >= SMALL_BLOCK_SIZE) - { - const size_t round = (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1; - size += round; - } - mapping_insert(size, fli, sli); -} - -static block_header_t* search_suitable_block(control_t* control, int* fli, int* sli) -{ - int fl = *fli; - int sl = *sli; - - /* - ** First, search for a block in the list associated with the given - ** fl/sl index. - */ - unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl); - if (!sl_map) - { - /* No block exists. Search in the next largest first-level list. */ - const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1)); - if (!fl_map) - { - /* No free blocks available, memory has been exhausted. */ - return 0; - } - - fl = tlsf_ffs(fl_map); - *fli = fl; - sl_map = control->sl_bitmap[fl]; - } - tlsf_assert(sl_map && "internal error - second level bitmap is null"); - sl = tlsf_ffs(sl_map); - *sli = sl; - - /* Return the first block in the free list. */ - return control->blocks[fl][sl]; -} - -/* Remove a free block from the free list.*/ -static void remove_free_block(control_t* control, block_header_t* block, int fl, int sl) -{ - block_header_t* prev = block->prev_free; - block_header_t* next = block->next_free; - tlsf_assert(prev && "prev_free field can not be null"); - tlsf_assert(next && "next_free field can not be null"); - next->prev_free = prev; - prev->next_free = next; - - /* If this block is the head of the free list, set new head. */ - if (control->blocks[fl][sl] == block) - { - control->blocks[fl][sl] = next; - - /* If the new head is null, clear the bitmap. */ - if (next == &control->block_null) - { - control->sl_bitmap[fl] &= ~(1U << sl); - - /* If the second bitmap is now empty, clear the fl bitmap. */ - if (!control->sl_bitmap[fl]) - { - control->fl_bitmap &= ~(1U << fl); - } - } - } -} - -/* Insert a free block into the free block list. */ -static void insert_free_block(control_t* control, block_header_t* block, int fl, int sl) -{ - block_header_t* current = control->blocks[fl][sl]; - tlsf_assert(current && "free list cannot have a null entry"); - tlsf_assert(block && "cannot insert a null entry into the free list"); - block->next_free = current; - block->prev_free = &control->block_null; - current->prev_free = block; - - tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE) - && "block not aligned properly"); - /* - ** Insert the new block at the head of the list, and mark the first- - ** and second-level bitmaps appropriately. - */ - control->blocks[fl][sl] = block; - control->fl_bitmap |= (1U << fl); - control->sl_bitmap[fl] |= (1U << sl); -} - -/* Remove a given block from the free list. */ -static void block_remove(control_t* control, block_header_t* block) -{ - int fl, sl; - mapping_insert(block_size(block), &fl, &sl); - remove_free_block(control, block, fl, sl); -} - -/* Insert a given block into the free list. */ -static void block_insert(control_t* control, block_header_t* block) -{ - int fl, sl; - mapping_insert(block_size(block), &fl, &sl); - insert_free_block(control, block, fl, sl); -} - -static int block_can_split(block_header_t* block, size_t size) -{ - return block_size(block) >= sizeof(block_header_t) + size; -} - -/* Split a block into two, the second of which is free. */ -static block_header_t* block_split(block_header_t* block, size_t size) -{ - /* Calculate the amount of space left in the remaining block. */ - block_header_t* remaining = - offset_to_block(block_to_ptr(block), size - block_header_overhead); - - const size_t remain_size = block_size(block) - (size + block_header_overhead); - - tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE) - && "remaining block not aligned properly"); - - tlsf_assert(block_size(block) == remain_size + size + block_header_overhead); - block_set_size(remaining, remain_size); - tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size"); - - block_set_size(block, size); - block_mark_as_free(remaining); - - return remaining; -} - -/* Absorb a free block's storage into an adjacent previous free block. */ -static block_header_t* block_absorb(block_header_t* prev, block_header_t* block) -{ - tlsf_assert(!block_is_last(prev) && "previous block can't be last"); - /* Note: Leaves flags untouched. */ - prev->size += block_size(block) + block_header_overhead; - block_link_next(prev); - return prev; -} - -/* Merge a just-freed block with an adjacent previous free block. */ -static block_header_t* block_merge_prev(control_t* control, block_header_t* block) -{ - if (block_is_prev_free(block)) - { - block_header_t* prev = block_prev(block); - tlsf_assert(prev && "prev physical block can't be null"); - tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such"); - block_remove(control, prev); - block = block_absorb(prev, block); - } - - return block; -} - -/* Merge a just-freed block with an adjacent free block. */ -static block_header_t* block_merge_next(control_t* control, block_header_t* block) -{ - block_header_t* next = block_next(block); - tlsf_assert(next && "next physical block can't be null"); - - if (block_is_free(next)) - { - tlsf_assert(!block_is_last(block) && "previous block can't be last"); - block_remove(control, next); - block = block_absorb(block, next); - } - - return block; -} - -/* Trim any trailing block space off the end of a block, return to pool. */ -static void block_trim_free(control_t* control, block_header_t* block, size_t size) -{ - tlsf_assert(block_is_free(block) && "block must be free"); - if (block_can_split(block, size)) - { - block_header_t* remaining_block = block_split(block, size); - block_link_next(block); - block_set_prev_free(remaining_block); - block_insert(control, remaining_block); - } -} - -/* Trim any trailing block space off the end of a used block, return to pool. */ -static void block_trim_used(control_t* control, block_header_t* block, size_t size) -{ - tlsf_assert(!block_is_free(block) && "block must be used"); - if (block_can_split(block, size)) - { - /* If the next block is free, we must coalesce. */ - block_header_t* remaining_block = block_split(block, size); - block_set_prev_used(remaining_block); - - remaining_block = block_merge_next(control, remaining_block); - block_insert(control, remaining_block); - } -} - -static block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size) -{ - block_header_t* remaining_block = block; - if (block_can_split(block, size)) - { - /* We want the 2nd block. */ - remaining_block = block_split(block, size - block_header_overhead); - block_set_prev_free(remaining_block); - - block_link_next(block); - block_insert(control, block); - } - - return remaining_block; -} - -static block_header_t* block_locate_free(control_t* control, size_t size) -{ - int fl = 0, sl = 0; - block_header_t* block = 0; - - if (size) - { - mapping_search(size, &fl, &sl); - - /* - ** mapping_search can futz with the size, so for excessively large sizes it can sometimes wind up - ** with indices that are off the end of the block array. - ** So, we protect against that here, since this is the only callsite of mapping_search. - ** Note that we don't need to check sl, since it comes from a modulo operation that guarantees it's always in range. - */ - if (fl < FL_INDEX_COUNT) - { - block = search_suitable_block(control, &fl, &sl); - } - } - - if (block) - { - tlsf_assert(block_size(block) >= size); - remove_free_block(control, block, fl, sl); - } - - return block; -} - -static void* block_prepare_used(control_t* control, block_header_t* block, size_t size) -{ - void* p = 0; - if (block) - { - tlsf_assert(size && "size must be non-zero"); - block_trim_free(control, block, size); - block_mark_as_used(block); - p = block_to_ptr(block); - } - return p; -} - -/* Clear structure and point all empty lists at the null block. */ -static void control_construct(control_t* control) -{ - int i, j; - - control->block_null.next_free = &control->block_null; - control->block_null.prev_free = &control->block_null; - - control->fl_bitmap = 0; - for (i = 0; i < FL_INDEX_COUNT; ++i) - { - control->sl_bitmap[i] = 0; - for (j = 0; j < SL_INDEX_COUNT; ++j) - { - control->blocks[i][j] = &control->block_null; - } - } -} - -/* -** Debugging utilities. -*/ - -typedef struct integrity_t -{ - int prev_status; - int status; -} integrity_t; - -#define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } } - -static void integrity_walker(void* ptr, size_t size, int used, void* user) -{ - block_header_t* block = block_from_ptr(ptr); - integrity_t* integ = tlsf_cast(integrity_t*, user); - const int this_prev_status = block_is_prev_free(block) ? 1 : 0; - const int this_status = block_is_free(block) ? 1 : 0; - const size_t this_block_size = block_size(block); - - int status = 0; - (void)used; - tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect"); - tlsf_insist(size == this_block_size && "block size incorrect"); - - integ->prev_status = this_status; - integ->status += status; -} - -int tlsf_check(tlsf_t tlsf) -{ - int i, j; - - control_t* control = tlsf_cast(control_t*, tlsf); - int status = 0; - - /* Check that the free lists and bitmaps are accurate. */ - for (i = 0; i < FL_INDEX_COUNT; ++i) - { - for (j = 0; j < SL_INDEX_COUNT; ++j) - { - const int fl_map = control->fl_bitmap & (1U << i); - const int sl_list = control->sl_bitmap[i]; - const int sl_map = sl_list & (1U << j); - const block_header_t* block = control->blocks[i][j]; - - /* Check that first- and second-level lists agree. */ - if (!fl_map) - { - tlsf_insist(!sl_map && "second-level map must be null"); - } - - if (!sl_map) - { - tlsf_insist(block == &control->block_null && "block list must be null"); - continue; - } - - /* Check that there is at least one free block. */ - tlsf_insist(sl_list && "no free blocks in second-level map"); - tlsf_insist(block != &control->block_null && "block should not be null"); - - while (block != &control->block_null) - { - int fli, sli; - tlsf_insist(block_is_free(block) && "block should be free"); - tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced"); - tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced"); - tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free"); - tlsf_insist(block_size(block) >= block_size_min && "block not minimum size"); - - mapping_insert(block_size(block), &fli, &sli); - tlsf_insist(fli == i && sli == j && "block size indexed in wrong list"); - block = block->next_free; - } - } - } - - return status; -} - -#undef tlsf_insist - -static void default_walker(void* ptr, size_t size, int used, void* user) -{ - (void)user; - printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr)); -} - -void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user) -{ - tlsf_walker pool_walker = walker ? walker : default_walker; - block_header_t* block = - offset_to_block(pool, -(int)block_header_overhead); - - while (block && !block_is_last(block)) - { - pool_walker( - block_to_ptr(block), - block_size(block), - !block_is_free(block), - user); - block = block_next(block); - } -} - -size_t tlsf_block_size(void* ptr) -{ - size_t size = 0; - if (ptr) - { - const block_header_t* block = block_from_ptr(ptr); - size = block_size(block); - } - return size; -} - -int tlsf_check_pool(pool_t pool) -{ - /* Check that the blocks are physically correct. */ - integrity_t integ = { 0, 0 }; - tlsf_walk_pool(pool, integrity_walker, &integ); - - return integ.status; -} - -/* -** Size of the TLSF structures in a given memory block passed to -** tlsf_create, equal to the size of a control_t -*/ -size_t tlsf_size(void) -{ - return sizeof(control_t); -} - -size_t tlsf_align_size(void) -{ - return ALIGN_SIZE; -} - -size_t tlsf_block_size_min(void) -{ - return block_size_min; -} - -size_t tlsf_block_size_max(void) -{ - return block_size_max; -} - -/* -** Overhead of the TLSF structures in a given memory block passed to -** tlsf_add_pool, equal to the overhead of a free block and the -** sentinel block. -*/ -size_t tlsf_pool_overhead(void) -{ - return 2 * block_header_overhead; -} - -size_t tlsf_alloc_overhead(void) -{ - return block_header_overhead; -} - -pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) -{ - block_header_t* block; - block_header_t* next; - - const size_t pool_overhead = tlsf_pool_overhead(); - const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE); - - if (((ptrdiff_t)mem % ALIGN_SIZE) != 0) - { - printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n", - (unsigned int)ALIGN_SIZE); - return 0; - } - - if (pool_bytes < block_size_min || pool_bytes > block_size_max) - { -#if defined (TLSF_64BIT) - printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n", - (unsigned int)(pool_overhead + block_size_min), - (unsigned int)((pool_overhead + block_size_max) / 256)); -#else - printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n", - (unsigned int)(pool_overhead + block_size_min), - (unsigned int)(pool_overhead + block_size_max)); -#endif - return 0; - } - - /* - ** Create the main free block. Offset the start of the block slightly - ** so that the prev_phys_block field falls outside of the pool - - ** it will never be used. - */ - block = offset_to_block(mem, -(tlsfptr_t)block_header_overhead); - block_set_size(block, pool_bytes); - block_set_free(block); - block_set_prev_used(block); - block_insert(tlsf_cast(control_t*, tlsf), block); - - /* Split the block to create a zero-size sentinel block. */ - next = block_link_next(block); - block_set_size(next, 0); - block_set_used(next); - block_set_prev_free(next); - - return mem; -} - -void tlsf_remove_pool(tlsf_t tlsf, pool_t pool) -{ - control_t* control = tlsf_cast(control_t*, tlsf); - block_header_t* block = offset_to_block(pool, -(int)block_header_overhead); - - int fl = 0, sl = 0; - - tlsf_assert(block_is_free(block) && "block should be free"); - tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free"); - tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero"); - - mapping_insert(block_size(block), &fl, &sl); - remove_free_block(control, block, fl, sl); -} - -/* -** TLSF main interface. -*/ - -#if _DEBUG -int test_ffs_fls() -{ - /* Verify ffs/fls work properly. */ - int rv = 0; - rv += (tlsf_ffs(0) == -1) ? 0 : 0x1; - rv += (tlsf_fls(0) == -1) ? 0 : 0x2; - rv += (tlsf_ffs(1) == 0) ? 0 : 0x4; - rv += (tlsf_fls(1) == 0) ? 0 : 0x8; - rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10; - rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20; - rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40; - rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80; - -#if defined (TLSF_64BIT) - rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100; - rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200; - rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400; -#endif - - if (rv) - { - printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv); - } - return rv; -} -#endif - -tlsf_t tlsf_create(void* mem) -{ -#if _DEBUG - if (test_ffs_fls()) - { - return 0; - } -#endif - - if (((tlsfptr_t)mem % ALIGN_SIZE) != 0) - { - printf("tlsf_create: Memory must be aligned to %u bytes.\n", - (unsigned int)ALIGN_SIZE); - return 0; - } - - control_construct(tlsf_cast(control_t*, mem)); - - return tlsf_cast(tlsf_t, mem); -} - -tlsf_t tlsf_create_with_pool(void* mem, size_t bytes) -{ - tlsf_t tlsf = tlsf_create(mem); - tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size()); - return tlsf; -} - -void tlsf_destroy(tlsf_t tlsf) -{ - /* Nothing to do. */ - (void)tlsf; -} - -pool_t tlsf_get_pool(tlsf_t tlsf) -{ - return tlsf_cast(pool_t, (char*)tlsf + tlsf_size()); -} - -void* tlsf_malloc(tlsf_t tlsf, size_t size) -{ - control_t* control = tlsf_cast(control_t*, tlsf); - const size_t adjust = adjust_request_size(size, ALIGN_SIZE); - block_header_t* block = block_locate_free(control, adjust); - return block_prepare_used(control, block, adjust); -} - -void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size) -{ - control_t* control = tlsf_cast(control_t*, tlsf); - const size_t adjust = adjust_request_size(size, ALIGN_SIZE); - - /* - ** We must allocate an additional minimum block size bytes so that if - ** our free block will leave an alignment gap which is smaller, we can - ** trim a leading free block and release it back to the pool. We must - ** do this because the previous physical block is in use, therefore - ** the prev_phys_block field is not valid, and we can't simply adjust - ** the size of that block. - */ - const size_t gap_minimum = sizeof(block_header_t); - const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align); - - /* - ** If alignment is less than or equals base alignment, we're done. - ** If we requested 0 bytes, return null, as tlsf_malloc(0) does. - */ - const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust; - - block_header_t* block = block_locate_free(control, aligned_size); - - /* This can't be a static assert. */ - tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead); - - if (block) - { - void* ptr = block_to_ptr(block); - void* aligned = align_ptr(ptr, align); - size_t gap = tlsf_cast(size_t, - tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); - - /* If gap size is too small, offset to next aligned boundary. */ - if (gap && gap < gap_minimum) - { - const size_t gap_remain = gap_minimum - gap; - const size_t offset = tlsf_max(gap_remain, align); - const void* next_aligned = tlsf_cast(void*, - tlsf_cast(tlsfptr_t, aligned) + offset); - - aligned = align_ptr(next_aligned, align); - gap = tlsf_cast(size_t, - tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); - } - - if (gap) - { - tlsf_assert(gap >= gap_minimum && "gap size too small"); - block = block_trim_free_leading(control, block, gap); - } - } - - return block_prepare_used(control, block, adjust); -} - -void tlsf_free(tlsf_t tlsf, void* ptr) -{ - /* Don't attempt to free a NULL pointer. */ - if (ptr) - { - control_t* control = tlsf_cast(control_t*, tlsf); - block_header_t* block = block_from_ptr(ptr); - tlsf_assert(!block_is_free(block) && "block already marked as free"); - block_mark_as_free(block); - block = block_merge_prev(control, block); - block = block_merge_next(control, block); - block_insert(control, block); - } -} - -/* -** The TLSF block information provides us with enough information to -** provide a reasonably intelligent implementation of realloc, growing or -** shrinking the currently allocated block as required. -** -** This routine handles the somewhat esoteric edge cases of realloc: -** - a non-zero size with a null pointer will behave like malloc -** - a zero size with a non-null pointer will behave like free -** - a request that cannot be satisfied will leave the original buffer -** untouched -** - an extended buffer size will leave the newly-allocated area with -** contents undefined -*/ -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) -{ - control_t* control = tlsf_cast(control_t*, tlsf); - void* p = 0; - - /* Zero-size requests are treated as free. */ - if (ptr && size == 0) - { - tlsf_free(tlsf, ptr); - } - /* Requests with NULL pointers are treated as malloc. */ - else if (!ptr) - { - p = tlsf_malloc(tlsf, size); - } - else - { - block_header_t* block = block_from_ptr(ptr); - block_header_t* next = block_next(block); - - const size_t cursize = block_size(block); - const size_t combined = cursize + block_size(next) + block_header_overhead; - const size_t adjust = adjust_request_size(size, ALIGN_SIZE); - - tlsf_assert(!block_is_free(block) && "block already marked as free"); - - /* - ** If the next block is used, or when combined with the current - ** block, does not offer enough space, we must reallocate and copy. - */ - if (adjust > cursize && (!block_is_free(next) || adjust > combined)) - { - p = tlsf_malloc(tlsf, size); - if (p) - { - const size_t minsize = tlsf_min(cursize, size); - memcpy(p, ptr, minsize); - tlsf_free(tlsf, ptr); - } - } - else - { - /* Do we need to expand to the next block? */ - if (adjust > cursize) - { - block_merge_next(control, block); - block_mark_as_used(block); - } - - /* Trim the resulting block and return the original pointer. */ - block_trim_used(control, block, adjust); - p = ptr; - } - } - - return p; -} \ No newline at end of file diff --git a/libpsn00b/libc/tlsf.h b/libpsn00b/libc/tlsf.h deleted file mode 100644 index 399f80ad..00000000 --- a/libpsn00b/libc/tlsf.h +++ /dev/null @@ -1,92 +0,0 @@ -#pragma once - -#ifndef INCLUDED_tlsf -#define INCLUDED_tlsf - -/* -** Two Level Segregated Fit memory allocator, version 3.1. -** Written by Matthew Conte -** http://tlsf.baisoku.org -** -** Based on the original documentation by Miguel Masmano: -** http://www.gii.upv.es/tlsf/main/docs -** -** This implementation was written to the specification -** of the document, therefore no GPL restrictions apply. -** -** Copyright (c) 2006-2016, Matthew Conte -** All rights reserved. -** -** Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in the -** documentation and/or other materials provided with the distribution. -** * Neither the name of the copyright holder nor the -** names of its contributors may be used to endorse or promote products -** derived from this software without specific prior written permission. -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -** DISCLAIMED. IN NO EVENT SHALL MATTHEW CONTE BE LIABLE FOR ANY -** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include - -#if defined(__cplusplus) -extern "C" { -#endif - -/* tlsf_t: a TLSF structure. Can contain 1 to N pools. */ -/* pool_t: a block of memory that TLSF can manage. */ -typedef void* tlsf_t; -typedef void* pool_t; - -/* Create/destroy a memory pool. */ -tlsf_t tlsf_create(void* mem); -tlsf_t tlsf_create_with_pool(void* mem, size_t bytes); -void tlsf_destroy(tlsf_t tlsf); -pool_t tlsf_get_pool(tlsf_t tlsf); - -/* Add/remove memory pools. */ -pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes); -void tlsf_remove_pool(tlsf_t tlsf, pool_t pool); - -/* malloc/memalign/realloc/free replacements. */ -void* tlsf_malloc(tlsf_t tlsf, size_t bytes); -void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t bytes); -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size); -void tlsf_free(tlsf_t tlsf, void* ptr); - -/* Returns internal block size, not original request size */ -size_t tlsf_block_size(void* ptr); - -/* Overheads/limits of internal structures. */ -size_t tlsf_size(void); -size_t tlsf_align_size(void); -size_t tlsf_block_size_min(void); -size_t tlsf_block_size_max(void); -size_t tlsf_pool_overhead(void); -size_t tlsf_alloc_overhead(void); - -/* Debugging. */ -typedef void (*tlsf_walker)(void* ptr, size_t size, int used, void* user); -void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user); -/* Returns nonzero if any internal consistency check fails. */ -int tlsf_check(tlsf_t tlsf); -int tlsf_check_pool(pool_t pool); - -#if defined(__cplusplus) -}; -#endif - -#endif \ No newline at end of file From b520402ae3e3c9e0f2642d8f133979c206e54f93 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:50:08 +1100 Subject: [PATCH 032/128] Reverted from TLSF --- libpsn00b/libc/malloc.c | 463 +++++++++++++++++++++------------------- 1 file changed, 249 insertions(+), 214 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index a884c2d4..3d2a4b91 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -15,265 +15,300 @@ #include #include +#include #include -#define _align(x, n) (((x) + ((n) - 1)) & ~((n) - 1)) +#define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) /* Private types */ typedef struct _BlockHeader { - struct _BlockHeader *prev, *next; - void *ptr; - size_t size; + struct _BlockHeader *prev, *next; + void *ptr; + size_t size; } BlockHeader; /* Internal globals */ -static void *_heap_start, *_heap_end, *_heap_limit; -static size_t _heap_alloc, _heap_alloc_max; +static void *_heap_start, *_heap_end, *_heap_limit; +static size_t _heap_alloc, _heap_alloc_max; -static void *_alloc_start; -static BlockHeader *_alloc_head, *_alloc_tail; +static void *_alloc_start; +static BlockHeader *_alloc_head, *_alloc_tail; /* Heap management API */ __attribute__((weak)) void InitHeap(void *addr, size_t size) { - _heap_start = addr; - _heap_end = addr; - _heap_limit = (void *) ((uintptr_t) addr + size); + _heap_start = addr; + _heap_end = addr; + _heap_limit = (void *)((uintptr_t)addr + size); - _heap_alloc = 0; - _heap_alloc_max = 0; + _heap_alloc = 0; + _heap_alloc_max = 0; - _alloc_start = addr; - _alloc_head = 0; - _alloc_tail = 0; + _alloc_start = addr; + _alloc_head = 0; + _alloc_tail = 0; } __attribute__((weak)) void *sbrk(ptrdiff_t incr) { - void *old_end = _heap_end; - void *new_end = (void *) _align((uintptr_t) old_end + incr, 8); + void *old_end = _heap_end; + void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); + printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, + new_end); - if (new_end > _heap_limit) - return 0; + if (new_end > _heap_limit) + return 0; - _heap_end = new_end; - return old_end; + _heap_end = new_end; + return old_end; } __attribute__((weak)) void TrackHeapUsage(ptrdiff_t alloc_incr) { - _heap_alloc += alloc_incr; + _heap_alloc += alloc_incr; - if (_heap_alloc > _heap_alloc_max) - _heap_alloc_max = _heap_alloc; + if (_heap_alloc > _heap_alloc_max) + _heap_alloc_max = _heap_alloc; } __attribute__((weak)) void GetHeapUsage(HeapUsage *usage) { - usage->total = _heap_limit - _heap_start; - usage->heap = _heap_end - _heap_start; - usage->stack = _heap_limit - _heap_end; + usage->total = _heap_limit - _heap_start; + usage->heap = _heap_end - _heap_start; + usage->stack = _heap_limit - _heap_end; - usage->alloc = _heap_alloc; - usage->alloc_max = _heap_alloc_max; + usage->alloc = _heap_alloc; + usage->alloc_max = _heap_alloc_max; } /* Memory allocator */ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { - BlockHeader *prev = head; - - for (; prev; prev = prev->next) { - if (prev->next) { - uintptr_t next_bot = (uintptr_t) prev->next; - next_bot -= (uintptr_t) prev->ptr + prev->size; - - if (next_bot >= size) - return prev; - } - } - - return prev; + BlockHeader *prev = head; + printf("[FindFit] size: 0x%x\n", size); + for (; prev; prev = prev->next) { + if (prev->next) { + uintptr_t next_bot = (uintptr_t)prev->next; + printf("[FindFit] next_bot: %p\n", (void *)next_bot); + next_bot -= (uintptr_t)prev->ptr + prev->size; + printf("[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", + prev->ptr, prev->size, prev->ptr + prev->size, (void *)next_bot); + if (next_bot >= size) { + printf("[FindFit] found %p\n", prev); + return prev; + } + } + } + printf("[FindFit] Not found: %p\n", prev); + return prev; } __attribute__((weak)) void *malloc(size_t size) { - if (!size) - return 0; - - size_t _size = _align(size + sizeof(BlockHeader), 8); - - // Nothing's initialized yet? Let's just initialize the bottom of our heap, - // flag it as allocated. - if (!_alloc_head) { - //if (!_alloc_start) - //_alloc_start = sbrk(0); - - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = 0; - - _alloc_head = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; - } - - // We *may* have the bottom of our heap that has shifted, because of a free. - // So let's check first if we have free space there, because I'm nervous - // about having an incomplete data structure. - if (((uintptr_t) _alloc_start + _size) < ((uintptr_t) _alloc_head)) { - BlockHeader *new = (BlockHeader *) _alloc_start; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = 0; - new->next = _alloc_head; - - _alloc_head->prev = new; - _alloc_head = new; - - TrackHeapUsage(size); - return ptr; - } - - // No luck at the beginning of the heap, let's walk the heap to find a fit. - BlockHeader *prev = _find_fit(_alloc_head, _size); - if (prev) { - BlockHeader *new = (BlockHeader *) ((uintptr_t) prev->ptr + prev->size); - - void *ptr = (void *)((uintptr_t) new + sizeof(BlockHeader)); - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = prev; - new->next = prev->next; - - (new->next)->prev = new; - prev->next = new; - - TrackHeapUsage(size); - return ptr; - } - - // Time to extend the size of the heap. - BlockHeader *new = (BlockHeader *) sbrk(_size); - if (!new) - return 0; - - void *ptr = (void *) &new[1]; - new->ptr = ptr; - new->size = _size - sizeof(BlockHeader); - new->prev = _alloc_tail; - new->next = 0; - - _alloc_tail->next = new; - _alloc_tail = new; - - TrackHeapUsage(size); - return ptr; + if (!size) + return 0; + + size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size_nh = _size - sizeof(BlockHeader); + + // Nothing's initialized yet? Let's just initialize the bottom of our heap, + // flag it as allocated. + if (!_alloc_head) { + // if (!_alloc_start) + //_alloc_start = sbrk(0); + + BlockHeader *new = (BlockHeader *)sbrk(_size); + if (!new) + return 0; + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size_nh; + new->prev = 0; + new->next = 0; + + _alloc_head = new; + _alloc_tail = new; + + TrackHeapUsage(_size); + return ptr; + } + + // We *may* have the bottom of our heap that has shifted, because of a free. + // So let's check first if we have free space there, because I'm nervous + // about having an incomplete data structure. + if (((uintptr_t)_alloc_start + _size) < ((uintptr_t)_alloc_head)) { + printf("[Malloc] bottom heap shifted: %p < %p\n", _alloc_start + _size, + _alloc_head); + BlockHeader *new = (BlockHeader *)_alloc_start; + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size_nh; + new->prev = 0; + new->next = _alloc_head; + printf("[Malloc] new->next: %p\n", new->next); + + _alloc_head->prev = new; + _alloc_head = new; + + TrackHeapUsage(_size); + return ptr; + } + + // No luck at the beginning of the heap, let's walk the heap to find a fit. + BlockHeader *prev = _find_fit(_alloc_head, _size); + if (prev) { + BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); + printf("[Malloc] found fit: %p\n", new); + + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size_nh; + new->prev = prev; + new->next = prev->next; + printf("[Malloc] fit, new->next: %p\n", new->next); + + (new->next)->prev = new; + prev->next = new; + printf("[Malloc] fit, prev->next: %p\n", prev->next); + + TrackHeapUsage(_size); + return ptr; + } + + // Time to extend the size of the heap. + BlockHeader *new = (BlockHeader *)sbrk(_size); + if (!new) + return 0; + printf("[Malloc] extended heap: %p\n", new); + void *ptr = (void *)&new[1]; + new->ptr = ptr; + new->size = _size_nh; + new->prev = _alloc_tail; + new->next = 0; + + _alloc_tail->next = new; + printf("[Malloc] extend, _alloc_tail->next: %p\n", _alloc_tail->next); + _alloc_tail = new; + + TrackHeapUsage(_size); + return ptr; } __attribute__((weak)) void *calloc(size_t num, size_t size) { - return malloc(num * size); + return malloc(num * size); } __attribute__((weak)) void *realloc(void *ptr, size_t size) { - if (!size) { - free(ptr); - return 0; - } - if (!ptr) - return malloc(size); - - size_t _size = _align(size + sizeof(BlockHeader), 8); - BlockHeader *prev = (BlockHeader *) ((uintptr_t) ptr - sizeof(BlockHeader)); - - // New memory block shorter? - if (prev->size >= _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - - if (!prev->next) - sbrk((ptr - sbrk(0)) + _size); - - return ptr; - } - - // New memory block larger; is it the last one? - if (!prev->next) { - void *new = sbrk(_size - prev->size); - if (!new) - return 0; - - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // Do we have free memory after it? - if (((prev->next)->ptr - ptr) > _size) { - TrackHeapUsage(size - prev->size); - prev->size = _size - sizeof(BlockHeader); - return ptr; - } - - // No luck. - void *new = malloc(size); - if (!new) - return 0; - - __builtin_memcpy(new, ptr, prev->size); - free(ptr); - return new; + if (!size) { + free(ptr); + return 0; + } + if (!ptr) + return malloc(size); + + size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size_nh = _size - sizeof(BlockHeader); + BlockHeader *prev = (BlockHeader *)((uintptr_t)ptr - sizeof(BlockHeader)); + + // New memory block shorter? + if (prev->size >= _size_nh) { + printf("[Realloc] new size shorter: 0x%x >= 0x%x\n", prev->size, _size_nh); + TrackHeapUsage(_size_nh - prev->size); + prev->size = _size_nh; + + // This is the last block, move the break back to accomodate shrinking + if (!prev->next) { + // We have overriden prev->size, need to calculate it from break + void *new_break = sbrk((ptr - sbrk(0)) + _size_nh); + printf("[Realloc] last block, shrink break: %p\n", new_break); + } + return ptr; + } + + // New memory block larger; is it the last one? + if (!prev->next) { + printf("[Realloc] new block larger\n"); + void *new = sbrk(_size_nh - prev->size); + if (!new) + return 0; + printf("[Realloc] new break: 0x%x => %p\n", _size_nh - prev->size, new); + TrackHeapUsage(_size_nh - prev->size); + prev->size = _size_nh; + return ptr; + } + + // Do we have free memory after it? + if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { + printf("[Realloc] free mem after: 0x%x >= 0x%x\n", + (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); + TrackHeapUsage(_size_nh - prev->size); + prev->size = _size_nh; + return ptr; + } + + // No luck. + void *new = malloc(size); + if (!new) + return 0; + printf("[Realloc] new malloc addr: %p\n", new); + __builtin_memcpy(new, ptr, prev->size); + free(ptr); + return new; } __attribute__((weak)) void free(void *ptr) { - if (!ptr || !_alloc_head) - return; - - // First block; bumping head ahead. - if (ptr == _alloc_head->ptr) { - size_t size = _alloc_head->size; - size += (uintptr_t) _alloc_head->ptr - (uintptr_t) _alloc_head; - _alloc_head = _alloc_head->next; - - if (_alloc_head) { - _alloc_head->prev = 0; - } else { - _alloc_tail = 0; - sbrk(-size); - } - - TrackHeapUsage(-(_alloc_head->size)); - return; - } - - // Finding the proper block - BlockHeader *cur = _alloc_head; - - for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { - if (!cur->next) - return; - } - - if (cur->next) { - // In the middle, just unlink it - (cur->next)->prev = cur->prev; - } else { - // At the end, shrink heap - void *top = sbrk(0); - size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; - _alloc_tail = cur->prev; - - sbrk(-size); - } - - TrackHeapUsage(-(cur->size)); - (cur->prev)->next = cur->next; + if (!ptr || !_alloc_head) + return; + + // First block; bumping head ahead. + if (ptr == _alloc_head->ptr) { + printf("[Free] first block, bump head forward\n"); + size_t size = _alloc_head->size; + size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; + printf("[Free] size: 0x%x\n", size); + _alloc_head = _alloc_head->next; + printf("[Free] new head: %p\n", _alloc_head); + if (_alloc_head) { + _alloc_head->prev = 0; + printf("[Free] New head exists, setting prev to null\n"); + } else { + printf("[Free] No new head exists, nulling tail\n"); + _alloc_tail = 0; + sbrk(-size); + } + + TrackHeapUsage(-size); + return; + } + + // Finding the proper block + BlockHeader *cur = _alloc_head; + printf("[Free] find block, base: %p\n", cur); + for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { + if (!cur->next) + return; + } + printf("[Free] found: %p\n", cur); + + if (cur->next) { + // In the middle, just unlink it + printf("[Free] has next, setting next->prev to cur->prev: %p\n", cur->prev); + (cur->next)->prev = cur->prev; + } else { + // At the end, shrink heap + printf("[Free] at end of heap\n"); + void *top = sbrk(0); + printf("[Free] heap top: %p\n", top); + size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; + printf("[Free] size: 0x%x\n", size); + _alloc_tail = cur->prev; + + printf("[Free] new tail: %p\n", _alloc_tail); + sbrk(-size); + } + printf("[Free] heap_change: 0x%x\n", -(cur->size) - sizeof(BlockHeader)); + TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); + (cur->prev)->next = cur->next; + printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); + printf("[Free] setting prev->next to cur->next: %p\n", cur->next); } \ No newline at end of file From 91e080fdc503d1c8cb2decbd1d80ac90285aaf20 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 21:59:35 +1100 Subject: [PATCH 033/128] Reverted from TLSF --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 3d2a4b91..b79756b8 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -53,7 +53,7 @@ __attribute__((weak)) void InitHeap(void *addr, size_t size) { __attribute__((weak)) void *sbrk(ptrdiff_t incr) { void *old_end = _heap_end; - void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); + void *new_end = (void*) old_end + incr;// (void *)_align((uintptr_t)old_end + incr, 8); printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); From dd1fc33fe84886fac69768b36328a038d2dae174 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 22:48:59 +1100 Subject: [PATCH 034/128] Fixed prints --- libpsn00b/libc/malloc.c | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index b79756b8..252c5d47 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -53,7 +53,7 @@ __attribute__((weak)) void InitHeap(void *addr, size_t size) { __attribute__((weak)) void *sbrk(ptrdiff_t incr) { void *old_end = _heap_end; - void *new_end = (void*) old_end + incr;// (void *)_align((uintptr_t)old_end + incr, 8); + void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); @@ -219,8 +219,9 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // This is the last block, move the break back to accomodate shrinking if (!prev->next) { // We have overriden prev->size, need to calculate it from break - void *new_break = sbrk((ptr - sbrk(0)) + _size_nh); - printf("[Realloc] last block, shrink break: %p\n", new_break); + void* top = sbrk(0); + void *new_break = sbrk((ptr - top) + _size_nh); + printf("[Realloc] last block, shrink break: (%p - %p) + 0x%x => %p\n", ptr, top, _size_nh, new_break); } return ptr; } @@ -238,9 +239,8 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { } // Do we have free memory after it? - if (((prev->next)->ptr - sizeof(BlockHeader) - ptr) >= _size_nh) { - printf("[Realloc] free mem after: 0x%x >= 0x%x\n", - (prev->next)->ptr - sizeof(BlockHeader) - ptr, _size_nh); + if (prev->next - ptr >= _size_nh) { + printf("[Realloc] free mem after: %p >= 0x%x\n", prev->next - ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -263,8 +263,9 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = _alloc_head->size; - size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; + size_t size = (((uinptr_t)_alloc_head->ptr) + _alloc_head->size) - (uintptr_t)_alloc_head + //size_t size = _alloc_head->size; + //size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; printf("[Free] new head: %p\n", _alloc_head); @@ -306,8 +307,8 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); } - printf("[Free] heap_change: 0x%x\n", -(cur->size) - sizeof(BlockHeader)); - TrackHeapUsage(-(cur->size) - sizeof(BlockHeader)); + printf("[Free] heap_change: 0x%x\n", -(cur->size - sizeof(BlockHeader))); + TrackHeapUsage(-(cur->size - sizeof(BlockHeader))); (cur->prev)->next = cur->next; printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); printf("[Free] setting prev->next to cur->next: %p\n", cur->next); From e265713056613f55d4f03d4d987eb0c8ba7c5782 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 22:52:55 +1100 Subject: [PATCH 035/128] Fixed prints --- libpsn00b/libc/malloc.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 252c5d47..039472cb 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -239,8 +239,8 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { } // Do we have free memory after it? - if (prev->next - ptr >= _size_nh) { - printf("[Realloc] free mem after: %p >= 0x%x\n", prev->next - ptr, _size_nh); + if ((uintptr_t)prev->next - (uintptr_t)ptr >= _size_nh) { + printf("[Realloc] free mem after: %p >= 0x%x\n", (uintptr_t)prev->next - (uintptr_t)ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -263,7 +263,7 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = (((uinptr_t)_alloc_head->ptr) + _alloc_head->size) - (uintptr_t)_alloc_head + size_t size = (((uintptr_t)_alloc_head->ptr) + _alloc_head->size) - (uintptr_t)_alloc_head; //size_t size = _alloc_head->size; //size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); From 7064335d9be464c43c96ca64d9744bd0c88eda96 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:02:36 +1100 Subject: [PATCH 036/128] Fixed prints --- libpsn00b/libc/malloc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 039472cb..b8fbfd24 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -286,6 +286,7 @@ __attribute__((weak)) void free(void *ptr) { BlockHeader *cur = _alloc_head; printf("[Free] find block, base: %p\n", cur); for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { + printf("[Free] cur: %p cur->next: %p\n", cur, cur->next); if (!cur->next) return; } @@ -293,7 +294,7 @@ __attribute__((weak)) void free(void *ptr) { if (cur->next) { // In the middle, just unlink it - printf("[Free] has next, setting next->prev to cur->prev: %p\n", cur->prev); + printf("[Free] has next %p, setting cur->next->prev to cur->prev: %p\n", cur->next, cur->prev); (cur->next)->prev = cur->prev; } else { // At the end, shrink heap From edcd9b23b84eb45c771144ffdf350e5b9c7da4b9 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:25:45 +1100 Subject: [PATCH 037/128] Fixed prints --- libpsn00b/libc/malloc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index b8fbfd24..95a2bbd7 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -157,10 +157,10 @@ __attribute__((weak)) void *malloc(size_t size) { // No luck at the beginning of the heap, let's walk the heap to find a fit. BlockHeader *prev = _find_fit(_alloc_head, _size); if (prev) { - BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); + BlockHeader* new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); printf("[Malloc] found fit: %p\n", new); - void *ptr = (void *)&new[1]; + void *ptr = (void *)(new + sizeof(BlockHeader)); new->ptr = ptr; new->size = _size_nh; new->prev = prev; @@ -176,11 +176,11 @@ __attribute__((weak)) void *malloc(size_t size) { } // Time to extend the size of the heap. - BlockHeader *new = (BlockHeader *)sbrk(_size); + BlockHeader* new = (BlockHeader *)sbrk(_size); if (!new) return 0; printf("[Malloc] extended heap: %p\n", new); - void *ptr = (void *)&new[1]; + void *ptr = (void *)(new + sizeof(BlockHeader)); new->ptr = ptr; new->size = _size_nh; new->prev = _alloc_tail; From ff02ba554de67df6d671e979c844736f111567ab Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:30:16 +1100 Subject: [PATCH 038/128] Fixed prints --- libpsn00b/libc/malloc.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 95a2bbd7..695a5fdf 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -119,7 +119,7 @@ __attribute__((weak)) void *malloc(size_t size) { if (!new) return 0; - void *ptr = (void *)&new[1]; + void *ptr = (void *)(new + sizeof(BlockHeader)); new->ptr = ptr; new->size = _size_nh; new->prev = 0; @@ -140,7 +140,7 @@ __attribute__((weak)) void *malloc(size_t size) { _alloc_head); BlockHeader *new = (BlockHeader *)_alloc_start; - void *ptr = (void *)&new[1]; + void *ptr = (void *)(new + sizeof(BlockHeader)); new->ptr = ptr; new->size = _size_nh; new->prev = 0; From 0fd216338072775a3665972a98c5a42c47e209d4 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:42:01 +1100 Subject: [PATCH 039/128] Fixed prints --- libpsn00b/libc/malloc.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 695a5fdf..530f6071 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -90,8 +90,13 @@ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { uintptr_t next_bot = (uintptr_t)prev->next; printf("[FindFit] next_bot: %p\n", (void *)next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - printf("[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", - prev->ptr, prev->size, prev->ptr + prev->size, (void *)next_bot); + printf( + "[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", + prev->ptr, + prev->size, + prev->ptr + prev->size, + (void *)next_bot + ); if (next_bot >= size) { printf("[FindFit] found %p\n", prev); return prev; @@ -118,8 +123,9 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader *new = (BlockHeader *)sbrk(_size); if (!new) return 0; - + printf("[Malloc] new: %p\n, new); void *ptr = (void *)(new + sizeof(BlockHeader)); + printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; new->prev = 0; @@ -139,8 +145,10 @@ __attribute__((weak)) void *malloc(size_t size) { printf("[Malloc] bottom heap shifted: %p < %p\n", _alloc_start + _size, _alloc_head); BlockHeader *new = (BlockHeader *)_alloc_start; + printf("[Malloc] new: %p\n", new); void *ptr = (void *)(new + sizeof(BlockHeader)); + printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; new->prev = 0; @@ -161,6 +169,7 @@ __attribute__((weak)) void *malloc(size_t size) { printf("[Malloc] found fit: %p\n", new); void *ptr = (void *)(new + sizeof(BlockHeader)); + printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; new->prev = prev; @@ -181,13 +190,14 @@ __attribute__((weak)) void *malloc(size_t size) { return 0; printf("[Malloc] extended heap: %p\n", new); void *ptr = (void *)(new + sizeof(BlockHeader)); + printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; new->prev = _alloc_tail; new->next = 0; _alloc_tail->next = new; - printf("[Malloc] extend, _alloc_tail->next: %p\n", _alloc_tail->next); + printf("[Malloc] extend _alloc_tail->next: %p\n", _alloc_tail->next); _alloc_tail = new; TrackHeapUsage(_size); From 6f28a2232e77678a88c6548f45968277ee166110 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:45:13 +1100 Subject: [PATCH 040/128] Fixed prints --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 530f6071..db0c8403 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -123,7 +123,7 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader *new = (BlockHeader *)sbrk(_size); if (!new) return 0; - printf("[Malloc] new: %p\n, new); + printf("[Malloc] new: %p\n", new); void *ptr = (void *)(new + sizeof(BlockHeader)); printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; From 8ed1a11948bc242d39cc44d8de59310fd2e1b634 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Thu, 18 Jan 2024 23:55:07 +1100 Subject: [PATCH 041/128] Fixed prints --- libpsn00b/libc/malloc.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index db0c8403..c1e606b7 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -132,7 +132,9 @@ __attribute__((weak)) void *malloc(size_t size) { new->next = 0; _alloc_head = new; + printf("[Malloc] _alloc_head: %p\n", _alloc_head); _alloc_tail = new; + printf("[Malloc] _alloc_tail: %p\n", _alloc_tail); TrackHeapUsage(_size); return ptr; @@ -154,9 +156,11 @@ __attribute__((weak)) void *malloc(size_t size) { new->prev = 0; new->next = _alloc_head; printf("[Malloc] new->next: %p\n", new->next); - _alloc_head->prev = new; + printf("[Malloc] _alloc_head->prev: %p\n", new); _alloc_head = new; + printf("[Malloc] _alloc_head: %p\n", new); + printf("[Malloc] Unset here, _alloc_tail: %p\n", _alloc_tail); TrackHeapUsage(_size); return ptr; @@ -197,8 +201,10 @@ __attribute__((weak)) void *malloc(size_t size) { new->next = 0; _alloc_tail->next = new; - printf("[Malloc] extend _alloc_tail->next: %p\n", _alloc_tail->next); + printf("[Malloc] alloc_tail->next: %p\n", _alloc_tail->next); _alloc_tail = new; + printf("[Malloc] _alloc_tail: %p\n", _alloc_tail); + printf("[Malloc] Unset here, _alloc_head: %p\n", _alloc_head); TrackHeapUsage(_size); return ptr; From 01abbbdb26a52df1aef6b3b76e7d12c404f4c53a Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Fri, 19 Jan 2024 00:14:49 +1100 Subject: [PATCH 042/128] Added print statements --- libpsn00b/libc/malloc.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index c1e606b7..87fb1ead 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -127,6 +127,7 @@ __attribute__((weak)) void *malloc(size_t size) { void *ptr = (void *)(new + sizeof(BlockHeader)); printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; + printf("[Malloc] size: 0x%x\n", _size_nh); new->size = _size_nh; new->prev = 0; new->next = 0; @@ -176,9 +177,11 @@ __attribute__((weak)) void *malloc(size_t size) { printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; + printf("[Malloc] size: 0x%x\n", new->size); new->prev = prev; + printf("[Malloc] prev: %p\n", new->prev); new->next = prev->next; - printf("[Malloc] fit, new->next: %p\n", new->next); + printf("[Malloc] next: %p\n", new->next); (new->next)->prev = new; prev->next = new; @@ -197,8 +200,11 @@ __attribute__((weak)) void *malloc(size_t size) { printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; + printf("[Malloc] size: 0x%x\n", _size_nh); new->prev = _alloc_tail; + printf("[Malloc] prev: %p\n", new->prev); new->next = 0; + printf("[Malloc] next: %p\n", new->next); _alloc_tail->next = new; printf("[Malloc] alloc_tail->next: %p\n", _alloc_tail->next); From ab7c7e3400305f6a8882b0d1c8f5ee3f7cd6606a Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Fri, 19 Jan 2024 00:38:53 +1100 Subject: [PATCH 043/128] Added print statements --- libpsn00b/libc/malloc.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 87fb1ead..a141d0d5 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -40,7 +40,9 @@ static BlockHeader *_alloc_head, *_alloc_tail; __attribute__((weak)) void InitHeap(void *addr, size_t size) { _heap_start = addr; + printf("[Init] heap start %p\n", _heap_start); _heap_end = addr; + printf("[Init] heap end %p\n", _heap_end); _heap_limit = (void *)((uintptr_t)addr + size); _heap_alloc = 0; @@ -52,7 +54,9 @@ __attribute__((weak)) void InitHeap(void *addr, size_t size) { } __attribute__((weak)) void *sbrk(ptrdiff_t incr) { + printf("[Sbrk] Increment: 0x%x\n", incr); void *old_end = _heap_end; + printf("[Sbrk] old end: %p\n", old_end); void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); From 69305717d258507f44c2edce3716f4be63e03a8e Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Fri, 19 Jan 2024 00:47:09 +1100 Subject: [PATCH 044/128] Added print statements --- libpsn00b/libc/malloc.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index a141d0d5..4ff59dd9 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -128,7 +128,7 @@ __attribute__((weak)) void *malloc(size_t size) { if (!new) return 0; printf("[Malloc] new: %p\n", new); - void *ptr = (void *)(new + sizeof(BlockHeader)); + void *ptr = (void *)&new[1]; printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; printf("[Malloc] size: 0x%x\n", _size_nh); @@ -154,7 +154,7 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader *new = (BlockHeader *)_alloc_start; printf("[Malloc] new: %p\n", new); - void *ptr = (void *)(new + sizeof(BlockHeader)); + void *ptr = (void *)&new[1]; printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; @@ -177,7 +177,7 @@ __attribute__((weak)) void *malloc(size_t size) { BlockHeader* new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); printf("[Malloc] found fit: %p\n", new); - void *ptr = (void *)(new + sizeof(BlockHeader)); + void *ptr = (void *)&new[1]; printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; @@ -200,7 +200,7 @@ __attribute__((weak)) void *malloc(size_t size) { if (!new) return 0; printf("[Malloc] extended heap: %p\n", new); - void *ptr = (void *)(new + sizeof(BlockHeader)); + void *ptr = (void *)&new[1]; printf("[Malloc] ptr: %p\n", ptr); new->ptr = ptr; new->size = _size_nh; From 28a03aab97ff6a8bff75bfed8886067e887ea11f Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Fri, 19 Jan 2024 00:53:27 +1100 Subject: [PATCH 045/128] Added print statements --- libpsn00b/libc/malloc.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 4ff59dd9..e21c8074 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -129,7 +129,9 @@ __attribute__((weak)) void *malloc(size_t size) { return 0; printf("[Malloc] new: %p\n", new); void *ptr = (void *)&new[1]; + // TODO: Need to explain/understand why these two are different. printf("[Malloc] ptr: %p\n", ptr); + printf("[Malloc] pointer arithmetic ptr: %p\n", (void*)(new + sizeof(BlockHeader))); new->ptr = ptr; printf("[Malloc] size: 0x%x\n", _size_nh); new->size = _size_nh; From 8f2907a0983b4fdc566f246d2203e6f08c8efcdd Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Fri, 19 Jan 2024 00:59:46 +1100 Subject: [PATCH 046/128] Added print statements --- libpsn00b/libc/malloc.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index e21c8074..e327efb1 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -22,7 +22,7 @@ /* Private types */ -typedef struct _BlockHeader { +typedef struct __attribute__((aligned (8))) _BlockHeader { struct _BlockHeader *prev, *next; void *ptr; size_t size; From 811add52955c724aef03edb2377ee47b4b68454a Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 13:05:37 +1100 Subject: [PATCH 047/128] Reverted changes to indexing --- .idea/.gitignore | 8 -- .idea/PSn00bSDK.iml | 2 + .idea/editor.xml | 102 ++++++++++++++++++ .idea/misc.xml | 4 + .idea/modules.xml | 8 ++ .idea/vcs.xml | 6 ++ .idea/workspace.xml | 98 +++++++++++++++++ .../CMakeFiles/clion-Debug-log.txt | 8 -- libpsn00b/libc/malloc.c | 51 +++++---- 9 files changed, 244 insertions(+), 43 deletions(-) delete mode 100644 .idea/.gitignore create mode 100644 .idea/PSn00bSDK.iml create mode 100644 .idea/editor.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 .idea/workspace.xml diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b81..00000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/PSn00bSDK.iml b/.idea/PSn00bSDK.iml new file mode 100644 index 00000000..f08604bb --- /dev/null +++ b/.idea/PSn00bSDK.iml @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/.idea/editor.xml b/.idea/editor.xml new file mode 100644 index 00000000..4642935f --- /dev/null +++ b/.idea/editor.xml @@ -0,0 +1,102 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..79b3c948 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 00000000..348e7160 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 00000000..93106b21 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1705716046414 + + + + + + + + + + + \ No newline at end of file diff --git a/cmake-build-debug/CMakeFiles/clion-Debug-log.txt b/cmake-build-debug/CMakeFiles/clion-Debug-log.txt index f81b7341..5713fe9e 100644 --- a/cmake-build-debug/CMakeFiles/clion-Debug-log.txt +++ b/cmake-build-debug/CMakeFiles/clion-Debug-log.txt @@ -1,12 +1,4 @@ "/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/bin/cmake" -DCMAKE_BUILD_TYPE=Debug "-DCMAKE_MAKE_PROGRAM=/Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/ninja/mac/x64/ninja" -G Ninja -S /Users/jackkilrain/PSn00bSDK -B /Users/jackkilrain/PSn00bSDK/cmake-build-debug -CMake Warning (dev) at /Users/jackkilrain/Library/Application Support/JetBrains/Toolbox/apps/CLion-Nova/ch-0/233.13871/CLion 2023.3 EAP.app/Contents/bin/cmake/mac/x64/share/cmake-3.27/Modules/GNUInstallDirs.cmake:243 (message): - Unable to determine default CMAKE_INSTALL_LIBDIR directory because no - target architecture is known. Please enable at least one language before - including GNUInstallDirs. -Call Stack (most recent call first): - CMakeLists.txt:22 (include) -This warning is for project developers. Use -Wno-dev to suppress it. - CMake Error at CMakeLists.txt:125 (message): The mkpsxiso directory is empty. Run 'git submodule update --init --recursive' to populate it. diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index e327efb1..9ca0525a 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -18,11 +18,12 @@ #include #include +#define ALIGN_SIZE 8 #define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) /* Private types */ -typedef struct __attribute__((aligned (8))) _BlockHeader { +typedef struct __attribute__((aligned(ALIGN_SIZE))) _BlockHeader { struct _BlockHeader *prev, *next; void *ptr; size_t size; @@ -57,7 +58,7 @@ __attribute__((weak)) void *sbrk(ptrdiff_t incr) { printf("[Sbrk] Increment: 0x%x\n", incr); void *old_end = _heap_end; printf("[Sbrk] old end: %p\n", old_end); - void *new_end = (void *)_align((uintptr_t)old_end + incr, 8); + void *new_end = (void *)_align((uintptr_t)old_end + incr, ALIGN_SIZE); printf("[Sbrk] literal shift %p, aligned shift %p\n", old_end + incr, new_end); @@ -94,13 +95,8 @@ static BlockHeader *_find_fit(BlockHeader *head, size_t size) { uintptr_t next_bot = (uintptr_t)prev->next; printf("[FindFit] next_bot: %p\n", (void *)next_bot); next_bot -= (uintptr_t)prev->ptr + prev->size; - printf( - "[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", - prev->ptr, - prev->size, - prev->ptr + prev->size, - (void *)next_bot - ); + printf("[FindFit] ptr: %p, size: 0x%x, offset: %p, next_bot: %p\n", + prev->ptr, prev->size, prev->ptr + prev->size, (void *)next_bot); if (next_bot >= size) { printf("[FindFit] found %p\n", prev); return prev; @@ -115,7 +111,7 @@ __attribute__((weak)) void *malloc(size_t size) { if (!size) return 0; - size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size = _align(size + sizeof(BlockHeader), ALIGN_SIZE); size_t _size_nh = _size - sizeof(BlockHeader); // Nothing's initialized yet? Let's just initialize the bottom of our heap, @@ -129,9 +125,6 @@ __attribute__((weak)) void *malloc(size_t size) { return 0; printf("[Malloc] new: %p\n", new); void *ptr = (void *)&new[1]; - // TODO: Need to explain/understand why these two are different. - printf("[Malloc] ptr: %p\n", ptr); - printf("[Malloc] pointer arithmetic ptr: %p\n", (void*)(new + sizeof(BlockHeader))); new->ptr = ptr; printf("[Malloc] size: 0x%x\n", _size_nh); new->size = _size_nh; @@ -176,7 +169,7 @@ __attribute__((weak)) void *malloc(size_t size) { // No luck at the beginning of the heap, let's walk the heap to find a fit. BlockHeader *prev = _find_fit(_alloc_head, _size); if (prev) { - BlockHeader* new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); + BlockHeader *new = (BlockHeader *)((uintptr_t)prev->ptr + prev->size); printf("[Malloc] found fit: %p\n", new); void *ptr = (void *)&new[1]; @@ -198,7 +191,7 @@ __attribute__((weak)) void *malloc(size_t size) { } // Time to extend the size of the heap. - BlockHeader* new = (BlockHeader *)sbrk(_size); + BlockHeader *new = (BlockHeader *)sbrk(_size); if (!new) return 0; printf("[Malloc] extended heap: %p\n", new); @@ -234,7 +227,7 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { if (!ptr) return malloc(size); - size_t _size = _align(size + sizeof(BlockHeader), 8); + size_t _size = _align(size + sizeof(BlockHeader), ALIGN_SIZE); size_t _size_nh = _size - sizeof(BlockHeader); BlockHeader *prev = (BlockHeader *)((uintptr_t)ptr - sizeof(BlockHeader)); @@ -247,9 +240,10 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // This is the last block, move the break back to accomodate shrinking if (!prev->next) { // We have overriden prev->size, need to calculate it from break - void* top = sbrk(0); + void *top = sbrk(0); void *new_break = sbrk((ptr - top) + _size_nh); - printf("[Realloc] last block, shrink break: (%p - %p) + 0x%x => %p\n", ptr, top, _size_nh, new_break); + printf("[Realloc] last block, shrink break: (%p - %p) + 0x%x => %p\n", + ptr, top, _size_nh, new_break); } return ptr; } @@ -268,7 +262,8 @@ __attribute__((weak)) void *realloc(void *ptr, size_t size) { // Do we have free memory after it? if ((uintptr_t)prev->next - (uintptr_t)ptr >= _size_nh) { - printf("[Realloc] free mem after: %p >= 0x%x\n", (uintptr_t)prev->next - (uintptr_t)ptr, _size_nh); + printf("[Realloc] free mem after: %p >= 0x%x\n", + (uintptr_t)prev->next - (uintptr_t)ptr, _size_nh); TrackHeapUsage(_size_nh - prev->size); prev->size = _size_nh; return ptr; @@ -291,9 +286,10 @@ __attribute__((weak)) void free(void *ptr) { // First block; bumping head ahead. if (ptr == _alloc_head->ptr) { printf("[Free] first block, bump head forward\n"); - size_t size = (((uintptr_t)_alloc_head->ptr) + _alloc_head->size) - (uintptr_t)_alloc_head; - //size_t size = _alloc_head->size; - //size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; + size_t size = (((uintptr_t)_alloc_head->ptr) + _alloc_head->size) - + (uintptr_t)_alloc_head; + // size_t size = _alloc_head->size; + // size += (uintptr_t)_alloc_head->ptr - (uintptr_t)_alloc_head; printf("[Free] size: 0x%x\n", size); _alloc_head = _alloc_head->next; printf("[Free] new head: %p\n", _alloc_head); @@ -314,7 +310,7 @@ __attribute__((weak)) void free(void *ptr) { BlockHeader *cur = _alloc_head; printf("[Free] find block, base: %p\n", cur); for (cur = _alloc_head; ptr != cur->ptr; cur = cur->next) { - printf("[Free] cur: %p cur->next: %p\n", cur, cur->next); + printf("[Free] cur: %p cur->next: %p\n", cur, cur->next); if (!cur->next) return; } @@ -322,7 +318,8 @@ __attribute__((weak)) void free(void *ptr) { if (cur->next) { // In the middle, just unlink it - printf("[Free] has next %p, setting cur->next->prev to cur->prev: %p\n", cur->next, cur->prev); + printf("[Free] has next %p, setting cur->next->prev to cur->prev: %p\n", + cur->next, cur->prev); (cur->next)->prev = cur->prev; } else { // At the end, shrink heap @@ -336,9 +333,9 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] new tail: %p\n", _alloc_tail); sbrk(-size); } - printf("[Free] heap_change: 0x%x\n", -(cur->size - sizeof(BlockHeader))); - TrackHeapUsage(-(cur->size - sizeof(BlockHeader))); + printf("[Free] heap_change: 0x%x\n", -(cur->size + sizeof(BlockHeader))); + TrackHeapUsage(-(cur->size + sizeof(BlockHeader))); (cur->prev)->next = cur->next; printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); printf("[Free] setting prev->next to cur->next: %p\n", cur->next); -} \ No newline at end of file +} From 1ad7cdad42976e58b1772b0d1d47f61583fc57e9 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 15:40:30 +1100 Subject: [PATCH 048/128] Fixed free at end size calculation --- .idea/workspace.xml | 27 ++++++++++++--------------- libpsn00b/libc/malloc.c | 12 ++++++------ 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 93106b21..585a8252 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -3,9 +3,9 @@ - + { + "useNewFormat": true +} @@ -22,8 +22,7 @@ - - + - + { + "associatedIndex": 4 +} - - - - - - @@ -84,6 +80,7 @@ diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 9ca0525a..2e1f09b2 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -315,18 +315,18 @@ __attribute__((weak)) void free(void *ptr) { return; } printf("[Free] found: %p\n", cur); - + printf("[Free] cur->next: %p\n", cur->next); if (cur->next) { // In the middle, just unlink it - printf("[Free] has next %p, setting cur->next->prev to cur->prev: %p\n", - cur->next, cur->prev); + printf("[Free] has next %p, setting cur->next->prev: %p to cur->prev: %p\n", + (cur->next)->prev, cur->next, cur->prev); (cur->next)->prev = cur->prev; } else { // At the end, shrink heap printf("[Free] at end of heap\n"); void *top = sbrk(0); printf("[Free] heap top: %p\n", top); - size_t size = (top - (cur->prev)->ptr) + (cur->prev)->size; + size_t size = (top - (cur->prev)->ptr) - (cur->prev)->size; printf("[Free] size: 0x%x\n", size); _alloc_tail = cur->prev; @@ -335,7 +335,7 @@ __attribute__((weak)) void free(void *ptr) { } printf("[Free] heap_change: 0x%x\n", -(cur->size + sizeof(BlockHeader))); TrackHeapUsage(-(cur->size + sizeof(BlockHeader))); - (cur->prev)->next = cur->next; printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); - printf("[Free] setting prev->next to cur->next: %p\n", cur->next); + (cur->prev)->next = cur->next; + printf("[Free] setting cur->prev->next to cur->next: %p\n", cur->next); } From 290c399d09d0e42b5ca42a872cd975080ee0c0f4 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 15:51:30 +1100 Subject: [PATCH 049/128] Fixed free at end size calculation --- .idea/workspace.xml | 7 ++----- libpsn00b/libc/malloc.c | 2 ++ 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 585a8252..483702ee 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -21,10 +21,7 @@ - - - - + diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 2e1f09b2..e53a4d05 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -318,6 +318,7 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] cur->next: %p\n", cur->next); if (cur->next) { // In the middle, just unlink it + assert((cur->next)->prev == cur); printf("[Free] has next %p, setting cur->next->prev: %p to cur->prev: %p\n", (cur->next)->prev, cur->next, cur->prev); (cur->next)->prev = cur->prev; @@ -336,6 +337,7 @@ __attribute__((weak)) void free(void *ptr) { printf("[Free] heap_change: 0x%x\n", -(cur->size + sizeof(BlockHeader))); TrackHeapUsage(-(cur->size + sizeof(BlockHeader))); printf("[Free] cur->prev->next: %p\n", (cur->prev)->next); + assert((cur->prev)->next == cur); (cur->prev)->next = cur->next; printf("[Free] setting cur->prev->next to cur->next: %p\n", cur->next); } From 4be9c1e0833d2ecf6934d9cbb4ecb187b434d51d Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 15:54:18 +1100 Subject: [PATCH 050/128] Fixed free at end size calculation --- .idea/workspace.xml | 6 ++++-- libpsn00b/libc/malloc.c | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 483702ee..aa6a9798 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -21,7 +21,9 @@ - + + + diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index e53a4d05..fb6c5465 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -17,6 +17,7 @@ #include #include #include +#include #define ALIGN_SIZE 8 #define _align(x, n) (((x) + ((n)-1)) & ~((n)-1)) From 6571318fad481f3ec8c15281062d60272e005df4 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 16:05:09 +1100 Subject: [PATCH 051/128] Added logs --- .idea/workspace.xml | 6 ++---- libpsn00b/libc/malloc.c | 1 + 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index aa6a9798..d1200980 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -21,9 +21,7 @@ - - - + diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index fb6c5465..81131694 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -184,6 +184,7 @@ __attribute__((weak)) void *malloc(size_t size) { printf("[Malloc] next: %p\n", new->next); (new->next)->prev = new; + printf("[Malloc] (new->next)->prev: %p\n", (new->next)->prev); prev->next = new; printf("[Malloc] fit, prev->next: %p\n", prev->next); From a29dd9d3521a3f4190a61bf59d1b929bcd7ed7cb Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 16:24:33 +1100 Subject: [PATCH 052/128] Added logs --- .idea/workspace.xml | 7 +++++-- libpsn00b/libc/malloc.c | 2 +- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index d1200980..5d415d52 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -21,7 +21,10 @@ - + + + + diff --git a/libpsn00b/libc/malloc.c b/libpsn00b/libc/malloc.c index 81131694..f27bd6fe 100644 --- a/libpsn00b/libc/malloc.c +++ b/libpsn00b/libc/malloc.c @@ -322,7 +322,7 @@ __attribute__((weak)) void free(void *ptr) { // In the middle, just unlink it assert((cur->next)->prev == cur); printf("[Free] has next %p, setting cur->next->prev: %p to cur->prev: %p\n", - (cur->next)->prev, cur->next, cur->prev); + cur->next, (cur->next)->prev, cur->prev); (cur->next)->prev = cur->prev; } else { // At the end, shrink heap From 7eb71b7f65d82fc17237ab4a96df6eeac7855379 Mon Sep 17 00:00:00 2001 From: EngineersBox Date: Sat, 20 Jan 2024 17:45:04 +1100 Subject: [PATCH 053/128] Added logs --- .idea/workspace.xml | 2 +- libpsn00b/libc/malloc.c | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.idea/workspace.xml b/.idea/workspace.xml index 5d415d52..4bc7441d 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -80,7 +80,7 @@