UP | HOME

Readme for utility-section-rs

Store general data on bare metal

Table of Contents

utility-section-rs defines a library crate utility-section for managing a collection of strings and blobs in contiguous flash pages in the context of bare metal embedded applications, coordinating its use, and a Cargo extension cargo-utility-section that creates such collections. The initial motivation was convenient managment of key/value secrets in code hosted and built on publicly visible infrastructure (Sourcehub, Github, etc.) but the scheme is intended to be extensible to other use cases. In particular it supports a blob store, useful for holding firmware blobs (like those required to support cyw43 radio modules) outside of executables, saving device space for DFU arrangements and compile/transfer time during development.

The utility-section data is intended to be a fixed address hard-coded into the consuming application, often defined in the linker script and relayed into the generated app binary. This same address might serve to identify a subsequent section of fixed RAM/ROM storage; the utility-section API provides ways of establishing and accessing this following data (by parsing the utility section and providing a raw pointer past its end, with a specified alignment).

Source code is in a SourceHut Git repo. There's also a bug tracker and a mailing list.

1. Why a from-scratch implementation?

Google's protobuf has become the canonical way to do things like this (space-efficient encoding of structured data). Alignment was troublesome though: I want the option of specifying that blobs land on specific boundaries so they can be used in place, though my immediate need didn't require this. I didn't find a way to add arbitrary padding to a protobuf encoding, the more one that adapted to the alignment of the encoding itself.

Likely a more exhaustive search than I did would turn up other canned approaches, but at this point I was intrigued with variable-length uint encoding and just started rolling. It didn't take all that long (cough, cough).

2. bit format

Here's sorta-BNF for utility-section bit coding:

UTILITY_SECTION: STRINGS BLOBS
HINT: u8+ /* 0-127 in 7 LSBs; else ersatz Huffman-esque >127 */
STRINGS: STRING*
STRING: STRING_LEN STRING_BYTES
STRING_LENGTH: HINT
STRING_BYTES: u8{STRING_LENGTH}
BLOBS: BLOB*
BLOB: BLOB_LENGTH BLOB_ID BLOB_ALIGNMENT BLOB_PADDING BLOB_BYTES
BLOB_LENGTH: HINT
BLOB_ID: HINT
BLOB_ALIGNMENT: HINT  /* as a power of 2, so 0 for arbitrary align */
BLOB_PADDING u8*  /* '>' as needed to _ALIGNMENT */
BLOB_BYTES: u8{BLOB_LENGTH}

HINT values above are ersatz-Huffman-coded unsigned integers. Values in the range 0..=127 are given in a single byte - the MSB is zero. Otherwise the seven LSBs are the MSBs of a larger value, whose lower bits are given in following bytes recursively. The target platform's usize maximum value is currently an upper bound on HINT values, so for a 32-bit platform the maximum HINT value is 2^28-1 (0x0fff_ffff_ffff_ffff, decimal 268,435,455).

Since dereferencing a raw pointer in Rust requires an unsafe{} block, constructing a safe API for string and blob retrieval in a no-heap context requires the app to provide a [u8;N] buffer large enough to hold the largest item (key, value or full string or blob depending on the API endpoint). These limits are established outside the context of the utility-section system, and enforced only by None responses to Option<> return values. API functions detailing STRING and BLOB items in terms of raw pointer offsets are also provided.

2.1. Strings

Key/value pairs are conventionally coded here like environment variables, with ''= separating key from value, but entries can be any arbitrary-length strings of bits whose length is a multiple of eight. When accessed through the utility-section key/value API routines the key portion must decode as valid UTF-8; the value portion (and the entire string, when using the buffer API) can be an arbitrary bit string. Each STRING entry in storage is a HINT string length followed by the string itself. Subsequent string items follow immediately after the last byte of their predecessor, with no padding. A zero-length item (single byte 0x00) ends the collection of strings.

2.2. Blobs

Following in storage the collection of strings (or the mandatory zero byte that marks the entire content of an empty collection of strings) is a sequence of blobs, each with an identifying integer given as a HINT value. A BLOB_LENGTH of zero (0u8) marks the end of the blobs collection. BLOB_ID, BLOB_ALIGNMENT and BLOB_BYTES are not present for a zero-length blob, which is therefore always one byte in length (this BLOB_LENGTH value). Padding is added between the BLOB_ALIGNMENT specifier and the first blob byte.

2.3. Following data

A single API function accepts an alignment value and returns the lowest-valued raw pointer past the end of all strings and blobs that meets the alignment specified.

2.4. Visualizing UTILITY_SECTION

Here's a concrete example, which assumes the address of its first byte is aligned to eight bytes. Note the alignment value 0x03 means "align to an even 2^3 boundary", not "add three bytes of padding", potentially confusing here:

0x04 First string is 4 bytes in length
"AP=X" These are the four bytes of the string
0x03 Second string is 3 bytes in length
"P=Y" Three bytes of 2nd string
0x00 Third string, len zero, ends first table
0x07 First blob is of length 7 bytes
0x00 First blob identifier is zero
0x03 First blob is aligned to an 8-byte boundary (2^3)
">>>DEADBEE" Padding followed by the eight blob bytes
0x00 Second blob, len zero, ends second table.

3. Parsing interface

// Find access point name and password as AP and PW in first table
// Addr comes from the linker script
const MAX_PACKED = 64usize;
let u = UtilitySection<MAX_PACKED>::new(addr);
let mut ap: &str;
let mut pw: [u8; MAX_PACKED];
while let Some((len, buf)) in u.next_string() {
    if let Some(i) = &buf[..].position(|b| b == b'=') {
        match &buf[..i].to_str() {
            "AP" => { ap = &buf[i+1..].into().expect("UTF-8"); },
            "P" => { memcpy(&pw, &buf[i+1..].as_ptr(), len - 3); },
            _ => { panic!("Unexpected key {:?}", &buf[..i]); },
        }
    } else {
        panic!("Unexpected non-KV string");
    }
}
while let Some((blob_len: usize, blob_offset: *u8)) = u.next_blob() {
    // do something. Note dereferencing blob_offset requires unsafe{}.
}

4. Generating utility

cargo utility-section reads memory.x to find the offset of the UTILITY section, and places values and file contents given on its command line into an ELF file encoding these items as described here, to be loaded at the proper section address.

Usage:

cargo utility-section [OPTIONS]

OPTIONS:

-s STRING Include the string in the output.
-b ALIGN FILENAME Include the file contents in the output, aligned.
-o FILENAME Output file to write, '.elf' if unspecified

Arrange shell escape options to specify STRING accurately.

ALIGN is a power of 2 alignment boundary. To align to an 8-byte boundary, specify 3. To accept any alignment, specify 0.

Date: 2026-02-16 Mon 00:00

Author: Steve Work <steve@renlabs.com>

Created: 2026-12-05 Sat 07:04

Validate