We are currently working on new rules for what content should and shouldn't be allowed on this website, and are looking for feedback! See Esolang:2026 topicality proposal to view and give feedback on the current draft.

Crawssembly/Heap Allocator

From Esolang
Jump to navigation Jump to search

The following is a dynamic memory allocator written in Crawssembly by User:Craw, forming part of the Crawssembly Standard Library (CSL).

The allocator implements a first-fit allocation algorithm, supporting variable-sized memory blocks, reuse of previously freed blocks and splitting of larger free blocks. It also checks the position of the stack pointer before extending the heap to prevent the two regions from overlapping.

The allocation algorithm is implemented using Crawssembly's primitive arithmetic, bitwise operations, conditional regions and memory device.

Implementation

Memory layout

The heap begins at memory address 0x10000 and grows towards higher memory addresses, while the stack grows towards lower memory addresses.

Each heap block consists of a single header word followed by a variable number of data words.

Lower addresses

0x10000
+------------------+
| Block header     |
+------------------+
| Data             |
| ...              |
+------------------+
| Block header     |
+------------------+
| Data             |
| ...              |
+------------------+
| Empty header (0) |
+------------------+
|                  |
| Unused memory    |
|                  |
+------------------+
| Stack            |
| ...              |
+------------------+

Higher addresses

The address of the next block is calculated using:

next address = current address + block size + 1

The additional word accounts for the block header.

Block headers

The size and allocation status of each block are encoded within a single integer.

The least significant bit indicates whether the block is free, while bits 1–20 contain the size of the block in memory words.

 Bit:  20                    1   0
       +---------------------+---+
       |     Block size      | F |
       +---------------------+---+

F = 0: Allocated
F = 1: Free

A header value of zero indicates the end of the heap.

The header is constructed using:

header = (size << 1) OR free flag

For example, an allocated block containing eight data words has a header value of 16, while a free block of the same size has a header value of 17.

Basic memory layout of the Crawssembly Stack & Heap
Basic memory layout of the Crawssembly Stack & Heap

Allocation algorithm

The allocator begins at address 0x10000 and traverses the heap sequentially, reading the header of each block.

For each block, the allocator:

  1. Extracts the block size and free flag.
  2. Determines whether the block is free.
  3. Determines whether the block is large enough to satisfy the requested allocation.
  4. Advances to the next block if the current block is unsuitable.

The first suitable free block is selected, making this a first-fit allocation algorithm.

Block splitting

If a suitable free block is larger than the requested allocation, it may be divided into two separate blocks.

Before allocation:

+--------+-----------------------------+
| Header |          Free data          |
+--------+-----------------------------+

After allocation:

+--------+-------------+--------+------+
| Header | Allocated   | Header | Free |
+--------+-------------+--------+------+

The first block is marked as allocated, while the remaining space is given a new header and marked as free.

The size of the remaining free block is calculated as:

remaining size = original size − requested size − 1

If exactly one unused word would remain, the allocated block is instead extended by one word. This avoids creating a free block containing a header but no usable data.

Heap extension

If no suitable free block is found, the allocator attempts to create a new block at the end of the heap.

Before doing so, it compares the address immediately following the proposed allocation with the stack pointer stored in red.

Allocation is permitted only if:

block address + requested size + 1 < stack pointer

If insufficient space remains between the heap and stack, the allocator returns an error.

Interface

The public allocation routine is provided by heap/alloc.craw, which validates the requested size before executing the internal allocation routine, heap/_alloc.craw.

Register Direction Purpose
r02 Input Requested allocation size in memory words
rec Output Address of the allocated block header
ree Output Error code
red Input Stack pointer

The allocator returns the following error codes:

Value Meaning
0 Successful allocation
4 Invalid allocation size or insufficient available memory

Source Code

The following is the combined source code. In the real CSL this code is split between the main code _alloc.craw and a thin size wrapper alloc.craw. This source code combines both.

; CSL: heap/alloc.craw			r02 = input	r06 = header
; Inputs: r02				r03 = address	r07 = flags
; Outputs: rec, ree			r04 = block size
; Scope: r01-r07, rec-red | 60000-60002	r05 = size

sav r02 r01				; ready size test

sav 4 ree				; assume bad size

ifg 60003				; size > 0

  sav 0 ree				; size is ok

  ; executestd heap/_alloc.craw		; main code

  ; CSL: heap/_alloc.craw			r02 = input	r06 = header
  ; Inputs: r02					r03 = address	r07 = flags
  ; Outputs: rec, ree				r04 = block size
  ; Scope: r01-r07, rec-red | 60000-60002	r05 = size

  rmv 60000				; free label

  sav 0 r01				; initialise registers
  sav 0 r03
  sav 0 r04
  sav 0 r05
  sav 0 r06
  sav 0 r07

  sav r02 r05				; preserve size

  sav 1 r01				; 0b0..1
  sav 16 r02				; shift amount
  cal shl r01 r02			; 0b0..10000000000000000  (0x10000)
  sav r01 r03				; save address

  60000					; block walk loop

    sav 0 r07				; reset flags

    io mem addr r03			; set active memory

    sav 0 r06				; clear last header

    io mem read r06			; extract header
    sav r06 r01				; ready header

    ifz 60001				; header is empty, end of heap

      cal add 2 r07			; set end flag to true
      sav r01 r07			; update flags

    rmv 60001				; end header empty check

    sav 127 r01				; 0b0..01111111
    sav 7 r02				; shift amount
    cal shl r01 r02			; 0b0..0111110000000
    cal add 127 r01			; 0b0..0111111111111
    cal shl r01 r02			; 0b0..01111111111110000000
    cal add 126 r01			; 0b0..01111111111111111110

    cal and r06 r01			; extract size-flag part
    sav 1 r02				; shift amount
    cal shr r01 r02			; remove 0 from flag
    sav r01 r04				; preserve block size

    cal and 1 r06			; extract free flag  

    ifg 60001				; is free

      cal not r04 rff			; negation 1st step
      cal add 1 r01			; negation 2nd step
      cal add r05 r01			; size - block

      ifg 60002				; size > block, not suitable

        cal add r03 r04			; increase address by block size
        cal add 1 r01			; include header word
        sav r01 r03			; update address

        jmp 60000			; continue loop

      rmv 60002				; end not suitable check

      cal add 1 r07			; skip flag true
      sav r01 r07			; update flags 
   
      sav r03 rec			; update heap pointer

      sav 1 r02				; shift amount
      cal shl r05 r02			; create proper size header 

      io mem write r01			; creates header

      cal add r03 r05			; add block size to address
      cal add 1 r01			; include header address
      sav r01 r03			; update address

      io mem addr r03			; set active address to new header

      cal not r05 rff			; negation (skip +1 for header)
      cal add r04 r01			; block - size

      ifg 60002				; leftover > 1

        sav 1 r02			; shift amount
        cal shl r01 r02			; newsize << 1
        cal add 1 r01			; set free flag to true

        io mem write r01		; create new header from old block

      rmv 60002				; end leftover > 1 branch

      cal not r05 rff			; negation (skip +1 for header)
      cal add r04 r01			; block - size
      sav r01 r02			; preserve value

      ifz 60002				; exactly one unused word remains

        cal not r05 rff			; -requested - 1
        cal add r03 r01			; return to allocated header
        io mem addr r01			; set active address

        sav 0 r01			; makes sure to clear stale data

        io mem read r01			; get allocated header

        cal add 2 r01			; increase encoded size by one word
        io mem write r01		; update header

      rmv 60002				; end overlap check

    rmv 60001				; end is free check

    sav r07 r01				; ready flags

    ifz 60001				; not at end

      cal add r03 r04			; increase address by block size
      cal add 1 r01			; include header word
      sav r01 r03			; update address

      jmp 60000				; continue loop

    rmv 60001				; end all flags = false check
  rmv 60000				; free label

  sav 0 ree				; assume proper allocation occured

  cal and 2 r07				; get end flag

  ifg 60000				; no block found

    cal not red rff			; negation 1st step
    cal add 1 r01			; negation 2nd step
    cal add r03 r01			; address - stack pointer
    cal add r05 r01			; new_address - 1 - stack pointer
    cal add 1 r01			; new_address - stack_pointer

    sav 4 ree				; assume no room

    ifl 60001				; st > hp => room on heap
 
      sav 0 ree				; room found for new block

      sav r03 rec			; update heap pointer

      sav 1 r02				; shift amount
      cal shl r05 r02			; size << 1

      io mem addr rec			; set new block address
      io mem write r01			; write allocated header to new block

    rmv 60001				; room check

  rmv 60000				; end no block found check

  sav 0 r01				; clear used registers
  sav 0 r02
  sav 0 r03
  sav 0 r04
  sav 0 r05
  sav 0 r06
  sav 0 r07

  ; end of _alloc.craw

rmv 60003				; end size > 0 check

sav 0 r01				; reset used registers
sav 0 r02