A simple allocator written in Rust that manages memory in fixed-size chunks.

Overview

Simple Chunk Allocator

A simple no_std allocator written in Rust that manages memory in fixed-size chunks/blocks. Useful for basic no_std binaries where you want to manage a heap of a few megabytes without complex features such as paging/page table management. Instead, this allocator gets a fixed/static memory region and allocates memory from there. This memory region can be contained inside the executable file that uses this allocator. See examples down below.

There probably exist better solutions for large-scale applications that have better performance by using a more complex algorithm. However, this is good for simple no_std binaries and hopefully also for educational purposes. It helped me to understand a lot about allocators.

TL;DR

  • no_std allocator with test coverage
  • uses static memory as backing storage (no paging/page table manipulations)
  • allocation strategy is a combination of next-fit and best-fit
  • reasonable fast with low code complexity
  • const compatibility (no runtime init() required)
  • efficient in scenarios where heap is a few dozens megabytes in size
  • user-friendly API

The inner and low-level ChunkAllocator can be used as #[global_allocator] with the synchronized wrapper type GlobalChunkAllocator. Both can be used with the allocator_api feature. The latter enables the usage in several types of the Rust standard library, such as Vec::new_in or BTreeMap::new_in. This is primarily interesting for testing but may also enable other interesting use-cases.

The focus is on const compatibility. The allocator and the backing memory can get initialized during compile time and need no runtime init() call or similar. This means that if the compiler accepts it then the allocation will also work during runtime. However, you can also create allocator objects during runtime.

The inner and low-level ChunkAllocator is a chunk allocator or also called fixed-size block allocator. It uses a mixture of the strategies next-fit and a best-fit. It tries to use the smallest gap for an allocation request to prevent fragmentation but this is no guarantee. Each allocation is a trade-off between a low allocation time and preventing fragmentation. The default chunk size is 256 bytes but this can be changed as compile time const generic. Having a fixed-size block allocator enables an easy bookkeeping algorithm through a bitmap but has as consequence that small allocations, such as 64 byte will take at least one chunk/block of the chosen block size.

This project originates from my Diplom thesis project. Since I originally had lots of struggles to create this (my first ever allocator), I outsourced it for better testability and to share my knowledge and findings with others in the hope that someone can learn from it in any way.

Minimal Code Example

#![feature(const_mut_refs)]
#![feature(allocator_api)]

use simple_chunk_allocator::{heap, heap_bitmap, GlobalChunkAllocator, PageAligned};

// The macros help to get a correctly sized arrays types.
// I page-align them for better caching and to improve the availability of
// page-aligned addresses.

/// Backing storage for heap (1Mib). (read+write) static memory in final executable.
///
/// heap!: first argument is chunk amount, second argument is size of each chunk.
///        If no arguments are provided it falls back to defaults.
///        Example: `heap!(chunks=16, chunksize=256)`.
static mut HEAP: PageAligned<[u8; 1048576]> = heap!();
/// Backing storage for heap bookkeeping bitmap. (read+write) static memory in final executable.
///
/// heap_bitmap!: first argument is amount of chunks.
///               If no argument is provided it falls back to a default.
///               Example: `heap_bitmap!(chunks=16)`.
static mut HEAP_BITMAP: PageAligned<[u8; 512]> = heap_bitmap!();

// please make sure that the backing memory is at least CHUNK_SIZE aligned; better page-aligned
#[global_allocator]
static ALLOCATOR: GlobalChunkAllocator =
    unsafe { GlobalChunkAllocator::new(HEAP.deref_mut_const(), HEAP_BITMAP.deref_mut_const()) };

fn main() {
    // at this point, the allocator already got used a bit by the Rust runtime that executes
    // before main() gets called. This is not the case if a `no_std` binary gets produced.
    let old_usage = ALLOCATOR.usage();
    let mut vec = Vec::new();
    vec.push(1);
    vec.push(2);
    vec.push(3);
    assert!(ALLOCATOR.usage() > old_usage);

    // use "allocator_api"-feature. You can use this if "ALLOCATOR" is not registered as
    // the global allocator. Otherwise, it is already the default.
    let _boxed = Box::new_in([1, 2, 3], ALLOCATOR.allocator_api_glue());
}

Another Code Example (Free Standing Linux Binary)

This is an excerpt. The code can be found in the GitHub repository in freestanding-linux-example.

static mut HEAP: PageAligned<[u8; 256]> = heap!(chunks = 16, chunksize = 16);
static mut HEAP_BITMAP: PageAligned<[u8; 2]> = heap_bitmap!(chunks = 16);

// please make sure that the backing memory is at least CHUNK_SIZE aligned; better page-aligned
#[global_allocator]
static ALLOCATOR: GlobalChunkAllocator<16> =
    unsafe { GlobalChunkAllocator::<16>::new(HEAP.deref_mut_const(), HEAP_BITMAP.deref_mut_const()) };

/// Referenced as entry by linker argument. Entry into the code.
#[no_mangle]
fn start() -> ! {
    write!(StdoutWriter, "Hello :)\n").unwrap();
    let mut vec = Vec::new();
    (0..10).for_each(|x| vec.push(x));
    write!(StdoutWriter, "vec: {:#?}\n", vec).unwrap();
    exit();
}

MSRV

This crate only builds with the nightly version of Rust because it uses many nightly-only features. I developed it with version 1.61.0-nightly (2022-03-05). Older nightly versions might work. So far there is no stable Rust compiler version that compiles this.

Performance

The default CHUNK_SIZE is 256 bytes. It is a tradeoff between performance and efficient memory usage.

I executed my example bench in release mode on an Intel i7-1165G7 CPU and a heap of 160MB to get the results listed below. I used RUSTFLAGS="-C target-cpu=native" cargo run --release --example bench to excute the benchmark with maximum performance. The benchmark simulates a heavy usage of the heap in a single-threaded program with many random allocations and deallocations. The benchmark stops when the heap is at 100%. The allocations vary in their alignment. The table below shows the results of this benchmark as number of clock cycles.

Chunk Size # Chunks # allocations # deallocations median average min max
128 1310720 68148 47915 955 1001 126 57989
256 [DEFAULT] 655360 71842 51744 592 619 121 53578
512 327680 66672 46858 373 401 111 54403

The results vary slightly because each run gets influenced by some randomness. One can see that the performance gets slower with a growing number of chunks. Increasing the chunk size reduces the size of the bookkeeping bitmap which accelerates the lookup. However, a smaller chunk size occupies less heap when only very small allocations are required.

Note that performance is better than listed above when the heap is used less frequently and does not run full.

You might also like...
A simple menu to keep all your most used one-liners and scripts in one place
A simple menu to keep all your most used one-liners and scripts in one place

Dama Desktop Agnostic Menu Aggregate This program aims to be a hackable, easy to use menu that can be paired to lightweight window managers in order t

A simple scanner that loops through ips and checks if a minecraft server is running on port 25565

scanolotl Scanolotl is a simple scanner that loops through ips and checks if a minecraft server is running on port 25565. Scanolotl can also preform a

A simple port sniffer(scanner) implementation with 🦀

A simple port sniffer(scanner) implementation with 🦀 Install from crates.io crago install ports-sniffer From aur: yay -S ports-sniffer Arguments Argu

A simple command line tool which quickly audits the Disallow entries of a site's robots.txt.

Domo Arigato A simple command line tool which quickly audits the Disallow entries of a site's robots.txt. Disallow entries can be used to stop search

An esoteric language/compiler written with Rust and Rust LLVM bindings

MeidoLang (メイドラング) A not so useful and esoteric language. The goal of this project was to contain some quirky or novel syntax in a stack-style program

link is a command and control framework written in rust
link is a command and control framework written in rust

link link is a command and control framework written in rust. Currently in alpha. Table of Contents Introduction Features Feedback Build Process Ackno

Multi-threaded Padding Oracle attacks against any service. Written in Rust.
Multi-threaded Padding Oracle attacks against any service. Written in Rust.

rustpad is a multi-threaded successor to the classic padbuster, written in Rust. It abuses a Padding Oracle vulnerability to decrypt any cypher text or encrypt arbitrary plain text without knowing the encryption key!

OpenSK is an open-source implementation for security keys written in Rust that supports both FIDO U2F and FIDO2 standards.

OpenSK This repository contains a Rust implementation of a FIDO2 authenticator. We developed OpenSK as a Tock OS application. We intend to bring a ful

Unofficial Bitwarden compatible server written in Rust, formerly known as bitwarden_rs

Alternative implementation of the Bitwarden server API written in Rust and compatible with upstream Bitwarden clients*, perfect for self-hosted deploy

Releases(v0.1.5)
  • v0.1.5(Nov 27, 2022)

    What's Changed

    • Fast realloc by @phip1611 in https://github.com/phip1611/simple-chunk-allocator/pull/2
    • comparison with linked-list-allocator by @phip1611 in https://github.com/phip1611/simple-chunk-allocator/pull/3

    Full Changelog: https://github.com/phip1611/simple-chunk-allocator/compare/v0.1.3...v0.1.5

    Source code(tar.gz)
    Source code(zip)
Owner
Philipp Schuster
Hello, I'm Philipp. I'm studying computer science at TU Dresden and I love coding. I'm especially interested in operating systems and low-level code.
Philipp Schuster
Memory hacking library for windows.

Memory hacking library for windows.

sy1ntexx 40 Jan 3, 2023
Using fibers to run in-memory code in a different and stealthy way.

Description A fiber is a unit of execution that must be manually scheduled by the application rather than rely on the priority-based scheduling mechan

Kurosh Dabbagh Escalante 121 Apr 20, 2023
A simple password manager written in Rust

ripasso A simple password manager written in Rust. The root crate ripasso is a library for accessing and decrypting passwords stored in pass format (G

Joakim Lundborg 548 Dec 26, 2022
A fast, simple, recursive content discovery tool written in Rust.

A simple, fast, recursive content discovery tool written in Rust ?? Releases ✨ Example Usage ✨ Contributing ✨ Documentation ?? ?? What the heck is a f

epi 3.6k Dec 30, 2022
simple multi-threaded port scanner written in rust

knockson simple multi-threaded port scanner written in rust Install Using AUR https://aur.archlinux.org/packages/knockson-bin/ yay -Syu knockson-bin M

Josh Münte 4 Oct 5, 2022
Simple prepender virus written in Rust

Linux.Fe2O3 This is a POC ELF prepender written in Rust. I like writting prependers on languages that I'm learning and find interesting. As for the na

Guilherme Thomazi Bonicontro 91 Dec 9, 2022
subscout is a simple, nimble subdomain enumeration tool written in Rust language

subscout is a simple, nimble subdomain enumeration tool written in Rust language. It is designed to help bug bounty hunters, security professionals and penetration testers discover subdomains of a given target domain.

Dom Sec 5 Apr 5, 2023
A simple port scanner built using rust-lang

A simple port scanner built using rust-lang

Krisna Pranav 1 Nov 6, 2021
Simple verification of Rust programs via functional purification in Lean 2(!)

electrolysis About A tool for formally verifying Rust programs by transpiling them into definitions in the Lean theorem prover. Masters thesis: Simple

Sebastian Ullrich 300 Dec 11, 2022
A simple rust library for working with ZIP archives

rust-zip A simple rust library to read and write Zip archives, which is also my pet project for learning Rust. At the moment you can list the files in

Jorge Gorbe Moya 11 Aug 6, 2022