[Mammoth] Write a custom buddy allocator to replace libc malloc.
This commit is contained in:
parent
d44be91099
commit
cbeb736e8c
5 changed files with 161 additions and 56 deletions
|
|
@ -1,6 +1,5 @@
|
|||
|
||||
add_library(c STATIC
|
||||
src/malloc.cpp
|
||||
src/string.cpp
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
#pragma once
|
||||
|
||||
#include "stddef.h"
|
||||
|
||||
void* malloc(size_t size);
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
#include <zcall.h>
|
||||
#include <zglobal.h>
|
||||
|
||||
#include "stdlib.h"
|
||||
|
||||
namespace {
|
||||
class NaiveAllocator {
|
||||
public:
|
||||
constexpr static uint64_t kSize = 0x10000;
|
||||
NaiveAllocator() {}
|
||||
bool is_init() { return next_addr_ != 0; }
|
||||
void Init() {
|
||||
uint64_t vmmo_cap;
|
||||
uint64_t err = ZMemoryObjectCreate(kSize, &vmmo_cap);
|
||||
if (err != 0) {
|
||||
(void)ZProcessExit(err);
|
||||
}
|
||||
err = ZAddressSpaceMap(gSelfVmasCap, 0, vmmo_cap, 0, &next_addr_);
|
||||
max_addr_ = next_addr_ + kSize;
|
||||
}
|
||||
|
||||
void* Allocate(size_t size) {
|
||||
uint64_t addr = next_addr_;
|
||||
next_addr_ += size;
|
||||
if (next_addr_ >= max_addr_) {
|
||||
(void)ZProcessExit(0xBEEF);
|
||||
return 0;
|
||||
}
|
||||
return reinterpret_cast<void*>(addr);
|
||||
}
|
||||
|
||||
private:
|
||||
uint64_t next_addr_ = 0;
|
||||
uint64_t max_addr_ = 0;
|
||||
};
|
||||
|
||||
NaiveAllocator gAlloc;
|
||||
|
||||
} // namespace
|
||||
|
||||
void* malloc(size_t size) {
|
||||
if (!gAlloc.is_init()) {
|
||||
gAlloc.Init();
|
||||
}
|
||||
return gAlloc.Allocate(size);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue