elf_tools 2.01
==============

A small collection of command-line utilities for relocatable ELF object
files and ar(1) archives.

Version 2.01 ships seven programs:

    elfrenamesym 1.02   Copy a .o (or .a member) while renaming specified
                        symbols.  Useful for symbol shimming, link-time
                        interposition, wrapper-style instrumentation, and
                        resolving multiple-definition conflicts.
                        (Uses libelf.)

    elflintsym 1.00     Lint one or more .o files or archives against a
                        list of POSIX regex patterns.  Useful as a CI gate
                        for forbidden symbols (gets, system, strcpy, ...)
                        or as a whitelist to enforce an export namespace.
                        (Uses libelf.)

    elfbundle 1.00      Combine several .o files (and/or .a archives) into
                        a single .o via 'ld -r', then seal the internal
                        symbols: every defined global not named in an
                        export whitelist is localized (or hidden with
                        --hidden), so a library can be vendored into
                        another program without symbol collisions.  -p
                        namespaces the exports with a prefix.
                        (Uses libelf; shells out to ld -r.)

    bin2obj 1.4         Convert an arbitrary binary file into a linkable
                        ELF .o that exports <prefix>_start, <prefix>_end,
                        and <prefix>_size global symbols.  With -h, also
                        emits a matching C header.  With -z, appends a
                        trailing NUL so <prefix>_start is a C string -
                        ideal for embedded SQL, shaders, configs, and
                        other text assets.  Useful for embedding PNGs,
                        TLS certificates, firmware blobs, etc., at link
                        time without runtime file I/O.
                        (Uses only libc and <elf.h>.)

    data2obj 1.05       Compile a data description into a linkable ELF .o.
                        Where bin2obj embeds an existing file verbatim,
                        data2obj builds the bytes of one or more sections
                        from a small C-like language with typed
                        declarations, structs, arrays, expressions,
                        control flow, and macros - and, crucially, with
                        references to symbols it does not define, which
                        become ELF relocations for ld to resolve.  That
                        makes it the tool for dispatch tables, pointer
                        tables, and headers whose fields are computed
                        from the layout of the data behind them.  With
                        -h it emits a matching typed C header (or, with
                        --assert-only, one that verifies a C type the
                        description did not define), with -l a
                        byte-level listing, and with -M a make(1)
                        dependency rule.  New in 1.04.
                        (Uses only libc and <elf.h>.)

    elf2asm 1.00        Turn a relocatable object or an archive (x86-64,
                        AArch64, RISC-V 64) back into assembly that
                        reassembles, with GNU as or with clang, into an
                        equivalent object -- for rebuilding, patching or
                        porting code whose source is lost.  Every output
                        file is verified by reassembling it with each
                        assembler installed and comparing the result;
                        what does not come back identical is re-emitted
                        as raw bytes until it does.  Alongside the
                        assembly it writes a Makefile that rebuilds the
                        object or archive, a C header recovered from the
                        DWARF (prototypes, types, and _Static_assert
                        layout checks), whatever original source files
                        are embedded in the object or can be found on
                        disk (checked against the DWARF 5 MD5), and a
                        MANIFEST.  -c rebuilds .cfi directives, -l .loc
                        directives.  New in 2.00.
                        (Uses Capstone and zlib.)

    elfcmp 1.00         Report whether two objects, or two archives, are
                        equivalent: the same sections, contents, symbols,
                        relocations and groups, ignoring what assemblers
                        choose for themselves (table order, mapping
                        symbols, .L temporaries).  The oracle elf2asm is
                        tested against, and a quick way to show that a
                        rebuilt object is a drop-in replacement.  New in
                        2.00.  (Uses zlib.)

New in 2.01
-----------
    data2obj 1.05.  A bug fix and the symbol and section features it
    lacked:

    - .init_array, .fini_array and .preinit_array are now emitted with
      their own section types (SHT_INIT_ARRAY and kin), aligned to a
      pointer.  Before, they took the default alignment of 16, so a
      single 8-byte constructor entry was followed by a zero slot in the
      linked array and the program crashed calling it at startup.  A
      ragged array is now an error.

    - `weak extern name;' declares an optional reference that links to
      zero when nothing defines it.  extern also takes a visibility.

    - `protected' and `internal' join `hidden' as visibilities.

    - `function' marks a label, item or extern STT_FUNC.

    - `retain = true;' sets SHF_GNU_RETAIN, so a section nothing refers
      to (a build stamp, a licence string) survives --gc-sections.

New in 2.00
-----------
    elf2asm and elfcmp, described above.  The two programs share a
    reader that does not use libelf, so they behave identically on Linux
    and FreeBSD and need no libelf at all; elf2asm decodes x86-64 and
    AArch64 with Capstone and RISC-V with its own decoder, because the
    Capstone 4 that Ubuntu 24.04 packages has no RISC-V support.

    elf2asm reproduces every member of libgcc.a for all three
    architectures under both GNU as and clang, with all but 19 of
    120,272 x86-64 instructions and every AArch64 and RISC-V instruction
    decoded, and every one of the 1,432 members of FreeBSD 15.1's own
    libc.a under clang; the rebuilt libc.a is equivalent to the system's.
    See the manual's performance chapter for the figures.

    The Makefile gains `dist' (roll the release tarball) and `manual'
    targets, and builds elf2asm only when Capstone is installed, so the
    other six programs still build without it.

New in 1.08
-----------
    A section's flags now follow its name.  Until now every section was
    emitted SHF_ALLOC and nothing else, so an object could contain a
    section called .data that was not writable and a .text that was not
    executable -- and 1.07's DT_TEXTREL warning made that visible by
    complaining about a section literally named .data and advising the
    author to move it somewhere writable.  .text/.init/.fini are now AX,
    .data/.bss/.init_array and friends WA, .comment and .debug* carry no
    flags, and everything else is A as before.  An explicit write, alloc
    or exec attribute still wins in both directions; only the flags
    follow the name, never the section type, so nobits stays something a
    description asks for.

    data2obj takes -Werror (also spelled --warnings-are-errors).  The
    DT_TEXTREL warning is the kind a project cleans up once and then
    wants held, and -q was the only knob, pointing the wrong way.  Every
    warning is still listed -- a run that is going to fail should say
    everything that is wrong with it -- but no output is written at all,
    so a later make cannot pick up a stale object.  -Werror overrides -q.

    data2obj diagnoses the unnamed-value form.  `node { 1 };' is the
    shape a reader arrives at from C; the value form takes an `=', and
    the parser has just read the type word, so it can say so instead of
    reporting that an expression was expected.

New in 1.07
-----------
    data2obj warns when an absolute relocation lands in a section the
    loader will map read-only.  A pointer table in .rodata links and
    runs, but it forces DT_TEXTREL into every position-independent
    executable that touches it, and until now the only complaint came
    from ld, long after the fact and about a different-sounding problem.
    data2obj now says it at the line that wrote the field, and names the
    fix.  A rel32 table in .rodata is deliberately not warned about: ld
    resolves it at static link time and nothing is left to relocate, so
    it is the better layout rather than the same mistake.

    data2obj --assert-only generates a header that checks a C type
    instead of defining one.  A description that lays out a table for a
    struct the program already declares cannot declare it a second time,
    which until now put the -h header out of reach in exactly the case
    that most needs it -- because a description guarding itself with
    sizeof() alone is not guarded at all.  Transpose two pointer fields
    and the size does not move; the per-field offset assertions catch it
    at the point of inclusion.  --assert-include=HEADER pulls in the
    caller's own header so the generated file stands on its own.

    data2obj structs may be declared `: natural', which lays them out by
    the C rules instead of packing them.  Packed is still the default and
    still the right one for a tool whose subject is byte layout, but when
    the target is an existing C ABI it means hand-padding every member,
    and every pad() is a chance to be quietly wrong.  `: natural' states
    the members and lets the rules do the rest; -h then emits the typedef
    unpacked, with the same assertions to prove the two sides agree.

    data2obj accepts a name bound to a string wherever it accepts a
    string literal, so `const S = "be"; char who[] = S;' works and, more
    to the point, a repeated variable-length record can be factored into
    a macro -- which is exactly where the old literal-only rule bit, and
    the only place it could not be worked around.

    data2obj tells a label from an array.  `k_history: ptr[] = { ... }'
    is a label followed by an anonymous array, and countof() on it used
    to report that the name was not a data item -- true, and a minute's
    work to see that the fix is to write `ptr k_history[] = { ... }'.
    The tool knows which case it is looking at, so it says so.

New in 1.06
-----------
    data2obj emits for six targets, not just x86: --march=x86-64 (the
    default), i386, aarch64, riscv64, riscv32, arm.  A `target' statement
    in the description names them too.  The machine number, pointer
    width and relocation numbers follow the target; the addend's home
    does as well, so riscv32 is ELF32 with RELA while arm is ELF32 with
    REL.  A reference in a field a psABI cannot relocate is refused by
    name rather than emitted as a number ld would reject.

    data2obj and bin2obj produce reproducible output.  Both honour
    SOURCE_DATE_EPOCH, both take --no-timestamp to drop the .comment
    creation stamp entirely, and data2obj takes --build-epoch=N.  Two
    builds of one input now match byte for byte, which build caches and
    distribution rebuild checks both depend on.

    data2obj gained crc32() and sum() over a range of emitted bytes, so
    a header can describe its payload's integrity and not merely its
    length; and build_epoch(), build_date() and build_time(), which read
    the pinned epoch so an image can carry a build stamp and still
    rebuild identically.

    data2obj gained the f16 and bf16 element types for weight and
    coefficient tables, rounding half to even as hardware does.

    data2obj's -h header now asserts the offset of every named struct
    field, not only the struct's size: a struct whose fields were
    reordered without changing the total is exactly what a size check
    misses.

    tests/run_all.sh builds its own fixtures, so the suite runs from a
    fresh unpack instead of failing on missing inputs.

The three libelf tools (elfrenamesym, elflintsym, elfbundle) handle
32-bit and 64-bit ELF transparently through libelf's gelf_* API.  bin2obj
does so through parallel write_elf32 and write_elf64 paths; data2obj
through a single writer parameterised by class.

Targets Linux and FreeBSD on x86-64 (and any other little-endian platform
supported by libelf; bin2obj and data2obj are little-endian-only at
present and refuse to build with a _Static_assert on big-endian hosts).
elf2asm and elfcmp read x86-64, AArch64 and RISC-V 64 objects on any of
those hosts; elf2asm verifies with whichever of GNU as and clang can
assemble for the object's target.

Files
-----
    elfrenamesym.c             elfrenamesym source
    elflintsym.c               elflintsym source
    elfbundle.c                elfbundle source
    bin2obj.c                  bin2obj source
    data2obj.c                 data2obj source
    elf2asm.c                  elf2asm driver
    elfcmp.c                   elfcmp driver
    e2a*.c, e2a*.h             shared by elf2asm and elfcmp: ELF and ar
                               reader, comparator, assembly emitter,
                               x86-64/AArch64/RISC-V printers, DWARF and
                               call-frame decoders, source recovery,
                               header generator
    elfrenamesym.1             man page (libelf rename tool)
    elflintsym.1               man page (libelf lint tool)
    elfbundle.1                man page (object bundler / symbol sealer)
    bin2obj.1                  man page (binary embed tool)
    data2obj.1                 man page (data description compiler,
                               including the full language reference)
    elf2asm.1                  man page (object to assembly)
    elfcmp.1                   man page (object equivalence)
    Makefile                   builds all seven binaries
    elf_tools_manual.tex       combined reference manual (LaTeX source)
    elf_tools_manual.pdf       combined reference manual (rendered PDF)
    bin2obj_example.sh         end-to-end demo for bin2obj
    data2obj_example.sh        end-to-end demo for data2obj
    elf2asm_example.sh         end-to-end demo for elf2asm and elfcmp
    tests/                     the test suite (tests/e2a: corpus and
                               helpers for the elf2asm tests)
    README                     this file

Build
-----
Requires: cc with -std=c17, GNU make, libelf (for the rename, lint, and
bundle tools), POSIX <regex.h> (for elflintsym and elfbundle), POSIX
<elf.h> (for bin2obj and data2obj).  elfbundle also needs a linker
supporting 'ld -r' at run time (GNU ld or lld); it is found via $LD,
--ld, or the PATH.

elf2asm and elfcmp need zlib, and elf2asm needs Capstone 4 or later;
without Capstone the Makefile builds the other six programs and says so.
elf2asm's verification wants an assembler for each target it meets: GNU
as (x86_64-, aarch64-, riscv64-linux-gnu-as) and/or clang.

    Linux  (Debian/Ubuntu):  apt install libelf-dev zlib1g-dev
                             libcapstone-dev
                             (for cross targets: clang, or
                             binutils-aarch64-linux-gnu and
                             binutils-riscv64-linux-gnu)
    Linux  (Fedora/RHEL):    dnf install elfutils-libelf-devel
                             zlib-devel capstone-devel
    FreeBSD:                 pkg install capstone gmake
                             (libelf, zlib and clang are in base)

    $ make

Install (optional)
------------------
    $ make install         # uses PREFIX=/usr/local by default
    $ make install PREFIX=/opt/local DESTDIR=/tmp/stage   # alternate

Testing
-------
The package ships with a test suite under tests/.  After `make' run:

    $ make test           # runs all 100 tests
    $ make sanitize-test  # rebuild with ASan+UBSan and run the suite

A test that cannot run on this machine -- every elf2asm test when
Capstone was not found, the cross-architecture ones without a cross
compiler and assembler -- is reported as skipped, with the reason, and
counted separately from the passes.

Quick start
-----------
Rename a symbol:

    $ echo "d sl_init sl_create" > rules.txt
    $ elfrenamesym -v rules.txt stringlist.o stringlist.renamed.o

Lint a binary for forbidden libc references:

    $ cat > forbid.txt <<EOF
    u  ^gets$       banned by CERT-C; use fgets
    u  ^system$     shell injection vector; use posix_spawn
    EOF
    $ elflintsym forbid.txt myprog.o

Bundle a library into one .o, exporting only its public API and sealing
the rest so it can be vendored without symbol clashes:

    $ elfbundle -E '^mylib_.*$' -o mylib_bundle.o parser.o lexer.o table.o

Embed a PNG into a C program; -h also emits a matching header file:

    $ bin2obj -h logo.png
    $ nm logo.o
    0000000000003020 R logo_png_end
    0000000000003020 A logo_png_size
    0000000000000000 R logo_png_start
    $ cat logo.h          # extern declarations, ready to #include

Embed a text file as a NUL-terminated C string (-z):

    $ printf 'SELECT * FROM users;' > q.sql
    $ bin2obj -z -h q.sql
    $ nm q.o | grep q_sql_start
    0000000000000000 R q_sql_start   # printf("%s", q_sql_start) just works

Build a dispatch table over functions defined in other objects, with the
pointers left for ld to fill in:

    $ cat > dispatch.ds <<'EOF'
    extern op_add, op_sub, op_mul;

    struct op { ptr fn; u32 arity; u32 flags; };

    export op ops[] = {
        { op_add, 2, 0 },
        { op_sub, 2, 0 },
        { op_mul, 2, 1 },
    };
    export abs nops = countof(ops);
    EOF
    $ data2obj -h dispatch.ds        # dispatch.o + a typed dispatch.h
    $ readelf -r dispatch.o | head -6
    000000000000  000700000001 R_X86_64_64  0000000000000000 op_add + 0

Turn an archive back into assembly, rebuild it, and check the result:

    $ elf2asm -o mylib libmylib.a
    elf2asm: wrote mylib (12 objects)
    $ cd mylib && make && elfcmp ../libmylib.a libmylib.a && echo same
    same
    $ ls include src          # recovered header(s) and source files

See elfrenamesym(1), elflintsym(1), elfbundle(1), bin2obj(1),
data2obj(1), elf2asm(1), elfcmp(1), and elf_tools_manual.pdf for full
details and worked examples.  data2obj(1) carries the complete reference for the data
description language.

License
-------
3-clause BSD license; see the top of each .c file for the full text.

Copyright (c) 2026, Robert Cousins.  All rights reserved.

Distribution
------------
    https://rcousins.com/pub/elf_tools-2.01

(Supersedes elf_tools-2.00, elf_tools-1.08, elf_tools-1.07, elf_tools-1.06,
elf_tools-1.05, elf_tools-1.04, elf_tools-1.03, elf_tools-1.02,
elf_tools-1.0, and the elfrenamesym-1.01 standalone package.)

Reporting bugs
--------------
Send mail to the author or open an issue at the distribution URL.
