+int
+lxsbrk(void* addr)
+{
+ return lxbrk(addr - current_heap_top) != NULL;
+}
+
+void*
+lxbrk(size_t size)
+{
+ if (size == 0) {
+ return NULL;
+ }
+
+ // plus WSIZE is the overhead for epilogue marker
+ size += WSIZE;
+ void* next = current_heap_top + ROUNDUP((uintptr_t)size, WSIZE);
+
+ if (next >= K_STACK_START) {
+ return NULL;
+ }
+
+ // Check the invariant
+ assert(size % BOUNDARY == 0)
+
+ uintptr_t heap_top_pg = PG_ALIGN(current_heap_top);
+ if (heap_top_pg != PG_ALIGN(next))
+ {
+ // if next do require new pages to be allocated
+ if (!vmm_alloc_pages(heap_top_pg + PG_SIZE, ROUNDUP(size, PG_SIZE), PG_PRESENT | PG_WRITE)) {
+ return NULL;
+ }
+
+ }
+
+ uintptr_t old = current_heap_top;
+ current_heap_top = next - WSIZE;
+ return old;
+}
+
+void*
+lx_grow_heap(size_t sz) {
+ uintptr_t start;
+
+ sz = ROUNDUP(sz, BOUNDARY);
+ if (!(start = lxbrk(sz))) {
+ return NULL;
+ }
+
+ uint32_t old_marker = *((uint32_t*)start);
+ uint32_t free_hdr = PACK(sz, CHUNK_PF(old_marker));
+ SW(start, free_hdr);
+ SW(FPTR(start, sz), free_hdr);
+ SW(NEXT_CHK(start), PACK(0, M_ALLOCATED | M_PREV_FREE));
+
+ return coalesce(start);
+}
+
+void*
+lx_malloc(size_t size)
+{
+ // Simplest first fit approach.
+
+ uint8_t* ptr = &__kernel_heap_start;
+ // round to largest 4B aligned value
+ // and space for header
+ size = ROUNDUP(size, BOUNDARY) + WSIZE;
+ while (ptr < current_heap_top) {
+ uint32_t header = *((uint32_t*)ptr);
+ size_t chunk_size = CHUNK_S(header);
+ if (chunk_size >= size && !CHUNK_A(header)) {
+ // found!
+ place_chunk(ptr, size);
+ return BPTR(ptr);
+ }
+ ptr += chunk_size;
+ }
+
+ // if heap is full (seems to be!), then allocate more space (if it's okay...)
+ if ((ptr = lx_grow_heap(size))) {
+ place_chunk(ptr, size);
+ return BPTR(ptr);
+ }
+
+ // Well, we are officially OOM!
+ return NULL;
+}
+
+void place_chunk(uint8_t* ptr, size_t size) {
+ uint32_t header = *((uint32_t*)ptr);
+ size_t chunk_size = CHUNK_S(header);
+ *((uint32_t*)ptr) = PACK(size, CHUNK_PF(header) | M_ALLOCATED);
+ uint8_t* n_hdrptr = (uint8_t*)(ptr + size);
+ uint32_t diff = chunk_size - size;
+ if (!diff) {
+ // if the current free block is fully occupied
+ uint32_t n_hdr = LW(n_hdrptr);
+ // notify the next block about our avaliability
+ SW(n_hdrptr, n_hdr & ~0x2);
+ } else {
+ // if there is remaining free space left
+ uint32_t remainder_hdr =
+ PACK(diff, M_NOT_ALLOCATED | M_PREV_ALLOCATED);
+ SW(n_hdrptr, remainder_hdr);
+ SW(FPTR(n_hdrptr, diff), remainder_hdr);
+
+ coalesce(n_hdrptr);
+ }