Files
my-os-project2/ulib/dlmalloc/dlmalloc_port.inc

93 lines
1.8 KiB
C++

// Config
#include <stddef.h>
#include <dlmalloc/malloc.h>
#include <uprintf.h>
#include <errors.h>
#include <sync/spinlock.h>
#include <string/string.h>
#include <sysdefs/mman.h>
#include <system/system.h>
#define USE_DL_PREFIX 1
#define LACKS_SYS_TYPES_H 1
#define NO_MALLOC_STATS 1
#define LACKS_ERRNO_H 1
#define LACKS_TIME_H 1
#define LACKS_STDLIB_H 1
#define LACKS_SYS_MMAN_H 1
#define LACKS_FCNTL_H 1
#define LACKS_UNISTD_H 1
#define LACKS_SYS_PARAM_H 1
#define LACKS_STRINGS_H 1
#define LACKS_SCHED_H 1
#define HAVE_MMAP 0
#define ABORT \
do { \
uprintf("dlmalloc: Aborting...\n"); \
} while(0)
#define MALLOC_FAILURE_ACTION
#define HAVE_MORECORE 1
#define USE_LOCKS 2
#define malloc_getpagesize 0x1000
#define EINVAL E_INVALIDARGUMENT
#define ENOMEM E_NOMEMORY
#define MLOCK_T SpinLock
int ACQUIRE_LOCK(SpinLock *sl) {
spinlock_acquire(sl);
return 0;
}
int RELEASE_LOCK(SpinLock *sl) {
spinlock_release(sl);
return 0;
}
int INITIAL_LOCK(SpinLock *sl) {
spinlock_release(sl);
return 0;
}
static MLOCK_T malloc_global_mutex = { 0 };
#define PAGE_SIZE 0x1000
static uint8_t *heap_start = (uint8_t *)NULL;
static uint8_t *heap_end = NULL;
static size_t _roundpage(size_t sz) {
return (sz + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
}
void *sbrk(ptrdiff_t inc) {
if (!heap_end) {
heap_end = heap_start;
}
if (inc == 0) {
return heap_end;
}
uint8_t *oldh = heap_end;
uint8_t *newh = heap_end + inc;
if (inc > 0) {
size_t allocsz = _roundpage((size_t)(newh - oldh));
uint8_t *maddr = NULL;
int32_t ret = mman_map(NULL, allocsz, MMAN_MAP_PF_RW, 0, &maddr);
if (ret != E_OK || maddr == NULL) {
return (void *)-1;
}
if (!heap_start) {
heap_start = maddr;
}
oldh = heap_end ? heap_end : maddr;
heap_end = oldh + allocsz;
} else {
heap_end = newh;
}
return oldh;
}