Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

6.9 KB
Raw Blame
/* bpf2c.c — build tool (runs on the build machine, never as root): reads the .o that
 * `clang -target bpf` produces from np.bpf.c and writes a C header with each program's
 * instructions and its relocations to maps by name (build/gen/np_bpf.h). That way lord-netperm
 * carries the programs inside and neither reads nor interprets ELF at run time.
 *
 *   build/bpf2c build/np.bpf.o build/gen/np_bpf.h
 *
 * It accepts only what the loader knows how to resolve: executable "cgroup/..." sections,
 * R_BPF_64_64 relocations against symbols of the "maps" section in ld_imm64 instructions, and
 * nothing in .text (functions are inlined) nor global data (.data/.rodata/.bss). Anything else
 * is an error: better to fail at build time than to load a half-made program. */
#include <elf.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifndef EM_BPF
#define EM_BPF 247
#endif
#ifndef R_BPF_64_64
#define R_BPF_64_64 1
#endif

static unsigned char *buf;
static size_t len;

static int die(const char *m, const char *x) {
    fprintf(stderr, "bpf2c: %s%s%s\n", m, x ? ": " : "", x ? x : "");
    exit(1);
}

static const void *at(uint64_t off, uint64_t n) {
    if (off > len || n > len - off) die("outside the file", NULL);
    return buf + off;
}

static const char *str(const Elf64_Shdr *sh, uint32_t off) {
    if (off >= sh->sh_size) die("string outside its table", NULL);
    const char *s = at(sh->sh_offset + off, 1);
    if (!memchr(s, 0, sh->sh_size - off)) die("unterminated string", NULL);
    return s;
}

int main(int argc, char **argv) {
    if (argc != 3) die("usage: bpf2c <input.o> <output.h>", NULL);
    FILE *f = fopen(argv[1], "rb");
    if (!f) die("could not open", argv[1]);
    fseek(f, 0, SEEK_END);
    long l = ftell(f);
    fseek(f, 0, SEEK_SET);
    if (l <= 0 || l > (64 << 20)) die("odd size", argv[1]);
    len = (size_t)l;
    buf = malloc(len);
    if (!buf || fread(buf, 1, len, f) != len) die("could not read", argv[1]);
    fclose(f);

    const Elf64_Ehdr *eh = at(0, sizeof *eh);
    if (memcmp(eh->e_ident, ELFMAG, SELFMAG) || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_ident[EI_DATA] != ELFDATA2LSB ||
        eh->e_type != ET_REL || eh->e_machine != EM_BPF || eh->e_shentsize != sizeof(Elf64_Shdr))
        die("not a 64-bit little-endian BPF object", argv[1]);
    const Elf64_Shdr *sh = at(eh->e_shoff, (uint64_t)eh->e_shnum * sizeof *sh);
    if (eh->e_shstrndx >= eh->e_shnum) die("no section names", NULL);
    const Elf64_Shdr *shstr = &sh[eh->e_shstrndx];

    int symtab = -1, maps = -1;
    for (int i = 0; i < eh->e_shnum; i++) {
        const char *nm = str(shstr, sh[i].sh_name);
        if (sh[i].sh_type == SHT_SYMTAB) symtab = i;
        if (!strcmp(nm, "maps")) maps = i;
        if ((!strcmp(nm, ".text") || !strncmp(nm, ".data", 5) || !strncmp(nm, ".rodata", 7) || !strcmp(nm, ".bss")) && sh[i].sh_size)
            die("unsupported section (non-inlined functions or global data)", nm);
    }
    if (symtab < 0 || maps < 0) die("missing the symbol table or the maps section", NULL);
    if (sh[symtab].sh_link >= eh->e_shnum || sh[symtab].sh_entsize != sizeof(Elf64_Sym)) die("odd symbol table", NULL);
    const Elf64_Shdr *strtab = &sh[sh[symtab].sh_link];
    const Elf64_Sym *syms = at(sh[symtab].sh_offset, sh[symtab].sh_size);
    size_t nsyms = sh[symtab].sh_size / sizeof *syms;

    FILE *o = fopen(argv[2], "w");
    if (!o) die("could not write", argv[2]);
    fprintf(o, "/* np_bpf.h — generated by build/bpf2c from np.bpf.c. Do not edit. */\n");
    fprintf(o, "#ifndef LORD_NP_BPF_GEN_H\n#define LORD_NP_BPF_GEN_H\n#include \"netperm/bpfsys.h\"\n\n");
    int nprog = 0;
    char names[32][64], fns[32][64];
    for (int i = 0; i < eh->e_shnum; i++) {
        const char *nm = str(shstr, sh[i].sh_name);
        if (sh[i].sh_type != SHT_PROGBITS || !(sh[i].sh_flags & SHF_EXECINSTR) || !sh[i].sh_size) continue;
        if (strncmp(nm, "cgroup/", 7)) die("unknown executable section", nm);
        if (nprog >= 32 || strlen(nm) >= sizeof names[0]) die("too many programs", NULL);
        if (sh[i].sh_size % 8) die("odd program size", nm);
        const char *fn = NULL;                          /* the section's function symbol */
        for (size_t k = 0; k < nsyms; k++)
            if (syms[k].st_shndx == i && ELF64_ST_TYPE(syms[k].st_info) == STT_FUNC) fn = str(strtab, syms[k].st_name);
        if (!fn || strlen(fn) >= sizeof fns[0]) die("program without a name", nm);
        snprintf(names[nprog], sizeof names[0], "%s", nm);
        snprintf(fns[nprog], sizeof fns[0], "%s", fn);
        const uint64_t *ins = at(sh[i].sh_offset, sh[i].sh_size);
        size_t n = sh[i].sh_size / 8;
        fprintf(o, "static const uint64_t np_insns_%d[%zu] = {", nprog, n);
        for (size_t k = 0; k < n; k++) fprintf(o, "%s0x%016llxull,", k % 4 ? " " : "\n    ", (unsigned long long)ins[k]);
        fprintf(o, "\n};\n");
        /* relocations of this section */
        int nrel = 0;
        fprintf(o, "static const NpReloc np_rel_%d[] = {\n", nprog);
        for (int r = 0; r < eh->e_shnum; r++) {
            if (sh[r].sh_info != (uint32_t)i) continue;
            if (sh[r].sh_type == SHT_RELA) die("RELA relocations not supported", nm);
            if (sh[r].sh_type != SHT_REL) continue;
            if (sh[r].sh_entsize != sizeof(Elf64_Rel) || sh[r].sh_link != (uint32_t)symtab) die("odd relocation table", nm);
            const Elf64_Rel *rel = at(sh[r].sh_offset, sh[r].sh_size);
            for (size_t k = 0; k < sh[r].sh_size / sizeof *rel; k++) {
                uint64_t sym = ELF64_R_SYM(rel[k].r_info);
                if (ELF64_R_TYPE(rel[k].r_info) != R_BPF_64_64) die("unsupported relocation (a call to a non-inlined function?)", nm);
                if (sym >= nsyms || syms[sym].st_shndx != maps) die("relocation against something that isn't a map", nm);
                if (rel[k].r_offset % 8 || rel[k].r_offset / 8 + 1 >= n) die("relocation outside the program", nm);
                uint64_t insn = ins[rel[k].r_offset / 8];
                if ((insn & 0xff) != 0x18) die("map relocation outside an ld_imm64", nm);
                const char *mn = str(strtab, syms[sym].st_name);
                for (const char *c = mn; *c; c++) if (!((*c >= 'a' && *c <= 'z') || (*c >= '0' && *c <= '9') || *c == '_')) die("odd map name", mn);
                fprintf(o, "    { %llu, \"%s\" },\n", (unsigned long long)(rel[k].r_offset / 8), mn);
                nrel++;
            }
        }
        if (!nrel) fprintf(o, "    { 0, 0 },\n");
        fprintf(o, "};\n#define NP_NREL_%d %d\n\n", nprog, nrel);
        nprog++;
    }
    if (!nprog) die("no programs", NULL);
    fprintf(o, "static const NpProgDesc np_progs[] = {\n");
    for (int i = 0; i < nprog; i++)
        fprintf(o, "    { \"%s\", \"%s\", np_insns_%d, sizeof np_insns_%d / 8, np_rel_%d, NP_NREL_%d },\n", names[i], fns[i], i, i, i, i);
    fprintf(o, "};\n#define NP_NPROGS %d\n\n#endif\n", nprog);
    if (fclose(o)) die("could not write", argv[2]);
    return 0;
}