Add a (bad)free in userspace

This commit is contained in:
Mathieu Maret 2023-11-11 00:08:08 +01:00
parent 1120b40655
commit bee58d9642
2 changed files with 32 additions and 14 deletions

View File

@ -443,25 +443,28 @@ int vasprintf(char **strp, const char *fmt, va_list ap)
{
int n = 0;
size_t size = 0;
char *p = malloc(256);
char *p = malloc(256);
/* Determine required size */
n = vsnprintf(p, size, fmt, ap);
if (n < 0)
if (n < 0){
free(p);
return -1;
}
/* One extra byte for '\0' */
size = min(256U,(size_t)n + 1);
size = min(256U, (size_t)n + 1);
n = vsnprintf(p, size, fmt, ap);
if (n < 0) {
free(p);
return -1;
}
*strp = p;
*strp = p;
return size;
}
@ -571,23 +574,38 @@ void *brk(void *addr)
return (void *)syscall1(SYSCALL_ID_BRK, (unsigned int)addr);
}
static char *heapTop = 0;
static char *heapFree = 0;
static char *lastAlloc = 0;
void *malloc(size_t size)
{
void *heapTop = 0;
static void *free = 0;
if (heapTop == 0) {
heapTop = brk(0);
free = heapTop;
heapTop = heapFree = brk(0);
} else {
heapTop = brk(0);
}
if (free + size > heapTop) {
if (brk(heapTop + size))
if (heapFree + size + sizeof(size) > heapTop) {
if (brk(heapTop + size + sizeof(size)))
return NULL;
}
free += size;
return (free - size);
*((size_t *)heapFree) = size;
heapFree += sizeof(size);
lastAlloc = heapFree;
heapFree += size;
return lastAlloc;
}
void free(void *ptr)
{
void *size_addr = ((char *)ptr - sizeof(size_t));
size_t size = *(size_t *)size_addr;
if (heapFree - size == ptr) {
heapFree = size_addr;
}
//TODO ELSE
return;
}

View File

@ -28,7 +28,6 @@ int vsnprintf(char *str, size_t size, const char *format, va_list ap) __attribut
int vprintf(const char *format, va_list ap) __attribute__ ((__format__ (printf, 1, 0)));
int printf(const char *format, ...) __attribute__ ((__format__ (printf, 1, 2)));
// Could be used after malloc is available
int asprintf(char **strp, const char *fmt, ...) __attribute__ ((__format__ (printf, 2, 3)));
int vasprintf(char **strp, const char *fmt, va_list ap) __attribute__ ((__format__ (printf, 2, 0)));
@ -49,3 +48,4 @@ char getchar();
int readline(char *buf, int size);
void *brk(void *addr);
void *malloc(size_t size);
void free(void *ptr);