Embedded HandbookApps
All sections › XII. Networks and DevOps for the engineer
STM32F407, STM32F411 · level intermediate · 18 min read
Open in the interactive handbook

109а. Version and build information inside the firmware: git hash, number, date, image CRC, a structure at a fixed address

In section 109.4 the git describe string becomes the firmware version, in 109.5 it is parsed on the board. Here is the next step: how this string, together with the build number, the commit hash, the time, the image length and CRC, ends up in one structure at an address known in advance; why make easily leaves yesterday's version in the image; why __DATE__ spoils reproducibility and how SOURCE_DATE_EPOCH fixes it; how to write the length and CRC after linking without losing the match between the ELF and the device; and how the GNU build ID links a device to its ELF when a crash is analysed.

The release pipeline — joining the bootloader and the application, the slot header in front of the image, the release log — is covered in section 201а. Here the same task is solved from inside the image: the structure carries its own length and CRC, and anyone who knows one address can check it.

The basis: a Cortex-M4 firmware of two C files built with arm-none-eabi-gcc 12.2.1 (stm-arm:1) with its own linker script; the version strings come from real git in a container (stm-ci:1), from a repository with a tag and three commits after it; the length and CRC are written by a Python script; the same check function as in the firmware is built with gcc 12.2.0 (stm-sys:1) and run over the finished .bin. Addresses are from nm and objdump, the build ID from readelf, the CRC is compared with zlib.crc32. The firmware was not run on silicon.

Terms used in the documentation

Original Meaning
build info block, image descriptor image descriptor: a structure with build information inside the firmware
post-link patching a patch after linking: fields known only from the finished image
write-if-changed write only if changed: the file is left alone if the content is the same
.note.gnu.build-id, NT_GNU_BUILD_ID the ELF note section with the build ID, note type 3
--build-id=sha1 an ld option: SHA-1 over the contents of the output file
-ffile-prefix-map replacing the build directory path in debug info and in macros
stale object an outdated object file: the source did not change, but the build inputs did

In plain words. A device must be able to answer "what are you?" without a computer with the sources. For this, at the start of the firmware, at an address everybody knows, a small card is placed: version, commit, build number, length and checksum. The bootloader, the debugger and a command over UART read the same card.


109а.1 What the device must know about itself

Five questions the firmware answers by itself:

Question Field Where it comes from
which version major.minor.patch git tag (109.4)
which build build pipeline counter (110)
which commit, edited or not commit, describe, flag git rev-parse, git describe --dirty
is the image intact image_len, image_crc script after linking
which ELF matches it build ID linker, --build-id

Build time is the least useful on this list: the commit and the number say more, and the time prevents getting identical images (109а.4). If it is needed, it is taken not from the build machine's clock but from SOURCE_DATE_EPOCH.


109а.2 Version number and build number

A semantic version is three numbers: the major one changes when compatibility breaks, the minor one when something new is added, the third for a fix. The rules and the release are covered in detail in 201а.1; what matters here is different: the version and the build number are different numbers. The version changes by a person's decision (a tag), the build number on every pipeline run. Two builds of the same tag with different numbers are normal: the second, for example, was built with a different compiler.

The experiment is real git in a container: a repository, the tag v1.2.0, three commits after it, then an unsaved edit. The command git describe --tags --dirty --match 'v[0-9]*' gave:

State String
on the tag v1.2.0
three commits after the tag v1.2.0-3-g71064c1
plus an unsaved edit v1.2.0-3-g71064c1-dirty

--match 'v[0-9]*' is needed so that an unrelated tag like test-board does not become a "version". The full commit hash is git rev-parse HEAD; its first 8 digits go into the firmware: 71064c15.

The build number in the experiment is 57, passed by make BUILD_NUMBER=57; in a pipeline it is the job number (section 110). A -dirty string may be accepted in a build but not released: such an image has no commit from which it can be repeated.


109а.3 From git into the build: a header or -D

Two ways to pass the version to the compiler.

-D options. The values go straight on the command line: -DFW_DESCRIBE='"v1.2.0-3-g71064c1"'. Simple, but make has no way to know that the string changed: the object file is newer than the source, and there will be no rebuild. Experiment: built with v1.2.0-3-g71064c1, then ran make with GIT_DESC=v1.3.0 — not a single file was recompiled, the .bin still has v1.2.0-3-g71064c1. The device will lie about its version until somebody does make clean.

A generated header. A script writes version.h, and make tracks it like any header. The trick is that the script runs every time, but the file is rewritten only if the content changed:

build_info.o: version.h
version.h: FORCE
    @python3 gen_version.py "$(GIT_DESC)" "$(GIT_HASH)" $(BUILD_NUMBER) > version.h.tmp
    @cmp -s version.h.tmp version.h || mv version.h.tmp version.h
    @rm -f version.h.tmp

FORCE is a target without rules, it is always "out of date", so the script runs on every make. And cmp leaves the old file with its old modification time if the new one is the same. The result:

What changed Recompiled
nothing (repeated make) nothing
build number 57 → 58 build_info.c
version string → v1.3.0 build_info.c, the image has v1.3.0
the same with -D nothing, the image has the old string

If version.h is written every time, without cmp, recompilation happens on every make, and if the header is included in the project's common header, everything is rebuilt. That is why version.h is included by one file — the one that holds the structure. The rest of the code reads the structure fields and knows nothing about version.h.

gen_version.py itself parses the string with the same rule as 109.5 and refuses an unclear one — a failed build is better than an image with version 0.0.0.

In CMake the same is done by add_custom_target(... ALL) with a script that is called every time and writes the file via configure_file or file(WRITE) after a comparison; a bare configure_file at the configuration stage runs once, and after a new commit the version stays old until the next configuration.


109а.4 Reproducible build: date, paths and SOURCE_DATE_EPOCH

Reproducible means that the same commit on another machine gives the same file byte for byte. Then the image hash in the log proves that the device has exactly this commit. Table 201а.4 measures this for the release build; here are three things that show up specifically with the build information structure.

__DATE__ and __TIME__. The string __DATE__ " " __TIME__ was built twice with a 2 s pause: the images contain Nov 29 2026 13:22:00 and Nov 29 2026 13:22:02, the SHA-256 differ. If SOURCE_DATE_EPOCH is set, gcc 12 takes "now" from it by itself: with SOURCE_DATE_EPOCH=1793786400 both builds gave Nov 4 2026 10:00:00 and identical images. This is the commit time, not the machine time: git log -1 --format=%ct. gen_version.py fills the time field with the same number.

A reference to the string. Without a reference from the code, the string with the date is thrown out by --gc-sections, even with the used attribute: it forbids removal by the compiler but not by the linker. In the experiment the first build with the date gave identical images — the string simply was not in them. A reference helped:

    uart_write(build_stamp);           /* без ссылки --gc-sections выбросит строку */

The directory path. The same sources in two directories without -ffile-prefix-map gave different .bin files, although the code is the same. The path is written into the ELF debug information, --build-id hashes the whole ELF, and the note with the hash sits in flash, that is, in the .bin. 24 bytes differed: 20 bytes of the ID and 4 bytes of the CRC that covers it. With -ffile-prefix-map=$(CURDIR)=. the two directories gave the same .bin and the same ID 160ee317ddd1cec6374d4a31887360c0e6e8df9b. If the note is not placed in flash, the path changes only the ELF (201а.4).


109а.5 A structure at a fixed address

The bootloader, the debugger and a PC program do not need ELF symbols if the structure's address is known in advance. A convenient place is right after the vector table: it is at the start of the image by the Cortex-M rule, and its size is known.

struct build_info {
    uint32_t magic;
    uint16_t layout;        /* версия самой структуры */
    uint16_t size;          /* sizeof(struct build_info) */
    uint8_t  major, minor, patch, flags;
    uint32_t build;         /* номер сборки из CI */
    uint32_t time;          /* SOURCE_DATE_EPOCH, а не время на машине сборки */
    uint32_t commit;        /* первые 8 шестнадцатеричных цифр коммита */
    char     describe[32];  /* git describe --tags --dirty */
    uint32_t image_len;     /* заполняет patch_image.py после компоновки */
    uint32_t image_crc;     /* CRC-32 образа; само поле считается нулями */
};

64 bytes, all fields naturally aligned, no holes. The layout is pinned by compile-time checks — if the size changes, the build stops:

_Static_assert(sizeof(struct build_info) == 64, "раскладка структуры");
_Static_assert(offsetof(struct build_info, image_crc) == 60, "поле CRC");

magic is the first check that "this is the right structure at all"; layout and size allow adding fields at the end: an old bootloader reads its own 64 bytes and makes no mistake. The instance is a constant in its own section:

__attribute__((section(".build_info"), used))
const struct build_info build_info = {
    .magic = BUILD_INFO_MAGIC, .layout = 1, .size = sizeof(struct build_info),
    .major = FW_MAJOR, .minor = FW_MINOR, .patch = FW_PATCH, .flags = FW_FLAGS,
    .build = FW_BUILD, .time = FW_TIME, .commit = FW_COMMIT,
    .describe = FW_DESCRIBE,
    .image_len = 0xFFFFFFFFu,   /* заглушки: незаплатанный образ не пройдёт проверку */
    .image_crc = 0xFFFFFFFFu,
};

The address is set by the linker script. KEEP prevents --gc-sections from throwing away sections nobody refers to — and nothing in the code refers to the vector table or to the structure:

    .text :
    {
        __image_start = .;
        KEEP(*(.isr_vector))
        . = 0x200;                    /* смещение сведений о сборке */
        KEEP(*(.build_info))
        *(.text*)
        *(.rodata*)
    } > FLASH

Inside an output section . = 0x200 is an offset from its start, that is, address 0x08000200. The F407 vector table is 98 words, 392 bytes, and fits into 0x200 with room to spare. The linker itself stops the build if there are more vectors: ld cannot "move the location counter backwards".

What came out according to nm and objdump:

Symbol or section Address Size
vectors 0x08000000 392 bytes
build_info 0x08000200 64 bytes
.text as a whole 0x08000000 1154 bytes
.note.gnu.build-id 0x08000484 36 bytes
.bin image 0x08000000 1192 bytes

On the left, the firmware image by address: from 0x08000000 the 392-byte vector table, empty up to 0x200, at 0x08000200 the 64-byte build information structure — the BLDI magic, version 1.2.0, build 57, time from SOURCE_DATE_EPOCH, commit, describe string, length 1192 and CRC-32, computed with the field itself as zeros; then code and constants, at 0x08000484 the 36-byte build-id note, the image ends at 0x080004a8; on the right, who reads the structure at the known address: the bootloader checks the CRC before the jump, the info command over UART prints the version line, a debugger over SWD reads x/16wx 0x08000200, the application checks itself at startup

The structure in the image, objdump -s at address 0x08000200:

 8000200 424c4449 01004000 01020000 39000000  BLDI..@.....9...
 8000210 2002eb6a 154c0671 76312e32 2e302d33   ..j.L.qv1.2.0-3
 8000220 2d673731 30363463 31000000 00000000  -g71064c1.......
 8000230 00000000 00000000 a8040000 b91c8e95  ................

BLDI is the magic, 0100 4000 is layout 1 and size 64, 01 02 00 is version 1.2.0, 39000000 is build 57, 2002eb6a is the time 1793786400, 154c0671 is the commit 71064c15, then the describe string, the length a8040000 = 1192 and the CRC b91c8e95.


109а.6 Length and CRC after linking

The compiler cannot know the image length and CRC: they depend on the whole image, including the structure itself. They are written after linking. Two decisions make this honest:

The script finds the field's address in the ELF from the section headers and writes there:

img = to_bin()
if struct.unpack_from("<I", img, OFF)[0] != MAGIC:
    sys.exit("patch_image: нет структуры по смещению 0x%x" % OFF)
struct.pack_into("<II", img, LEN_AT, len(img), 0)
crc = zlib.crc32(bytes(img)) & 0xFFFFFFFF
data = bytearray(open(elf, "rb").read())
struct.pack_into("<I", data, file_offset(data, BASE + LEN_AT), len(img))
struct.pack_into("<I", data, file_offset(data, BASE + CRC_AT), crc)

In the make rules it is the step between linking and the .bin:

fw.bin: fw.elf patch_image.py
    python3 patch_image.py fw.elf fw.bin

The result: len=1192 crc=0x958e1cb9. An independent check in Python — zlib.crc32 over the .bin with bytes 0x23c…0x23f zeroed — gave the same 0x958e1cb9. The CRC of the same image with the field filled in is a different number: treating the field as zeros is mandatory, and the same way in the script and in the firmware.

The linker computes the build ID before the patch, so it does not depend on the CRC — and is the same for two identical builds. And the CRC covers the note with the ID, so corruption of the ID in the device is also visible.


109а.7 The check at startup

The CRC-32 is the same as zlib's (polynomial 0xEDB88320, reflected), bitwise — without a table, 44 bytes of code:

uint32_t crc32_update(uint32_t crc, const uint8_t *p, uint32_t n)
{
    crc = ~crc;
    while (n--) {
        crc ^= *p++;
        for (int k = 0; k < 8; k++)
            crc = (crc >> 1) ^ (0xEDB88320u & -(crc & 1u));
    }
    return ~crc;
}

The check is in three pieces, the CRC field goes as zeros:

    if (bi->magic != BUILD_INFO_MAGIC || bi->size != sizeof *bi)
        return -1;                       /* структуры нет или чужая раскладка */
    if (bi->image_len > max_len || bi->image_len < at + 4)
        return -2;                       /* длина не заполнена или больше слота */
    uint32_t c = crc32_update(0, img, at);
    c = crc32_update(c, zero, 4);
    c = crc32_update(c, img + at + 4, bi->image_len - at - 4);
    return c == bi->image_crc ? 0 : -3;

The same function, built on the computer, was run over the finished .bin:

Image Result
as built 0
one bit in the code (offset 0x300) −3
one bit in the build ID −3
length and CRC still 0xFFFFFFFF, as before the patch −2
a 1024-byte slot with a 1192-byte image −2
magic erased −1

The 0xFFFFFFFF placeholder in image_len is not chosen by chance: an image that somebody forgot to pass through patch_image.py is cut off by the length check, not by an accidental CRC match. The function itself is 104 bytes of code, the whole computation over 1192 bytes runs once at startup. A bitwise CRC is slow, about eight steps per byte; for an image of hundreds of kilobytes — a nibble-wise computation with a 16-word table, as in 198щ.2.


109а.8 Who reads the structure

Everybody knows the address 0x08000200, and that is the main thing: ELF symbols are not needed.

The bootloader. Before jumping into the application it calls the same build_info_check with the slot start address and the slot size. On failure it stays in the bootloader and waits for a new image. The own bootloader of a production device (198щ) keeps the CRC in a separate header in front of the image, because the image is written there in parts; the structure inside the image complements the header — it can be read even from firmware flashed by a debugger, without a bootloader.

A UART command. The firmware answers "info" with one line:

int build_info_format(char *out, const struct build_info *bi)

On the finished image it gave:

fw 1.2.0+57 v1.2.0-3-g71064c1 len=1192 crc=958e1cb9

Without printf: its own put_dec and put_hex in a few lines, so as not to pull the library into the bootloader. The firmware prints the same line at startup, together with the result of the check:

    boot_status = build_info_check(__image_start, 512u * 1024u);
    build_info_format(line, &build_info);
    uart_write(line);
    uart_write(boot_status == 0 ? " ok\r\n" : " BAD\r\n");

A debugger over SWD. The address is known — reading 64 bytes is enough. In gdb it is x/16wx 0x08000200, in OpenOCD mdw 0x08000200 16, in STM32CubeProgrammer a memory read from the same address (section 35б). This works on a device where the firmware does not start at all: memory is readable even with the core halted.

Update from an app. The phone program (189а) compares the version of the incoming file with the version in the device. From the file it is read at the same offset 0x200 — no ELF parsing is needed.


109а.9 The GNU build ID and the crash dump

The option -Wl,--build-id=sha1 tells the linker to compute SHA-1 over the output file and put it into the note .note.gnu.build-id. In your own linker script the note must be placed explicitly, otherwise it becomes an orphan section and lands wherever it happens to:

    .note.gnu.build-id :
    {
        __build_id_start = .;
        KEEP(*(.note.gnu.build-id))
    } > FLASH

The note is 36 bytes: the name length, the ID length, type 3 (NT_GNU_BUILD_ID), the name GNU\0 and 20 bytes of hash. The firmware gets the hash like this:

const uint8_t *build_id_get(const uint8_t *note, uint32_t *len)
{
    const uint32_t *n = (const uint32_t *)note;
    if (n[2] != 3u)                      /* NT_GNU_BUILD_ID */
        return 0;
    *len = n[1];
    return note + 12 + ((n[0] + 3u) & ~3u);
}

readelf -n on the ELF showed 160ee317ddd1cec6374d4a31887360c0e6e8df9b; the same 20 bytes lie in the .bin at 0x08000484 + 16, and build_id_get returned them too.

Why it is needed when there is a commit hash: the commit says what it was built from, and the ID says what exactly came out, with this compiler and these options. A crash dump (35в) stores addresses; addr2line can decode them only with the ELF the firmware was made from. If the dump gives out the ID along with the addresses, the ELF is found unambiguously: the release archive stores the ELF under its ID, and readelf -n on a candidate must show the same number. A commit hash is not enough for this: from one commit, -O0 and -Os give different addresses.


109а.10 Version at startup and in the protocol

The firmware prints the version string as the first line after reset, before everything else: if the device hangs during initialisation, the log still shows what exactly hung. In a binary protocol (section 194 — frames with their own CRC) it is more convenient to send not the string but the 64 bytes of the structure themselves with one command: the layout is known, layout and size tell how to read new fields, and the PC program parses the same format as from the file. The "who are you" reply is worth keeping in the protocol from the first version and never changing its command number: it is the only command that any future client must understand.


109а.11 Pitfalls

Version via -D without dependencies. The new string did not rebuild the object, the old one stayed in the image. A header with write-if-changed or a full rebuild in the pipeline.

A version.h that is always written. Every make rebuilds the structure file, and if the header is included everywhere, the whole project.

__DATE__ in firmware. Two builds of the same commit are different files. Either remove it or use SOURCE_DATE_EPOCH from the commit time.

used instead of a reference. A string without a reference is thrown out by --gc-sections, and the check "the images matched" deceives: they simply do not contain the string.

The directory path in the note. With the note in flash, the directory path gets into the .bin through the ID: 24 bytes of difference. -ffile-prefix-map is mandatory.

A CRC over the field itself. The script and the firmware must treat the CRC field the same way — as zeros. Otherwise the CRC never matches, and if it matches by chance, that is a bug in the check.

A patch only in the .bin. An ELF without length and CRC is flashed by a debugger — and a device with the "right" firmware fails its own check.

A structure not at its address. Without KEEP it is thrown out by --gc-sections, without an explicit offset it moves when the vector table changes. Check with nm in the pipeline: build_info at 0x08000200.

-dirty in a release. The image has no commit; such an image must not be released (201а.6).


109а.12 Summary

Next: section 110 "CI/CD for firmware" — the same history, but the build and tests run by themselves, and the output is an image with the version from the tag.

Open in the interactive handbook