- // Simplest first fit approach.
-
- uint8_t* ptr = heap->start;
- // round to largest 4B aligned value
- // and space for header
- size = ROUNDUP(size, BOUNDARY) + WSIZE;
- while (ptr < (uint8_t*)heap->brk) {
- 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(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);
- }
-}
-
-void
-lx_free(void* ptr)
-{
- if (!ptr) {
- return;
- }
-
- uint8_t* chunk_ptr = (uint8_t*)ptr - WSIZE;
- uint32_t hdr = LW(chunk_ptr);
- size_t sz = CHUNK_S(hdr);
- uint8_t* next_hdr = chunk_ptr + sz;
-
- // make sure the ptr we are 'bout to free makes sense
- // the size trick comes from:
- // https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=1a1ac1d8f05b6f9bf295d7fdd0f12c2e4650a33c;hb=HEAD#l4437
- assert_msg(((uintptr_t)ptr < (uintptr_t)(-sz)) && !((uintptr_t)ptr & ~0x3),
- "free(): invalid pointer");
- assert_msg(sz > WSIZE && (sz & ~0x3),
- "free(): invalid size");
-
- SW(chunk_ptr, hdr & ~M_ALLOCATED);
- SW(FPTR(chunk_ptr, sz), hdr & ~M_ALLOCATED);
- SW(next_hdr, LW(next_hdr) | M_PREV_FREE);
-
- coalesce(chunk_ptr);
-}
-
-void*
-coalesce(uint8_t* chunk_ptr)
-{
- uint32_t hdr = LW(chunk_ptr);
- uint32_t pf = CHUNK_PF(hdr);
- uint32_t sz = CHUNK_S(hdr);
-
- uint32_t n_hdr = LW(chunk_ptr + sz);