eBPF-based security platform
bpm: inspect packaged upatch data
John Fastabendaa85afe8e95c
diff --git a/Documentation/upatch.rst b/Documentation/upatch.rstindex 7614f7d4..e1d80d40 100644--- a/Documentation/upatch.rst+++ b/Documentation/upatch.rst@@ -440,7 +440,20 @@ moves installed packages to the newest indexed version; ``uninstall``loads the package's unload directives, so a package can only beremoved through artifacts its operator signed. ``bpm info`` prints apackage's README from a local file or a reference before installing-it.+it. ``bpm info upatches`` lists the package's load upatches, while+``--all`` includes unload directives. ``bpm info data`` decodes the+selected upatch's ``.rodata`` initial value and prints BTF+variable names, types and values with offsets into both the loader data+and the upatch file. It reads the packaged artifact without running its+loader. Add ``--json`` to emit the same information as JSON; integer+values remain JSON numbers, enums include their name and numeric value,+and values without a supported BTF representation are shown as hex.+The member path is relative to the package root, for example::++ shirudo bpm info upatches ./kernel-obs-0.1.bee+ shirudo bpm info upatches ./kernel-obs-0.1.bee --all+ shirudo bpm info data ./kernel-obs-0.1.bee upatches/kernel-obs.upatch+ shirudo bpm info data ./kernel-obs-0.1.bee upatches/kernel-obs.upatch --jsonThe tree~~~~~~~~diff --git a/Makefile.shirudo b/Makefile.shirudoindex f2a1d660..2b056146 100644--- a/Makefile.shirudo+++ b/Makefile.shirudo@@ -220,6 +220,7 @@ UTIL_SRCS := \util/seal.c \util/serializer.c \util/upatch_maps.c \+ util/upatch_rodata.c \util/upatch_decode.c \util/upatch_maps_otel.c \util/elf_target.c \@@ -432,6 +433,7 @@ tools/shirudo-build/shirudo-build: $(BUILD_OBJS) util/sign.o util/config_image.outil/seal.o util/harden.o util/string.o \util/crypto_openssl.o util/tls_openssl.o \util/bpm_oci.o util/bpm_package.o \+ util/upatch_rodata.o \util/bpm_tree.o $(VERSION_OBJ) \$(LIBBPF_A)@printf ' LD $@\n'diff --git a/builtin-bpm.c b/builtin-bpm.cindex df659c1e..ea0a6f57 100644--- a/builtin-bpm.c+++ b/builtin-bpm.c@@ -50,6 +50,7 @@#include "util/paths.h"#include "util/seal.h"#include "util/upatch.h"+#include "util/upatch_rodata.h"struct bpm_source {char name[BPM_MAX_NAME];@@ -436,6 +437,177 @@ out:return rc;}+struct bpm_upatches_ctx {+ bool all;+ char *list;+ size_t len;+ size_t cap;+};++static int print_upatch_member(void *ctx, const char *member, char type)+{+ struct bpm_upatches_ctx *opts = ctx;+ static const char prefix[] = "upatches/";+ static const char unload[] = ".unload.upatch";+ static const char suffix[] = ".upatch";+ size_t len = strlen(member), unload_len = sizeof(unload) - 1;+ size_t suffix_len = sizeof(suffix) - 1;+ size_t need, cap;+ char *next;++ if (type != '0' || strncmp(member, prefix, sizeof(prefix) - 1) ||+ len < suffix_len || strcmp(member + len - suffix_len, suffix))+ return 0;+ if (!opts->all && len >= unload_len &&+ !strcmp(member + len - unload_len, unload))+ return 0;+ if (len <= sizeof(prefix) - 1 || strchr(member + sizeof(prefix) - 1, '/'))+ return 0;+ if (len > SIZE_MAX - opts->len - 1)+ return -EOVERFLOW;+ need = opts->len + len + 1;+ if (need > opts->cap) {+ cap = opts->cap ? opts->cap : 4096;+ while (cap < need) {+ if (cap > SHIRUDO_JSON_MAX_BYTES / 2) {+ cap = SHIRUDO_JSON_MAX_BYTES;+ break;+ }+ cap *= 2;+ }+ if (cap < need)+ return -E2BIG;+ next = xreallocarray(opts->list, opts->cap, cap, 1);+ if (!next)+ return -ENOMEM;+ opts->list = next;+ opts->cap = cap;+ }+ memcpy(opts->list + opts->len, member, len);+ opts->list[opts->len + len] = '\n';+ opts->len = need;+ return 0;+}++static int bpm_info_archive(const char *source, char temporary[])+{+ int fd, rc;++ if (strncmp(source, "oci://", 6))+ return 0;+ fd = mkstemp(temporary);+ if (fd < 0)+ return -errno;+ close(fd);+ rc = download_package(source, temporary);+ if (rc)+ unlink(temporary);+ return rc;+}++static int print_package_upatches(const char *source, bool all)+{+ char temporary[] = "/tmp/shirudo-bpm-upatches-XXXXXX";+ size_t beefile_len = 0;+ __u8 *beefile = NULL;+ const char *archive = source;+ char package_dir[101];+ struct bpm_upatches_ctx ctx = { .all = all };+ int rc;++ rc = bpm_info_archive(source, temporary);+ if (rc)+ return rc;+ if (!strncmp(source, "oci://", 6))+ archive = temporary;+ rc = bpm_pkg_read_member_in(archive, "Beefile", NULL, package_dir,+ sizeof(package_dir), &beefile, &beefile_len,+ 4u * 1024u * 1024u);+ if (!rc)+ rc = bpm_pkg_visit_members(archive, package_dir,+ print_upatch_member, &ctx);+ if (!rc && ctx.len)+ rc = write_complete(STDOUT_FILENO, ctx.list, ctx.len);+ if (rc == -ENOENT)+ pr_err("bpm info upatches: package %s does not include Beefile",+ source);+ if (beefile)+ xfree(beefile, beefile_len + 1);+ if (ctx.list)+ xfree(ctx.list, ctx.cap);+ if (archive == temporary)+ unlink(temporary);+ return rc;+}++static int print_package_upatch_data(const char *source, const char *member,+ bool json)+{+ static const char suffix[] = ".upatch";+ char temporary[] = "/tmp/shirudo-bpm-data-XXXXXX";+ size_t beefile_len = 0, upatch_len = 0;+ __u8 *beefile = NULL, *bytes = NULL;+ const char *archive = source;+ char package_dir[101];+ struct shirudo_upatch u = {};+ int rc;++ if (!bpm_archive_rel_ok(member) || strncmp(member, "upatches/", 9) ||+ strlen(member) < sizeof(suffix) - 1 ||+ strcmp(member + strlen(member) - (sizeof(suffix) - 1), suffix) ||+ strchr(member + 9, '/'))+ return -EINVAL;+ rc = bpm_info_archive(source, temporary);+ if (rc)+ return rc;+ if (!strncmp(source, "oci://", 6))+ archive = temporary;+ rc = bpm_pkg_read_member_in(archive, "Beefile", NULL, package_dir,+ sizeof(package_dir), &beefile, &beefile_len,+ 4u * 1024u * 1024u);+ if (rc) {+ if (rc == -ENOENT)+ pr_err("bpm info data: package %s does not include Beefile",+ source);+ goto out;+ }+ rc = bpm_pkg_read_member_in(archive, member, package_dir, NULL, 0,+ &bytes, &upatch_len,+ SHIRUDO_UPATCH_FILE_MAX);+ if (rc) {+ if (rc == -ENOENT)+ pr_err("bpm info data: package %s has no member %s",+ source, member);+ goto out;+ }+ rc = upatch_open_memory(bytes, upatch_len, &u);+ if (rc) {+ pr_err("bpm info data: %s is not a valid upatch", member);+ goto out;+ }+ if (upatch_is_unload(&u)) {+ pr_err("bpm info data: %s is an unload directive", member);+ rc = -EINVAL;+ goto out;+ }+ rc = upatch_rodata_print(&u, member, json);+ if (rc == -ENODATA)+ pr_err("bpm info data: %s has no loader .rodata map data", member);+ else if (rc == -ENOENT || rc == -EOPNOTSUPP)+ pr_err("bpm info data: %s has no supported BTF .rodata data", member);+ else if (rc == -EINVAL)+ pr_err("bpm info data: cannot decode .rodata in %s", member);+out:+ upatch_close(&u);+ if (beefile)+ xfree(beefile, beefile_len + 1);+ if (bytes)+ xfree(bytes, upatch_len + 1);+ if (archive == temporary)+ unlink(temporary);+ return rc;+}+static int cert_matches_active(const char *path){struct shirudo_cert a = {}, b = {};@@ -2149,11 +2321,18 @@ static void bpm_pull_usage(void)static void bpm_info_usage(void){fprintf(stderr,- "usage: shirudo bpm info <package-file|package-reference>\n\n"- "Prints README.md from a local .bee file or an OCI package.\n"+ "usage: shirudo bpm info <package-file|package-reference>\n"+ " shirudo bpm info upatches <package> [--all]\n"+ " shirudo bpm info data <package> <upatch-member> [--json]\n\n"+ "Prints package README.md, lists packaged upatches, or decodes\n"+ "the BPF .rodata initial data using its BTF types.\n""Examples:\n"" shirudo bpm info ./package.bee\n"- " shirudo bpm info oci://quay.io/namespace/package:tag\n");+ " shirudo bpm info upatches ./package.bee\n"+ " shirudo bpm info upatches ./package.bee --all\n"+ " shirudo bpm info data ./package.bee upatches/kernel-obs.upatch\n"+ " shirudo bpm info data ./package.bee upatches/kernel-obs.upatch --json\n"+ "Package may be a local .bee file or an oci:// reference.\n");}static int bpm_finish(int lock, int rc, const char *action)@@ -2268,19 +2447,49 @@ int cmd_bpm(int argc, const char **argv)if (!strcmp(sub, "config"))return cmd_bpm_config(argc - 1, argv + 1);if (!strcmp(sub, "info")) {+ bool json = false, all = false;+ const char *source;int rc;if (argc == 3 && is_help(argv[2])) {bpm_info_usage();return 0;}- if (argc != 3) {+ if (argc < 3) {bpm_info_usage();return 2;}+ if (!strcmp(argv[2], "upatches")) {+ if ((argc != 4 && argc != 5) ||+ (argc == 5 && strcmp(argv[4], "--all"))) {+ bpm_info_usage();+ return 2;+ }+ source = argv[3];+ all = argc == 5;+ } else if (!strcmp(argv[2], "data")) {+ if ((argc != 5 && argc != 6) ||+ (argc == 6 && strcmp(argv[5], "--json"))) {+ bpm_info_usage();+ return 2;+ }+ source = argv[3];+ json = argc == 6;+ } else {+ if (argc != 3) {+ bpm_info_usage();+ return 2;+ }+ source = argv[2];+ }if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK)return bpm_fail("initialize curl", -EIO);- rc = print_package_readme(argv[2]);+ if (!strcmp(argv[2], "upatches"))+ rc = print_package_upatches(source, all);+ else if (!strcmp(argv[2], "data"))+ rc = print_package_upatch_data(source, argv[4], json);+ else+ rc = print_package_readme(source);return bpm_finish(-1, rc, "info");}if (!strcmp(sub, "tree") && (argc < 3 || is_help(argv[2]))) {diff --git a/completion/shirudo.bash b/completion/shirudo.bashindex 7d17076a..dbb65584 100644--- a/completion/shirudo.bash+++ b/completion/shirudo.bash@@ -90,6 +90,23 @@ _shirudo()COMPREPLY=( $(compgen -W "--key-file=" -- "$cur") )elif [[ $sub == repo && cword -eq 3 ]]; thenCOMPREPLY=( $(compgen -W "update" -- "$cur") )+ elif [[ $sub == info && cword -eq 3 ]]; then+ COMPREPLY=( $(compgen -W "upatches data" -- "$cur") \+ $(compgen -f -X '!*.bee' -- "$cur") \+ $(compgen -d -- "$cur") )+ elif [[ $sub == info && ${COMP_WORDS[3]} == upatches && cword -eq 4 ]]; then+ COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \+ $(compgen -d -- "$cur") )+ elif [[ $sub == info && ${COMP_WORDS[3]} == upatches && cword -eq 5 ]]; then+ COMPREPLY=( $(compgen -W "--all" -- "$cur") )+ elif [[ $sub == info && ${COMP_WORDS[3]} == data && cword -eq 4 ]]; then+ COMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \+ $(compgen -d -- "$cur") )+ elif [[ $sub == info && ${COMP_WORDS[3]} == data && cword -eq 5 ]]; then+ COMPREPLY=( $(compgen -f -X '!*.upatch' -- "$cur") \+ $(compgen -d -- "$cur") )+ elif [[ $sub == info && ${COMP_WORDS[3]} == data && cword -eq 6 ]]; then+ COMPREPLY=( $(compgen -W "--json" -- "$cur") )elif [[ $sub == info ]]; thenCOMPREPLY=( $(compgen -f -X '!*.bee' -- "$cur") \$(compgen -d -- "$cur") )diff --git a/tools/shirudo-build/README.md b/tools/shirudo-build/README.mdindex aa750bb9..152227d8 100644--- a/tools/shirudo-build/README.md+++ b/tools/shirudo-build/README.md@@ -42,6 +42,7 @@ target boundary) and `AGENTS.md` (the no-subprocess invariant).| `<source.bpf.c>` | compile (fork/exec clang) → gen_loader → sign → package || `<file.bpf.o>` | gen_loader → sign → package (skip compile) || `--unload <name>` | emit signed UNLOAD directive `.upatch` |+| `upatch rewrite-rodata <original> <modified> -o <output> --data-range <offset:length>...` | verify an existing signed upatch, permit changes only to its BTF watch arrays, then re-sign it || `keys vouch <cert.der>` | sign a vouch for another certificate || `bpm build [context] --version <v> [-f <name>.bee] [--vmlinux <file>]` | compile, sign and package every Beefile upatch into a `.bee` || `bpm push <pkg.bee> oci://...` | publish the package and certificate referrer; with signing material, also update the signed index |diff --git a/tools/shirudo-build/package.c b/tools/shirudo-build/package.cindex 5c964d2f..d2743c04 100644--- a/tools/shirudo-build/package.c+++ b/tools/shirudo-build/package.c@@ -9,6 +9,7 @@#include <errno.h>#include <stdbool.h>#include <fcntl.h>+#include <limits.h>#include <stddef.h>#include <stdint.h>#include <stdio.h>@@ -26,6 +27,7 @@#include <shirudo/upatch.h>#include "bpf/lib/shirudo_serializer.h"+#include "bpm_package.h"#include "elf_target.h"#include "io.h"#include "loader.h"@@ -33,8 +35,10 @@#include "macros.h"#include "malloc.h"#include "package.h"+#include "paths.h"#include "sign.h"#include "upatch.h"+#include "upatch_rodata.h"/** A detached CMS over an ML-DSA-87 signature is about 5 KiB (4627-byte@@ -108,6 +112,292 @@ static void pack_header(struct shirudo_upatch_header *h,h->reserved1 = 0;}+int shirudo_build_package_resign(const char *original,+ const char *modified, const char *output,+ const struct shirudo_data_range *ranges,+ size_t nr_ranges, const char *pkey_path,+ const char *cert_path)+{+ struct shirudo_upatch_header hdr;+ struct shirudo_sign_io sio = {};+ struct shirudo_upatch src = {}, mod = {};+ struct shirudo_rodata_range watch_ranges[2] = {};+ const __u8 *src_data, *mod_data;+ bool range_found[2] = {};+ __u8 digest[SHIRUDO_SHA256_LEN], *payload = NULL, *sig_buf = NULL;+ char name[SHIRUDO_UPATCH_NAME_MAX + 1];+ __u32 loader_off, sig_off, data_off, meta_off;+ __u32 digest_len;+ __u64 total, payload_len;+ size_t i, j;+ int fd = -1;+ int rc;++ if (!original || !modified || !output || !ranges || !nr_ranges ||+ nr_ranges > 16 || !strcmp(original, output) ||+ !strcmp(modified, output))+ return -EINVAL;+ rc = upatch_open(original, &src);+ if (rc)+ return rc;+ rc = upatch_open(modified, &mod);+ if (rc)+ goto out;+ src_data = upatch_data(&src);+ mod_data = upatch_data(&mod);+ if (upatch_is_unload(&src) || upatch_is_unload(&mod) ||+ memcmp(src.map, mod.map, SHIRUDO_UPATCH_HEADER_SIZE) ||+ src.hdr.loader_insns_len != mod.hdr.loader_insns_len ||+ src.hdr.signature_len != mod.hdr.signature_len ||+ src.hdr.data_len != mod.hdr.data_len ||+ src.hdr.metadata_len != mod.hdr.metadata_len ||+ memcmp(upatch_loader(&src), upatch_loader(&mod),+ src.hdr.loader_insns_len) ||+ memcmp(upatch_signature(&src), upatch_signature(&mod),+ src.hdr.signature_len) ||+ (src.hdr.metadata_len &&+ memcmp(upatch_metadata(&src), upatch_metadata(&mod),+ src.hdr.metadata_len))) {+ rc = -EINVAL;+ goto out;+ }+ for (i = 0; i < nr_ranges; i++) {+ if (!ranges[i].length || ranges[i].offset > src.hdr.data_len ||+ ranges[i].length > src.hdr.data_len - ranges[i].offset ||+ (i && ranges[i].offset <+ ranges[i - 1].offset + ranges[i - 1].length)) {+ rc = -EINVAL;+ goto out;+ }+ }+ for (i = 0; i < src.hdr.data_len; i++) {+ bool allowed = false;++ for (j = 0; j < nr_ranges; j++)+ if (i >= ranges[j].offset &&+ i - ranges[j].offset < ranges[j].length) {+ allowed = true;+ break;+ }+ if (!allowed && src_data[i] != mod_data[i]) {+ rc = -EPERM;+ goto out;+ }+ }+ if (!memchr(src.hdr.name, '\0', sizeof(src.hdr.name))) {+ rc = -EINVAL;+ goto out;+ }+ if ((__u64)src.hdr.loader_insns_len + src.hdr.data_len > SIZE_MAX) {+ rc = -EOVERFLOW;+ goto out;+ }+ payload_len = (__u64)src.hdr.loader_insns_len + src.hdr.data_len;+ payload = xmalloc((size_t)payload_len);+ if (!payload) {+ rc = -ENOMEM;+ goto out;+ }+ memcpy(payload, upatch_loader(&src), src.hdr.loader_insns_len);+ memcpy(payload + src.hdr.loader_insns_len, upatch_data(&src),+ src.hdr.data_len);+ rc = bpm_verify_cms(payload, (size_t)payload_len,+ upatch_signature(&src), src.hdr.signature_len,+ cert_path);+ if (rc)+ goto out;+ if (EVP_Digest(payload, (size_t)payload_len, digest, &digest_len,+ EVP_sha256(), NULL) != 1 ||+ digest_len != sizeof(digest) ||+ memcmp(digest, src.hdr.payload_sha256, sizeof(digest))) {+ rc = -EBADMSG;+ goto out;+ }+ rc = upatch_rodata_watch_ranges(&src, watch_ranges);+ if (rc)+ goto out;+ if (nr_ranges != ARRAY_SIZE(watch_ranges)) {+ rc = -EINVAL;+ goto out;+ }+ for (i = 0; i < nr_ranges; i++) {+ for (j = 0; j < ARRAY_SIZE(watch_ranges); j++)+ if (ranges[i].offset == watch_ranges[j].offset &&+ ranges[i].length == watch_ranges[j].size &&+ !range_found[j]) {+ range_found[j] = true;+ break;+ }+ if (j == ARRAY_SIZE(watch_ranges)) {+ rc = -EPERM;+ goto out;+ }+ }+ sig_buf = xmalloc(SHIRUDO_MAX_SIG_SIZE);+ if (!sig_buf) {+ rc = -ENOMEM;+ goto out;+ }+ sio.insns = upatch_loader(&mod);+ sio.insns_sz = mod.hdr.loader_insns_len;+ sio.data = upatch_data(&mod);+ sio.data_sz = mod.hdr.data_len;+ sio.signature = sig_buf;+ sio.signature_sz = SHIRUDO_MAX_SIG_SIZE;+ rc = cms_sign(&sio, pkey_path, cert_path);+ if (rc)+ goto out;+ loader_off = sizeof(hdr);+ if ((__u64)loader_off + sio.insns_sz > UINT32_MAX) {+ rc = -EOVERFLOW;+ goto out;+ }+ sig_off = loader_off + (__u32)sio.insns_sz;+ if ((__u64)sig_off + sio.signature_sz > UINT32_MAX) {+ rc = -EOVERFLOW;+ goto out;+ }+ data_off = sig_off + (__u32)sio.signature_sz;+ if ((__u64)data_off + sio.data_sz > UINT32_MAX) {+ rc = -EOVERFLOW;+ goto out;+ }+ meta_off = data_off + (__u32)sio.data_sz;+ total = (__u64)meta_off + mod.hdr.metadata_len;+ if (total > SHIRUDO_UPATCH_FILE_MAX) {+ rc = -E2BIG;+ goto out;+ }+ memcpy(name, mod.hdr.name, SHIRUDO_UPATCH_NAME_MAX);+ name[SHIRUDO_UPATCH_NAME_MAX] = '\0';+ pack_header(&hdr, name, mod.hdr.type, mod.hdr.flags,+ sio.payload_sha256,+ loader_off, (__u32)sio.insns_sz,+ sig_off, (__u32)sio.signature_sz,+ mod.hdr.metadata_len ? meta_off : 0, mod.hdr.metadata_len,+ sio.data_sz ? data_off : 0, (__u32)sio.data_sz,+ mod.hdr.log_buf_sz, mod.hdr.nr_maps, mod.hdr.nr_progs);+ fd = open(output, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);+ if (fd < 0) {+ rc = -errno;+ goto out;+ }+ rc = write_complete(fd, &hdr, sizeof(hdr));+ if (!rc)+ rc = write_complete(fd, sio.insns, sio.insns_sz);+ if (!rc)+ rc = write_complete(fd, sig_buf, sio.signature_sz);+ if (!rc && sio.data_sz)+ rc = write_complete(fd, sio.data, sio.data_sz);+ if (!rc && mod.hdr.metadata_len)+ rc = write_complete(fd, upatch_metadata(&mod), mod.hdr.metadata_len);+ if (!rc && fsync(fd) != 0)+ rc = -errno;+out:+ if (fd >= 0)+ close(fd);+ if (sig_buf)+ xfree(sig_buf, SHIRUDO_MAX_SIG_SIZE);+ if (payload)+ xfree(payload, (size_t)payload_len);+ upatch_close(&mod);+ upatch_close(&src);+ return rc;+}++int shirudo_build_upatch_cli(int argc, char **argv)+{+ const char *keys_dir = NULL, *original = NULL, *modified = NULL;+ const char *output = NULL;+ const char *pkey = SHIRUDO_SIGNING_KEY_PATH;+ const char *cert = SHIRUDO_CERT_PATH;+ struct shirudo_data_range ranges[16] = {};+ char pkey_buf[PATH_MAX], cert_buf[PATH_MAX];+ int pkey_explicit = 0, cert_explicit = 0;+ size_t nr_ranges = 0;+ int i;+ int rc;++ if (argc < 2 || strcmp(argv[1], "rewrite-rodata")) {+ fprintf(stderr,+ "usage: shirudo-build upatch rewrite-rodata "+ "<original.upatch> <modified.upatch> -o <output.upatch> "+ "--data-range <offset:length>... [--keys-dir <dir>] "+ "[--key <signing_key.pem>] [--cert <cert.der>]\n");+ return 2;+ }+ for (i = 2; i < argc; i++) {+ if (!strcmp(argv[i], "-o") && i + 1 < argc) {+ output = argv[++i];+ } else if (!strcmp(argv[i], "--data-range") && i + 1 < argc) {+ const char *range = argv[++i];+ size_t off_len = digits(range, strlen(range));+ const char *length;+ size_t len_len;+ __u64 offset, len;++ if (nr_ranges == ARRAY_SIZE(ranges) || !off_len ||+ off_len >= strlen(range) ||+ range[off_len] != ':')+ return 2;+ length = range + off_len + 1;+ len_len = digits(length, strlen(length));+ if (!len_len || length[len_len] ||+ parse_u64(range, off_len, UINT32_MAX, &offset) ||+ parse_u64(length, len_len, UINT32_MAX, &len) || !len)+ return 2;+ ranges[nr_ranges].offset = (__u32)offset;+ ranges[nr_ranges].length = (__u32)len;+ nr_ranges++;+ } else if (!strcmp(argv[i], "--keys-dir") && i + 1 < argc) {+ keys_dir = argv[++i];+ } else if (!strcmp(argv[i], "--key") && i + 1 < argc) {+ pkey = argv[++i];+ pkey_explicit = 1;+ } else if (!strcmp(argv[i], "--cert") && i + 1 < argc) {+ cert = argv[++i];+ cert_explicit = 1;+ } else if (argv[i][0] == '-') {+ pr_err("upatch rewrite-rodata: unknown option %s", argv[i]);+ return 2;+ } else if (!original) {+ original = argv[i];+ } else if (!modified) {+ modified = argv[i];+ } else {+ pr_err("upatch rewrite-rodata: unexpected argument %s",+ argv[i]);+ return 2;+ }+ }+ if (!original || !modified || !output || !nr_ranges) {+ pr_err("upatch rewrite-rodata requires two inputs, -o, and data ranges");+ return 2;+ }+ keys_dir = keys_dir_resolve(keys_dir);+ if (keys_dir) {+ if (!pkey_explicit) {+ rc = shirudo_key_path(pkey_buf, sizeof(pkey_buf), keys_dir,+ SHIRUDO_SIGNING_KEY_FILE);+ if (rc)+ return 2;+ pkey = pkey_buf;+ }+ if (!cert_explicit) {+ rc = shirudo_key_path(cert_buf, sizeof(cert_buf), keys_dir,+ SHIRUDO_CERT_FILE);+ if (rc)+ return 2;+ cert = cert_buf;+ }+ }+ rc = shirudo_build_package_resign(original, modified, output,+ ranges, nr_ranges, pkey, cert);+ if (rc)+ pr_err("upatch rewrite-rodata: %s", strerror(-rc));+ return rc ? 1 : 0;+}+static bool unsupported_kprobe_section(const char *sec){if (sec && sec[0] == '?')diff --git a/tools/shirudo-build/package.h b/tools/shirudo-build/package.hindex 2f3df153..3e1e8c72 100644--- a/tools/shirudo-build/package.h+++ b/tools/shirudo-build/package.h@@ -10,6 +10,11 @@#include <shirudo/misc.h>+struct shirudo_data_range {+ __u32 offset;+ __u32 length;+};+int shirudo_build_package_load(const char *bpf_o, const char *src_path,const char *out_upatch, const char *upatch_name,const char *pkey_path, const char *cert_path);@@ -20,4 +25,11 @@ int shirudo_build_package_unload(const char *name,const char *pkey_path,const char *cert_path);+int shirudo_build_package_resign(const char *original,+ const char *modified, const char *output,+ const struct shirudo_data_range *ranges,+ size_t nr_ranges, const char *pkey_path,+ const char *cert_path);+int shirudo_build_upatch_cli(int argc, char **argv);+#endif /* SHIRUDO_BUILD_PACKAGE_H */diff --git a/tools/shirudo-build/shirudo-build.c b/tools/shirudo-build/shirudo-build.cindex 38ac956f..e7d4ea63 100644--- a/tools/shirudo-build/shirudo-build.c+++ b/tools/shirudo-build/shirudo-build.c@@ -212,6 +212,8 @@ int main(int argc, char **argv)if (argc >= 2 && strcmp(argv[1], "image") == 0)return shirudo_build_image(argc - 1, argv + 1);+ if (argc >= 2 && strcmp(argv[1], "upatch") == 0)+ return shirudo_build_upatch_cli(argc - 1, argv + 1);if (argc >= 2 && strcmp(argv[1], "bpm") == 0)return shirudo_build_bpm(argc - 1, argv + 1);if (argc >= 3 && strcmp(argv[1], "keys") == 0 &&diff --git a/upatches/kernel-obs/README.md b/upatches/kernel-obs/README.mdindex 54ee4ab0..4b1d0e31 100644--- a/upatches/kernel-obs/README.md+++ b/upatches/kernel-obs/README.md@@ -99,6 +99,16 @@ trailing `w` for opens for writing only. Both are compiled into thesigned object: edit the list, run `make lists` in this directory andrebuild the package. There is nothing to configure on the target.+To update only the watch addresses in an existing `.upatch`, run+`python3 rewrite_watch_upatch.py watch.list kernel-obs.upatch`. It takes+the same address and CIDR format as `gen_watch.py`, preserves the compiled+loader and BTF, and re-signs the changed `.rodata` with the operator key+from `/var/lib/shirudo/keys` (or `--keys-dir`). Use `--dry-run` to check+that the new tries fit the arrays in the existing BTF layout, or `-o` to+write a separate artifact. The tool refuses a list that needs more trie+nodes than the existing arrays hold; changing those capacities still+requires rebuilding the BPF object.+## Read the tables```shdiff --git a/upatches/kernel-obs/rewrite_watch_upatch.py b/upatches/kernel-obs/rewrite_watch_upatch.pynew file mode 100644index 00000000..d0cd6578--- /dev/null+++ b/upatches/kernel-obs/rewrite_watch_upatch.py@@ -0,0 +1,504 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: BSD-2-Clause+# Copyright (c) 2026 Authors of shirudo+"""Replace kernel-obs watch trie values in a signed .upatch."""++import argparse+import os+from pathlib import Path+import shutil+import struct+import subprocess+import sys+import tempfile++from gen_watch import build_trie, read_networks+++UPATCH_HEADER_SIZE = 360+UPATCH_MAX_SIZE = 16 * 1024 * 1024+BTF_MAGIC = 0xEB9F+BTF_KIND_INT = 1+BTF_KIND_ARRAY = 3+BTF_KIND_STRUCT = 4+BTF_KIND_TYPEDEF = 8+BTF_KIND_VOLATILE = 9+BTF_KIND_CONST = 10+BTF_KIND_RESTRICT = 11+BTF_KIND_VAR = 14+BTF_KIND_DATASEC = 15+BTF_KIND_TYPE_TAG = 18+BPF_PSEUDO_MAP_IDX_VALUE = 6+BPF_FUNC_SYS_BPF = 166+BPF_MAP_CREATE = 0+BPF_MAP_UPDATE_ELEM = 2+BPF_LDDW = 0x18+BPF_JMP_CALL = 0x85+BPF_ALU64_MOV_IMM = 0xB7+BPF_LDXW = 0x61+BPF_STXW = 0x63+BPF_STXDW = 0x7B+++class RewriteError(Exception):+ pass+++def parse_btf_at(data, start):+ if len(data) - start < 24:+ return None+ magic, version, flags, hdr_len, type_off, type_len, str_off, str_len = \+ struct.unpack_from("<HBBIIIII", data, start)+ if magic != BTF_MAGIC or version != 1 or hdr_len < 24:+ return None+ type_start = start + hdr_len + type_off+ type_end = type_start + type_len+ str_start = start + hdr_len + str_off+ str_end = str_start + str_len+ if (type_start < start or type_end < type_start or type_end > len(data) or+ str_start < start or str_end < str_start or str_end > len(data)):+ return None+ strings = data[str_start:str_end]+ types = [None]+ pos = type_start+ while pos < type_end:+ if type_end - pos < 12:+ return None+ name_off, info, size_type = struct.unpack_from("<III", data, pos)+ kind = (info >> 24) & 0x1f+ vlen = info & 0xffff+ kflag = bool(info & 0x80000000)+ pos += 12+ if kind in (BTF_KIND_INT, BTF_KIND_VAR, 17):+ extra = 4+ elif kind == BTF_KIND_ARRAY:+ extra = 12+ elif kind in (4, 5, BTF_KIND_DATASEC):+ extra = vlen * 12+ elif kind == 6:+ extra = vlen * 8+ elif kind == 13:+ extra = vlen * 8+ elif kind == 19:+ extra = vlen * 12+ else:+ extra = 0+ if extra > type_end - pos:+ return None+ payload = data[pos:pos + extra]+ pos += extra+ if name_off >= len(strings):+ return None+ end = strings.find(b"\0", name_off)+ if end < 0:+ return None+ try:+ name = strings[name_off:end].decode("utf-8")+ except UnicodeDecodeError:+ return None+ types.append({"name": name, "strings": strings,+ "kind": kind, "vlen": vlen,+ "size_type": size_type, "kflag": kflag,+ "payload": payload})+ if pos != type_end:+ return None+ return types+++def btf_u32s(typ):+ return struct.unpack("<" + "I" * (len(typ["payload"]) // 4),+ typ["payload"])+++def unwrap_type(types, type_id):+ for _ in range(16):+ if type_id <= 0 or type_id >= len(types):+ raise RewriteError("BTF contains an invalid type reference")+ typ = types[type_id]+ if typ["kind"] in (BTF_KIND_TYPEDEF, BTF_KIND_VOLATILE,+ BTF_KIND_CONST, BTF_KIND_RESTRICT,+ BTF_KIND_TYPE_TAG):+ type_id = typ["size_type"]+ continue+ return type_id, typ+ raise RewriteError("BTF type aliases exceed the supported depth")+++def read_watch_arrays(data_blob):+ candidates = []+ search = 0+ while True:+ start = data_blob.find(b"\x9f\xeb", search)+ if start < 0:+ break+ search = start + 1+ types = parse_btf_at(data_blob, start)+ if not types:+ continue+ for type_id, typ in enumerate(types):+ if typ["kind"] == BTF_KIND_DATASEC and typ["name"] == ".rodata":+ candidates.append((start, types, type_id, typ))+ if len(candidates) != 1:+ raise RewriteError("expected one BTF .rodata data section in the upatch")+ btf_start, types, datasec_id, datasec = candidates[0]+ vars = {}+ for i in range(datasec["vlen"]):+ var_id, offset, size = struct.unpack_from("<III", datasec["payload"],+ i * 12)+ if var_id <= 0 or var_id >= len(types):+ raise RewriteError("BTF .rodata contains an invalid variable")+ var = types[var_id]+ if var["kind"] != BTF_KIND_VAR:+ continue+ if var["name"] in ("obs_watch_v4", "obs_watch_v6"):+ vars[var["name"]] = (var["size_type"], offset, size)+ if set(vars) != {"obs_watch_v4", "obs_watch_v6"}:+ raise RewriteError("BTF .rodata is missing obs_watch_v4 or obs_watch_v6")+ return types, vars+++def array_layout(types, type_id, var_size):+ type_id, array = unwrap_type(types, type_id)+ if array["kind"] != BTF_KIND_ARRAY:+ raise RewriteError("watch variable is not a BTF array")+ elem_id, index_id, count = btf_u32s(array)+ elem_id, node = unwrap_type(types, elem_id)+ if node["kind"] != BTF_KIND_STRUCT:+ raise RewriteError("watch array element is not a BTF struct")+ node_size = node["size_type"]+ if count == 0 or count * node_size != var_size:+ raise RewriteError("watch array dimensions do not match its .rodata size")+ fields = []+ for i in range(node["vlen"]):+ name_off, field_type, offset_bits = struct.unpack_from(+ "<III", node["payload"], i * 12)+ if node["kflag"]:+ bit_size = offset_bits >> 24+ offset_bits &= 0x00ffffff+ else:+ bit_size = 0+ if bit_size or offset_bits % 8:+ raise RewriteError("watch node has an unsupported bitfield layout")+ # Names are read from BTF's string table by the type parser below.+ fields.append((field_type, offset_bits // 8, name_off))+ child = None+ terminal = None+ reserved = None+ for field_type, offset, name_off in fields:+ if field_type <= 0 or field_type >= len(types):+ continue+ field_name = btf_name(types, name_off)+ if field_name == "child":+ child = (offset, field_type)+ elif field_name == "terminal":+ terminal = (offset, field_type)+ elif field_name == "reserved":+ reserved = (offset, field_type)+ if not child or not terminal or not reserved:+ raise RewriteError("BTF watch node lacks child, terminal, or reserved fields")+ child_offset, child_type_id = child+ _, child_array = unwrap_type(types, child_type_id)+ if child_array["kind"] != BTF_KIND_ARRAY:+ raise RewriteError("BTF child field is not an array")+ child_elem, _, child_count = btf_u32s(child_array)+ child_elem_id, child_elem_type = unwrap_type(types, child_elem)+ if child_count != 256 or child_elem_type["kind"] != BTF_KIND_INT or \+ child_elem_type["size_type"] != 2:+ raise RewriteError("BTF child field is not 256 unsigned 16-bit entries")+ enc = struct.unpack("<I", child_elem_type["payload"])[0]+ if ((enc >> 24) & 0xf) & 1:+ raise RewriteError("BTF child field uses signed integers")+ term_offset, term_type_id = terminal+ _, term_type = unwrap_type(types, term_type_id)+ if term_type["kind"] != BTF_KIND_INT or term_type["size_type"] != 2:+ raise RewriteError("BTF terminal field is not a 16-bit integer")+ reserved_offset, reserved_type_id = reserved+ _, reserved_type = unwrap_type(types, reserved_type_id)+ if reserved_type["kind"] != BTF_KIND_ARRAY:+ raise RewriteError("BTF reserved field is not an array")+ reserved_elem, _, reserved_count = btf_u32s(reserved_type)+ _, reserved_elem_type = unwrap_type(types, reserved_elem)+ if reserved_count != 3 or reserved_elem_type["kind"] != BTF_KIND_INT or \+ reserved_elem_type["size_type"] != 2:+ raise RewriteError("BTF reserved field is not three 16-bit integers")+ return {"count": count, "node_size": node_size,+ "child_offset": child_offset, "terminal_offset": term_offset,+ "reserved_offset": reserved_offset}+++def btf_name(types, name_off):+ for typ in types[1:]:+ strings = typ.get("strings")+ if strings is not None:+ end = strings.find(b"\0", name_off)+ return strings[name_off:end].decode("utf-8")+ raise RewriteError("BTF string table is unavailable")+++def decode_insn(raw, index):+ return struct.unpack_from("<BBhi", raw, index * 8)+++def lddw_offset(insns, index, reg):+ if index + 1 >= len(insns):+ return None+ code, regs, off, imm = insns[index]+ next_code, _, next_off, next_imm = insns[index + 1]+ if (code != BPF_LDDW or regs & 0xf != reg or regs >> 4 !=+ BPF_PSEUDO_MAP_IDX_VALUE or off or imm or next_code or next_off):+ return None+ return next_imm & 0xffffffff+++def sys_bpf_call(insns, index):+ if index < 4 or index >= len(insns):+ return None+ if insns[index][0] != BPF_JMP_CALL or insns[index][3] != BPF_FUNC_SYS_BPF:+ return None+ cmd = insns[index - 4]+ attr_size = insns[index - 1]+ if (cmd[0] != BPF_ALU64_MOV_IMM or cmd[1] != 1 or+ insns[index - 3][0] != BPF_LDDW or+ attr_size[0] != BPF_ALU64_MOV_IMM or attr_size[1] != 3):+ return None+ attr = lddw_offset(insns, index - 3, 2)+ if attr is None:+ return None+ return cmd[3], attr, attr_size[3]+++def next_sys_bpf(insns, start):+ for index in range(start, len(insns)):+ if sys_bpf_call(insns, index):+ return index+ return len(insns)+++def map_create_slot(insns, call, end):+ for index in range(call + 1, end - 2):+ offset = lddw_offset(insns, index, 1)+ if offset is None:+ continue+ code, regs, off, imm = insns[index + 2]+ if (code == BPF_STXW and regs & 0xf == 1 and regs >> 4 == 7 and+ off == 0 and offset % 4 == 0):+ return offset // 4+ return None+++def map_update_slot(insns, call, attr):+ start = max(0, call - 48)+ for index in range(start, call - 5):+ fd_array_offset = lddw_offset(insns, index, 2)+ if fd_array_offset is None:+ continue+ code, regs, off, imm = insns[index + 2]+ if (code != BPF_LDXW or regs & 0xf != 0 or regs >> 4 != 2 or off or+ lddw_offset(insns, index + 3, 1) != attr):+ continue+ code, regs, off, imm = insns[index + 5]+ if (code == BPF_STXW and regs & 0xf == 1 and regs >> 4 == 0 and+ off == 0 and fd_array_offset % 4 == 0):+ return fd_array_offset // 4+ return None+++def map_update_value_offset(insns, call, attr):+ start = max(0, call - 24)+ for index in range(start, call - 4):+ value_offset = lddw_offset(insns, index, 0)+ if value_offset is None:+ continue+ if lddw_offset(insns, index + 2, 1) != attr + 16:+ continue+ code, regs, off, imm = insns[index + 4]+ if (code == BPF_STXDW and regs & 0xf == 1 and regs >> 4 == 0 and+ off == 0):+ return value_offset+ return None+++def locate_rodata_data(loader, data_blob, datasec_size):+ if len(loader) % 8:+ raise RewriteError("loader instruction section has an invalid size")+ insns = [decode_insn(loader, i) for i in range(len(loader) // 8)]+ created = {}+ for index, insn in enumerate(insns):+ call = sys_bpf_call(insns, index)+ if not call:+ continue+ cmd, attr_offset, attr_size = call+ if attr_offset > len(data_blob) or attr_size > len(data_blob) - attr_offset:+ raise RewriteError("loader BPF attribute is outside its data section")+ if cmd == BPF_MAP_CREATE:+ if attr_size < 44:+ continue+ map_name = data_blob[attr_offset + 28:attr_offset + 44]+ map_name = map_name.split(b"\0", 1)[0].decode("ascii", "ignore")+ if not map_name.endswith(".rodata"):+ continue+ slot = map_create_slot(insns, index,+ next_sys_bpf(insns, index + 1))+ if slot is None:+ raise RewriteError("cannot find the loader slot for .rodata")+ value_size = struct.unpack_from("<I", data_blob,+ attr_offset + 8)[0]+ if value_size != datasec_size:+ raise RewriteError(".rodata map size does not match BTF")+ created[slot] = value_size+ elif cmd == BPF_MAP_UPDATE_ELEM:+ slot = map_update_slot(insns, index, attr_offset)+ if slot not in created or created[slot] != datasec_size:+ continue+ value_offset = map_update_value_offset(insns, index, attr_offset)+ if value_offset is None:+ continue+ if value_offset > len(data_blob) or \+ datasec_size > len(data_blob) - value_offset:+ raise RewriteError(".rodata initializer is outside loader data")+ return value_offset+ raise RewriteError("loader has no initial .rodata map value")+++def encode_nodes(nodes, layout):+ if len(nodes) > layout["count"]:+ raise RewriteError(+ f"new trie needs {len(nodes)} nodes but the existing BTF array "+ f"holds {layout['count']}; rebuild the BPF object to change its layout")+ output = bytearray(layout["count"] * layout["node_size"])+ for index, node in enumerate(nodes):+ base = index * layout["node_size"]+ for octet, child in node["children"].items():+ struct.pack_into("<H", output,+ base + layout["child_offset"] + octet * 2,+ child + 1)+ struct.pack_into("<H", output, base + layout["terminal_offset"],+ int(node["terminal"]))+ return output+++def helper_path(explicit):+ if explicit:+ return explicit+ from_env = os.environ.get("SHIRUDO_BUILD")+ if from_env:+ return from_env+ repo = Path(__file__).resolve().parents[2]+ in_tree = repo / "tools" / "shirudo-build" / "shirudo-build"+ if in_tree.is_file() and os.access(in_tree, os.X_OK):+ return str(in_tree)+ return shutil.which("shirudo-build") or "shirudo-build"+++def rewrite(args):+ input_path = Path(args.upatch)+ output_path = Path(args.output) if args.output else input_path+ if input_path.stat().st_size > UPATCH_MAX_SIZE:+ raise RewriteError("input is not a bounded .upatch file")+ artifact = bytearray(input_path.read_bytes())+ if len(artifact) > UPATCH_MAX_SIZE or len(artifact) < UPATCH_HEADER_SIZE:+ raise RewriteError("input is not a bounded .upatch file")+ magic, version, flags = struct.unpack_from("<QII", artifact, 0)+ if magic != 0x53485244554e4150 or version != 1 or flags & 1:+ raise RewriteError("input must be a load upatch in version 1 format")+ loader_off, loader_len, sig_off, sig_len, meta_off, meta_len, \+ data_off, data_len = struct.unpack_from("<8I", artifact, 304)+ if (loader_off > len(artifact) or loader_len > len(artifact) - loader_off or+ data_off > len(artifact) or data_len > len(artifact) - data_off or+ sig_off > len(artifact) or sig_len > len(artifact) - sig_off or+ (meta_len and (meta_off > len(artifact) or+ meta_len > len(artifact) - meta_off))):+ raise RewriteError("upatch section bounds are invalid")+ data_blob = artifact[data_off:data_off + data_len]+ types, variables = read_watch_arrays(data_blob)+ datasec_id = next(i for i, typ in enumerate(types)+ if typ["kind"] == BTF_KIND_DATASEC and+ typ["name"] == ".rodata")+ datasec_size = types[datasec_id]["size_type"]+ rodata_offset = locate_rodata_data(+ artifact[loader_off:loader_off + loader_len], data_blob, datasec_size)+ networks = read_networks(Path(args.iplist))+ new_data = bytearray(data_blob)+ counts = {}+ ranges = []+ for version_num, name in ((4, "obs_watch_v4"), (6, "obs_watch_v6")):+ type_id, var_offset, var_size = variables[name]+ layout = array_layout(types, type_id, var_size)+ nodes = build_trie(networks, version_num)+ encoded = encode_nodes(nodes, layout)+ start = rodata_offset + var_offset+ end = start + var_size+ if end > len(new_data) or len(encoded) != var_size:+ raise RewriteError(f"{name} does not fit in the existing .rodata")+ new_data[start:end] = encoded+ counts[version_num] = (len(nodes), layout["count"])+ ranges.append((start, var_size))+ ranges.sort()+ absolute_data = data_off+ artifact[absolute_data:absolute_data + data_len] = new_data+ if args.dry_run:+ print("watch trie fits existing .rodata:")+ print(f" IPv4: {counts[4][0]} of {counts[4][1]} nodes")+ print(f" IPv6: {counts[6][0]} of {counts[6][1]} nodes")+ return+ mode = input_path.stat().st_mode & 0o777+ output_path.parent.mkdir(parents=True, exist_ok=True)+ modified_path = None+ signed_path = None+ try:+ with tempfile.NamedTemporaryFile(prefix=".watch-modified-",+ dir=input_path.parent, delete=False) as f:+ f.write(artifact)+ modified_path = Path(f.name)+ with tempfile.NamedTemporaryFile(prefix=".watch-signed-",+ dir=output_path.parent, delete=False) as f:+ signed_path = Path(f.name)+ cmd = [helper_path(args.shirudo_build), "upatch", "rewrite-rodata",+ str(input_path), str(modified_path), "-o", str(signed_path)]+ for offset, length in ranges:+ cmd.extend(("--data-range", f"{offset}:{length}"))+ if args.keys_dir:+ cmd.extend(("--keys-dir", args.keys_dir))+ if args.key:+ cmd.extend(("--key", args.key))+ if args.cert:+ cmd.extend(("--cert", args.cert))+ subprocess.run(cmd, check=True)+ os.chmod(signed_path, mode)+ os.replace(signed_path, output_path)+ signed_path = None+ finally:+ for temp in (modified_path, signed_path):+ if temp is not None:+ try:+ temp.unlink()+ except FileNotFoundError:+ pass+ print(f"rewrote and re-signed {output_path}")+ print(f" IPv4: {counts[4][0]} of {counts[4][1]} nodes")+ print(f" IPv6: {counts[6][0]} of {counts[6][1]} nodes")+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("iplist", help="watch.list with IPv4/IPv6 addresses or CIDRs")+ parser.add_argument("upatch", help="existing signed kernel-obs .upatch")+ parser.add_argument("-o", "--output", help="output path; defaults to in-place update")+ parser.add_argument("--keys-dir", help="shirudo signing key directory")+ parser.add_argument("--key", help="ML-DSA-87 signing_key.pem")+ parser.add_argument("--cert", help="matching cert.der")+ parser.add_argument("--shirudo-build", help="path to the shirudo-build helper")+ parser.add_argument("--dry-run", action="store_true",+ help="check BTF layout and trie capacity without writing")+ args = parser.parse_args()+ try:+ rewrite(args)+ except (OSError, ValueError, RewriteError, struct.error,+ subprocess.CalledProcessError) as error:+ print(f"rewrite_watch_upatch.py: {error}", file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/util/bpm_package.c b/util/bpm_package.cindex 59e806da..f02d80ad 100644--- a/util/bpm_package.c+++ b/util/bpm_package.c@@ -360,6 +360,132 @@ int bpm_pkg_read_member(const char *archive, const char *member,out, out_len, max);}+int bpm_pkg_visit_members(const char *archive, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx)+{+ gzFile gz = gzopen(archive, "rb");+ char root[256] = {};+ __u8 h[512];+ int rc = 0;++ if (!gz)+ return -errno;+ if (gzdirect(gz)) {+ gzclose(gz);+ return -EINVAL;+ }+ for (;;) {+ char name[PATH_MAX], rel[PATH_MAX], *slash;+ int n = gzread(gz, h, sizeof(h));+ __u64 size, remain, pad;+ size_t name_len, root_len;+ bool zero = true;+ int type;++ if (n == 0)+ break;+ if (n != (int)sizeof(h)) {+ rc = -EINVAL;+ break;+ }+ for (size_t i = 0; i < sizeof(h); i++) {+ if (h[i]) {+ zero = false;+ break;+ }+ }+ if (zero)+ break;+ if (!memchr(h, '\0', 100) || h[345] ||+ bpm_tar_octal((char *)h + 124, 12, &size)) {+ rc = -EINVAL;+ break;+ }+ strscpy(name, (char *)h, sizeof(name));+ type = h[156] ? h[156] : '0';+ name_len = strlen(name);+ if (type == '5' && name_len && name[name_len - 1] == '/')+ name[--name_len] = '\0';+ if (!bpm_archive_rel_ok(name)) {+ rc = -EINVAL;+ break;+ }+ if (!root[0]) {+ slash = strchr(name, '/');+ if ((!slash && type != '5') || (slash && slash == name) ||+ (slash ? (size_t)(slash - name) : name_len) >=+ sizeof(root)) {+ rc = -EINVAL;+ break;+ }+ root_len = slash ? (size_t)(slash - name) : name_len;+ memcpy(root, name, root_len);+ root[root_len] = '\0';+ }+ root_len = strlen(root);+ if (strncmp(name, root, root_len) ||+ (name[root_len] && name[root_len] != '/')) {+ rc = -EINVAL;+ break;+ }+ if (package_dir && strcmp(root, package_dir)) {+ rc = -EINVAL;+ break;+ }+ if (type != '0' && type != '5') {+ rc = -EPERM;+ break;+ }+ strscpy(rel, name + root_len + (name[root_len] == '/'),+ sizeof(rel));+ if (!*rel) {+ if (type != '5') {+ rc = -EINVAL;+ break;+ }+ } else if (!bpm_archive_rel_ok(rel)) {+ rc = -EINVAL;+ break;+ } else if (visit) {+ rc = visit(ctx, rel, (char)type);+ if (rc)+ break;+ }+ remain = size;+ while (remain) {+ __u8 discard[65536];+ size_t want = remain > sizeof(discard) ?+ sizeof(discard) : (size_t)remain;++ n = gzread(gz, discard, (__u32)want);+ if (n <= 0) {+ rc = -EINVAL;+ goto done;+ }+ remain -= (size_t)n;+ }+ pad = (512 - (size % 512)) % 512;+ while (pad) {+ __u8 discard[512];+ size_t want = pad > sizeof(discard) ?+ sizeof(discard) : (size_t)pad;++ n = gzread(gz, discard, (__u32)want);+ if (n <= 0) {+ rc = -EINVAL;+ goto done;+ }+ pad -= (size_t)n;+ }+ }+ if (!root[0])+ rc = -EINVAL;+done:+ if (gzclose(gz) != Z_OK && !rc)+ rc = -EINVAL;+ return rc;+}+static X509 *read_x509_memory(const __u8 *body, size_t len){BIO *b;diff --git a/util/bpm_package.h b/util/bpm_package.hindex a0b3cf3e..eb92f650 100644--- a/util/bpm_package.h+++ b/util/bpm_package.h@@ -45,6 +45,12 @@ int bpm_verify_cms(const __u8 *payload, size_t payload_len,int bpm_tar_octal(const char *p, size_t n, __u64 *out);bool bpm_archive_rel_ok(const char *name);+typedef int (*bpm_pkg_member_fn)(void *ctx, const char *member, char type);++/* Visit validated package-relative ustar members without extracting them. */+int bpm_pkg_visit_members(const char *archive, const char *package_dir,+ bpm_pkg_member_fn visit, void *ctx);+/** Read one member of a gzip'd ustar .bee into an xmalloc'd buffer of* out_len + 1 bytes. member is relative to the single top-level packagediff --git a/util/json.c b/util/json.cindex c2c9847f..e0e11fed 100644--- a/util/json.c+++ b/util/json.c@@ -143,6 +143,13 @@ void json_obj_open_key(struct shirudo_json_emit *e, const char *key)enter(e);}+void json_obj_value_open(struct shirudo_json_emit *e)+{+ json_value_begin(e);+ put(e, '{');+ enter(e);+}+void json_obj_close(struct shirudo_json_emit *e){put(e, '}');@@ -158,6 +165,29 @@ void json_arr_open(struct shirudo_json_emit *e, const char *key)enter(e);}+void json_arr_open_value(struct shirudo_json_emit *e)+{+ json_value_begin(e);+ put(e, '[');+ enter(e);+}++void json_key(struct shirudo_json_emit *e, const char *key)+{+ sep(e);+ put_string(e, key);+ put(e, ':');+ e->value_pending = true;+}++void json_value_begin(struct shirudo_json_emit *e)+{+ if (e->value_pending)+ e->value_pending = false;+ else+ sep(e);+}+void json_arr_close(struct shirudo_json_emit *e){put(e, ']');@@ -222,6 +252,22 @@ void json_str(struct shirudo_json_emit *e, const char *val)put_string(e, val);}+void json_str_value(struct shirudo_json_emit *e, const char *val)+{+ json_value_begin(e);+ put_string(e, val);+}++void json_raw_value(struct shirudo_json_emit *e, const char *value,+ size_t value_len)+{+ size_t i;++ json_value_begin(e);+ for (i = 0; i < value_len && !e->err; i++)+ put(e, value[i]);+}+void json_raw(struct shirudo_json_emit *e, const char *value,size_t value_len){diff --git a/util/json.h b/util/json.hindex 21e60585..c8fe4e81 100644--- a/util/json.h+++ b/util/json.h@@ -8,6 +8,7 @@#ifndef SHIRUDO_JSON_H#define SHIRUDO_JSON_H+#include <stdbool.h>#include <stddef.h>#include <shirudo/misc.h>@@ -29,6 +30,7 @@ struct shirudo_json_emit {int err; /* sticky; -ENOSPC, -EILSEQ, -E2BIG */__u32 depth; /* open-container nesting */__u32 nonempty; /* bit d set: container at depth d has a member */+ bool value_pending;};/*@@ -38,9 +40,14 @@ struct shirudo_json_emit {*/void json_obj_open(struct shirudo_json_emit *e);void json_obj_open_key(struct shirudo_json_emit *e, const char *key);+/* Value containers and scalars consume a pending json_key or array slot. */+void json_obj_value_open(struct shirudo_json_emit *e);void json_obj_close(struct shirudo_json_emit *e);void json_arr_open(struct shirudo_json_emit *e, const char *key);+void json_arr_open_value(struct shirudo_json_emit *e);void json_arr_close(struct shirudo_json_emit *e);+void json_key(struct shirudo_json_emit *e, const char *key);+void json_value_begin(struct shirudo_json_emit *e);void json_kv_string(struct shirudo_json_emit *e,const char *key, const char *val);void json_kv_int(struct shirudo_json_emit *e,@@ -52,6 +59,9 @@ void json_kv_null(struct shirudo_json_emit *e, const char *key);void json_kv_raw(struct shirudo_json_emit *e, const char *key,const char *value, size_t value_len);void json_str(struct shirudo_json_emit *e, const char *val);+void json_str_value(struct shirudo_json_emit *e, const char *val);+void json_raw_value(struct shirudo_json_emit *e, const char *value,+ size_t value_len);void json_raw(struct shirudo_json_emit *e, const char *value,size_t value_len);diff --git a/util/upatch.c b/util/upatch.cindex 1de98826..7215fcc6 100644--- a/util/upatch.c+++ b/util/upatch.c@@ -193,6 +193,35 @@ static void parse_decoders(struct shirudo_upatch *u)u->nr_decoders = nr_decoders;}+static int upatch_parse(const void *data, size_t size,+ struct shirudo_upatch *out)+{+ int rc;++ memset(out, 0, sizeof(*out));+ if (!data || !size || size > SHIRUDO_UPATCH_FILE_MAX)+ return -EINVAL;+ out->map = data;+ out->map_size = size;+ rc = parse_header(out->map, out->map_size, &out->hdr);+ if (rc)+ goto err;+ rc = validate_bounds(&out->hdr, out->map_size);+ if (rc)+ goto err;+ parse_decoders(out);+ return 0;+err:+ memset(out, 0, sizeof(*out));+ return rc;+}++int upatch_open_memory(const void *data, size_t size,+ struct shirudo_upatch *out)+{+ return upatch_parse(data, size, out);+}+int upatch_open(const char *path, struct shirudo_upatch *out){struct stat st;@@ -225,29 +254,23 @@ int upatch_open(const char *path, struct shirudo_upatch *out)if (m == MAP_FAILED)return -errno;- out->map = m;- out->map_size = (size_t)st.st_size;-- rc = parse_header(out->map, out->map_size, &out->hdr);- if (rc != 0) {- upatch_close(out);+ rc = upatch_parse(m, (size_t)st.st_size, out);+ if (rc) {+ munmap(m, (size_t)st.st_size);return rc;}- rc = validate_bounds(&out->hdr, out->map_size);- if (rc != 0) {- upatch_close(out);- return rc;- }- parse_decoders(out);+ out->mapped = true;return 0;}void upatch_close(struct shirudo_upatch *u){- if (u->map) {+ if (u->map && u->mapped)munmap((void *)u->map, u->map_size);+ if (u->map) {u->map = NULL;u->map_size = 0;+ u->mapped = false;u->decoder_blob = NULL;u->decoder_blob_len = 0;u->nr_decoders = 0;diff --git a/util/upatch.h b/util/upatch.hindex eb05f9db..592d9ad3 100644--- a/util/upatch.h+++ b/util/upatch.h@@ -22,6 +22,7 @@ struct shirudo_upatch {struct shirudo_upatch_header hdr; /* host byte order */const __u8 *map;size_t map_size;+ bool mapped;const struct shirudo_upatch_decoder_blob *decoder_blob;__u32 decoder_blob_len;__u32 nr_decoders;@@ -45,6 +46,8 @@ struct upatch_decoder_view {* decides whether to emit user-facing diagnostics.*/int upatch_open(const char *path, struct shirudo_upatch *out);+int upatch_open_memory(const void *data, size_t size,+ struct shirudo_upatch *out);void upatch_close(struct shirudo_upatch *u);/*diff --git a/util/upatch_rodata.c b/util/upatch_rodata.cnew file mode 100644index 00000000..0e37d724--- /dev/null+++ b/util/upatch_rodata.c@@ -0,0 +1,914 @@+// SPDX-License-Identifier: BSD-2-Clause+/* Copyright (c) 2026 Authors of shirudo */++#include <endian.h>+#include <errno.h>+#include <linux/bpf.h>+#include <linux/btf.h>+#include <stdarg.h>+#include <stdbool.h>+#include <stdio.h>+#include <string.h>+#include <unistd.h>++#include <bpf/btf.h>+#include <bpf/libbpf.h>++#include <shirudo/misc.h>+#include <shirudo/string.h>++#include "io.h"+#include "json.h"+#include "log.h"+#include "macros.h"+#include "malloc.h"+#include "upatch.h"+#include "upatch_rodata.h"++#define RODATA_MAPS_MAX 64+#define RODATA_JSON_MAX_DEPTH 8++struct rodata_map {+ char name[BPF_OBJ_NAME_LEN + 1];+ __u32 value_size;+ bool found;+};++struct rodata_view {+ struct btf *btf;+ const __u8 *bytes;+ __u32 data_offset;+ __u32 size;+ __u32 type_id;+};++static bool loader_lddw(const struct bpf_insn *insns, size_t count,+ size_t i, __u8 reg, __u32 *value)+{+ if (i + 1 >= count ||+ insns[i].code != (BPF_LD | BPF_DW | BPF_IMM) ||+ insns[i].dst_reg != reg ||+ insns[i].src_reg != BPF_PSEUDO_MAP_IDX_VALUE ||+ insns[i].off || insns[i].imm || insns[i + 1].code ||+ insns[i + 1].off)+ return false;+ *value = (__u32)insns[i + 1].imm;+ return true;+}++static bool sys_bpf_call(const struct bpf_insn *insns, size_t count,+ size_t i, __u32 *cmd, __u32 *attr, __u32 *attr_size)+{+ if (i < 4 || i >= count ||+ insns[i].code != (BPF_JMP | BPF_CALL) ||+ insns[i].imm != BPF_FUNC_sys_bpf ||+ insns[i - 4].code != (BPF_ALU64 | BPF_MOV | BPF_K) ||+ insns[i - 4].dst_reg != BPF_REG_1 ||+ insns[i - 3].code != (BPF_LD | BPF_DW | BPF_IMM) ||+ !loader_lddw(insns, count, i - 3, BPF_REG_2, attr) ||+ insns[i - 1].code != (BPF_ALU64 | BPF_MOV | BPF_K) ||+ insns[i - 1].dst_reg != BPF_REG_3)+ return false;+ *cmd = (__u32)insns[i - 4].imm;+ *attr_size = (__u32)insns[i - 1].imm;+ return true;+}++static bool map_create_slot(const struct bpf_insn *insns, size_t count,+ size_t call, size_t next_call, __u32 *slot)+{+ size_t i;++ for (i = call + 1; i + 2 < next_call; i++) {+ __u32 off;++ if (loader_lddw(insns, count, i, BPF_REG_1, &off) &&+ insns[i + 2].code == (BPF_STX | BPF_W | BPF_MEM) &&+ insns[i + 2].dst_reg == BPF_REG_1 &&+ insns[i + 2].src_reg == BPF_REG_7 &&+ !insns[i + 2].off && !(off % sizeof(__u32)) &&+ off / sizeof(__u32) < RODATA_MAPS_MAX) {+ *slot = off / sizeof(__u32);+ return true;+ }+ }+ return false;+}++static bool map_update_slot(const struct bpf_insn *insns, size_t count,+ size_t call, __u32 attr, __u32 *slot)+{+ size_t start = call > 48 ? call - 48 : 0;+ size_t i;+ __u32 map_fd_off = attr + offsetof(union bpf_attr, map_fd);++ for (i = start; i + 5 < call; i++) {+ __u32 fd_array_off, dest_off;++ if (!loader_lddw(insns, count, i, BPF_REG_2, &fd_array_off) ||+ insns[i + 2].code != (BPF_LDX | BPF_W | BPF_MEM) ||+ insns[i + 2].dst_reg != BPF_REG_0 ||+ insns[i + 2].src_reg != BPF_REG_2 || insns[i + 2].off ||+ !loader_lddw(insns, count, i + 3, BPF_REG_1, &dest_off) ||+ dest_off != map_fd_off ||+ insns[i + 5].code != (BPF_STX | BPF_W | BPF_MEM) ||+ insns[i + 5].dst_reg != BPF_REG_1 ||+ insns[i + 5].src_reg != BPF_REG_0 || insns[i + 5].off ||+ fd_array_off % sizeof(__u32) ||+ fd_array_off / sizeof(__u32) >= RODATA_MAPS_MAX)+ continue;+ *slot = fd_array_off / sizeof(__u32);+ return true;+ }+ return false;+}++static bool map_update_value(const struct bpf_insn *insns, size_t count,+ size_t call, __u32 attr, __u32 *value_off)+{+ size_t start = call > 24 ? call - 24 : 0;+ size_t i;+ __u32 value_field = attr + offsetof(union bpf_attr, value);++ for (i = start; i + 4 < call; i++) {+ __u32 source_off, dest_off;++ if (!loader_lddw(insns, count, i, BPF_REG_0, &source_off) ||+ !loader_lddw(insns, count, i + 2, BPF_REG_1, &dest_off) ||+ dest_off != value_field ||+ insns[i + 4].code != (BPF_STX | BPF_DW | BPF_MEM) ||+ insns[i + 4].dst_reg != BPF_REG_1 ||+ insns[i + 4].src_reg != BPF_REG_0 || insns[i + 4].off)+ continue;+ *value_off = source_off;+ return true;+ }+ return false;+}++static bool map_name_rodata(const char *name)+{+ static const char suffix[] = ".rodata";+ size_t name_len = strlen(name), suffix_len = sizeof(suffix) - 1;++ return name_len >= suffix_len &&+ !strcmp(name + name_len - suffix_len, suffix);+}++static int find_rodata_data(const struct shirudo_upatch *u,+ const struct btf *btf, __u32 datasec_id,+ struct rodata_view *view)+{+ const struct btf_type *sec = btf__type_by_id(btf, datasec_id);+ const struct bpf_insn *insns = upatch_loader(u);+ const __u8 *data = upatch_data(u);+ struct rodata_map maps[RODATA_MAPS_MAX] = {};+ size_t count = u->hdr.loader_insns_len / sizeof(*insns), i;+ __u32 sec_size;+ int rc = -ENODATA;++ if (!sec || BTF_INFO_KIND(sec->info) != BTF_KIND_DATASEC ||+ u->hdr.loader_insns_len % sizeof(*insns))+ return -EINVAL;+ sec_size = sec->size;+ for (i = 4; i < count; i++) {+ __u32 cmd, attr_off, attr_size;++ if (!sys_bpf_call(insns, count, i, &cmd, &attr_off,+ &attr_size))+ continue;+ if (cmd == BPF_MAP_CREATE) {+ union bpf_attr attr = {};+ __u32 end, next;+ char name[BPF_OBJ_NAME_LEN + 1];++ if (attr_size > sizeof(attr) ||+ attr_size < offsetof(union bpf_attr, map_name) ++ BPF_OBJ_NAME_LEN ||+ attr_off > u->hdr.data_len ||+ attr_size > u->hdr.data_len - attr_off)+ return -EINVAL;+ memcpy(&attr, data + attr_off, attr_size);+ memcpy(name, attr.map_name, BPF_OBJ_NAME_LEN);+ name[BPF_OBJ_NAME_LEN] = '\0';+ end = (__u32)count;+ for (next = (__u32)i + 1; next < count; next++) {+ __u32 ignored_cmd, ignored_attr, ignored_size;++ if (sys_bpf_call(insns, count, next, &ignored_cmd,+ &ignored_attr, &ignored_size)) {+ end = next;+ break;+ }+ }+ if (map_name_rodata(name)) {+ __u32 slot;++ if (!map_create_slot(insns, count, i, end, &slot))+ return -EOPNOTSUPP;+ maps[slot].value_size = attr.value_size;+ maps[slot].found = true;+ strscpy(maps[slot].name, name,+ sizeof(maps[slot].name));+ }+ } else if (cmd == BPF_MAP_UPDATE_ELEM) {+ __u32 slot, value_off;++ if (!map_update_slot(insns, count, i, attr_off, &slot) ||+ !map_update_value(insns, count, i, attr_off,+ &value_off))+ continue;+ if (!maps[slot].found)+ continue;+ if (maps[slot].value_size != sec_size ||+ value_off > u->hdr.data_len ||+ maps[slot].value_size > u->hdr.data_len - value_off)+ return -EINVAL;+ view->bytes = data + value_off;+ view->data_offset = value_off;+ view->size = sec_size;+ view->type_id = datasec_id;+ return 0;+ }+ }+ return rc;+}++static int btf_rodata_btf(const struct shirudo_upatch *u,+ struct rodata_view *view)+{+ const __u8 *data = upatch_data(u);+ struct btf *found = NULL;+ __u32 found_id = 0;+ size_t i;++ for (i = 0; i + sizeof(struct btf_header) <= u->hdr.data_len; i++) {+ struct btf_header hdr;+ __u32 end, type_end, str_end, layout_end;+ struct btf *btf;+ __s32 id;++ if (data[i] != (BTF_MAGIC & 0xff) ||+ data[i + 1] != (BTF_MAGIC >> 8))+ continue;+ memcpy(&hdr, data + i, sizeof(hdr));+ hdr.hdr_len = le32toh(hdr.hdr_len);+ hdr.type_off = le32toh(hdr.type_off);+ hdr.type_len = le32toh(hdr.type_len);+ hdr.str_off = le32toh(hdr.str_off);+ hdr.str_len = le32toh(hdr.str_len);+ hdr.layout_off = le32toh(hdr.layout_off);+ hdr.layout_len = le32toh(hdr.layout_len);+ if (hdr.hdr_len < offsetof(struct btf_header, layout_off) ||+ hdr.hdr_len > u->hdr.data_len - i)+ continue;+ if (hdr.hdr_len < sizeof(hdr)) {+ hdr.layout_off = 0;+ hdr.layout_len = 0;+ }+ type_end = hdr.type_off + hdr.type_len;+ str_end = hdr.str_off + hdr.str_len;+ layout_end = hdr.layout_off + hdr.layout_len;+ if (type_end < hdr.type_off || str_end < hdr.str_off ||+ layout_end < hdr.layout_off)+ continue;+ end = hdr.hdr_len + (type_end > str_end ? type_end : str_end);+ if (layout_end > end - hdr.hdr_len)+ end = hdr.hdr_len + layout_end;+ if (end < hdr.hdr_len || end > u->hdr.data_len - i)+ continue;+ btf = btf__new(data + i, end);+ if (libbpf_get_error(btf))+ continue;+ id = btf__find_by_name_kind(btf, ".rodata", BTF_KIND_DATASEC);+ if (id <= 0) {+ btf__free(btf);+ continue;+ }+ if (found) {+ btf__free(btf);+ btf__free(found);+ return -E2BIG;+ }+ found = btf;+ found_id = (__u32)id;+ }+ if (!found)+ return -ENOENT;+ view->btf = found;+ return find_rodata_data(u, found, found_id, view);+}++int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,+ struct shirudo_rodata_range ranges[2])+{+ static const char *const names[] = {+ "obs_watch_v4", "obs_watch_v6",+ };+ struct rodata_view view = {};+ const struct btf_type *sec;+ const struct btf_var_secinfo *vars;+ __u32 found = 0, i;+ int rc;++ if (!u || !ranges)+ return -EINVAL;+ rc = btf_rodata_btf(u, &view);+ if (rc) {+ btf__free(view.btf);+ return rc;+ }+ sec = btf__type_by_id(view.btf, view.type_id);+ if (!sec || BTF_INFO_KIND(sec->info) != BTF_KIND_DATASEC) {+ rc = -EINVAL;+ goto out;+ }+ vars = (const struct btf_var_secinfo *)(sec + 1);+ for (i = 0; i < BTF_INFO_VLEN(sec->info); i++) {+ const struct btf_type *var;+ const char *name;+ __u32 j, offset, size;++ var = btf__type_by_id(view.btf, vars[i].type);+ if (!var || BTF_INFO_KIND(var->info) != BTF_KIND_VAR)+ continue;+ name = btf__name_by_offset(view.btf, var->name_off);+ if (!name)+ continue;+ for (j = 0; j < ARRAY_SIZE(names); j++) {+ if (strcmp(name, names[j]))+ continue;+ if (found & (1u << j)) {+ rc = -EEXIST;+ goto out;+ }+ offset = vars[i].offset;+ size = vars[i].size;+ if (offset > view.size || size > view.size - offset ||+ view.data_offset > u->hdr.data_len ||+ offset > u->hdr.data_len - view.data_offset ||+ size > u->hdr.data_len - view.data_offset - offset) {+ rc = -EINVAL;+ goto out;+ }+ ranges[j].offset = view.data_offset + offset;+ ranges[j].size = size;+ found |= 1u << j;+ }+ }+ rc = found == (1u << ARRAY_SIZE(names)) - 1 ? 0 : -ENOENT;+out:+ btf__free(view.btf);+ return rc;+}++static __u32 btf_unwrap(const struct btf *btf, __u32 id)+{+ const struct btf_type *t;+ __u32 i;++ for (i = 0; i < RODATA_JSON_MAX_DEPTH; i++) {+ t = btf__type_by_id(btf, id);+ if (!t)+ return 0;+ switch (BTF_INFO_KIND(t->info)) {+ case BTF_KIND_TYPEDEF:+ case BTF_KIND_VOLATILE:+ case BTF_KIND_CONST:+ case BTF_KIND_RESTRICT:+ case BTF_KIND_TYPE_TAG:+ id = t->type;+ break;+ default:+ return id;+ }+ }+ return 0;+}++static int append_type_name(const struct btf *btf, __u32 id, char *buf,+ size_t cap, size_t *off, __u32 depth)+{+ const struct btf_type *t;+ const char *name;+ __u16 kind;+ int n;++ if (depth >= RODATA_JSON_MAX_DEPTH || *off >= cap)+ return -E2BIG;+ t = btf__type_by_id(btf, id);+ if (!t)+ return -EINVAL;+ kind = BTF_INFO_KIND(t->info);+ name = btf__name_by_offset(btf, t->name_off);+ if (kind == BTF_KIND_TYPEDEF && name && name[0]) {+ n = strsprintf(buf + *off, cap - *off, "%s", name);+ if (n < 0)+ return -ENOSPC;+ *off += (size_t)n;+ return 0;+ }+ if (kind == BTF_KIND_TYPEDEF || kind == BTF_KIND_VOLATILE ||+ kind == BTF_KIND_CONST || kind == BTF_KIND_RESTRICT ||+ kind == BTF_KIND_TYPE_TAG)+ return append_type_name(btf, t->type, buf, cap, off, depth + 1);+ if (kind == BTF_KIND_ARRAY) {+ const struct btf_array *a = (const struct btf_array *)(t + 1);++ if (append_type_name(btf, a->type, buf, cap, off, depth + 1))+ return -EINVAL;+ n = strsprintf(buf + *off, cap - *off, "[%u]", a->nelems);+ if (n < 0)+ return -ENOSPC;+ *off += (size_t)n;+ return 0;+ }+ if (kind == BTF_KIND_PTR) {+ if (append_type_name(btf, t->type, buf, cap, off, depth + 1))+ return -EINVAL;+ if (*off + 2 > cap)+ return -ENOSPC;+ memcpy(buf + *off, " *", 2);+ *off += 2;+ return 0;+ }+ if (name && name[0]) {+ n = strsprintf(buf + *off, cap - *off, "%s%s",+ kind == BTF_KIND_STRUCT ? "struct " :+ kind == BTF_KIND_UNION ? "union " :+ kind == BTF_KIND_ENUM ? "enum " : "", name);+ } else {+ const char *fallback = "?";++ switch (kind) {+ case BTF_KIND_INT:+ fallback = "integer";+ break;+ case BTF_KIND_STRUCT:+ fallback = "struct";+ break;+ case BTF_KIND_UNION:+ fallback = "union";+ break;+ case BTF_KIND_ENUM:+ case BTF_KIND_ENUM64:+ fallback = "enum";+ break;+ case BTF_KIND_FLOAT:+ fallback = "float";+ break;+ case BTF_KIND_FWD:+ fallback = "forward declaration";+ break;+ }+ n = strsprintf(buf + *off, cap - *off, "%s", fallback);+ }+ if (n < 0)+ return -ENOSPC;+ *off += (size_t)n;+ return 0;+}++static int json_number(struct shirudo_json_emit *e, __u64 value,+ bool is_signed)+{+ char number[32];+ int n;++ if (is_signed)+ n = strsprintf(number, sizeof(number), "%lld", (__s64)value);+ else+ n = strsprintf(number, sizeof(number), "%llu",+ (__u64)value);+ if (n < 0)+ return n;+ json_raw_value(e, number, (size_t)n);+ return e->err;+}++static int btf_integer(const struct btf_type *t, const void *bytes,+ size_t size, __u64 *value, bool *is_signed,+ bool *is_bool)+{+ __u32 enc, bits, bit_off;+ __u32 i;+ __u64 result = 0;++ if (t->size > size || !t->size || t->size > sizeof(result))+ return -EINVAL;+ enc = *(__u32 *)(t + 1);+ bits = BTF_INT_BITS(enc);+ bit_off = BTF_INT_OFFSET(enc);+ if (!bits || bits > 64 || bit_off + bits > t->size * 8)+ return -EINVAL;+ for (i = 0; i < bits; i++) {+ __u32 b = bit_off + i;++ if (((const __u8 *)bytes)[b / 8] & (1u << (b % 8)))+ result |= (__u64)1 << i;+ }+ *is_signed = (BTF_INT_ENCODING(enc) & BTF_INT_SIGNED) != 0;+ *is_bool = (BTF_INT_ENCODING(enc) & BTF_INT_BOOL) != 0;+ if (*is_signed && bits < 64 && (result & ((__u64)1 << (bits - 1))))+ result |= ~(((__u64)1 << bits) - 1);+ *value = result;+ return 0;+}++static void json_hex(struct shirudo_json_emit *e, const void *bytes,+ size_t size)+{+ static const char hex[] = "0123456789abcdef";+ char *text;+ const __u8 *p = bytes;+ size_t i, cap;++ if (size > (SHIRUDO_JSON_MAX_BYTES - 3) / 2) {+ e->err = -E2BIG;+ return;+ }+ cap = size * 2 + 3;+ text = xmalloc(cap);+ if (!text) {+ e->err = -ENOMEM;+ return;+ }+ text[0] = '0';+ text[1] = 'x';+ for (i = 0; i < size; i++) {+ text[2 + i * 2] = hex[p[i] >> 4];+ text[3 + i * 2] = hex[p[i] & 0x0f];+ }+ text[2 + size * 2] = '\0';+ json_str_value(e, text);+ xfree(text, cap);+}++static int json_btf_value(struct shirudo_json_emit *e, const struct btf *btf,+ __u32 type_id, const __u8 *bytes, size_t size,+ __u32 depth)+{+ const struct btf_type *t;+ __u16 kind;+ int rc;++ if (depth >= RODATA_JSON_MAX_DEPTH || !type_id || !bytes)+ return -EINVAL;+ type_id = btf_unwrap(btf, type_id);+ t = btf__type_by_id(btf, type_id);+ if (!t)+ return -EINVAL;+ kind = BTF_INFO_KIND(t->info);+ if (kind == BTF_KIND_INT) {+ __u64 value;+ bool sign, boolean;++ rc = btf_integer(t, bytes, size, &value, &sign, &boolean);+ if (rc)+ return rc;+ if (boolean)+ json_raw_value(e, value ? "true" : "false", value ? 4 : 5);+ else+ return json_number(e, value, sign);+ return e->err;+ }+ if (kind == BTF_KIND_ENUM || kind == BTF_KIND_ENUM64) {+ __u64 value = 0;+ bool sign = BTF_INFO_KFLAG(t->info);+ __u32 i, vlen = BTF_INFO_VLEN(t->info);+ const char *enum_name = NULL;++ if (!t->size || t->size > sizeof(value) || t->size > size)+ return -EINVAL;+ for (i = 0; i < t->size; i++)+ value |= (__u64)bytes[i] << (i * 8);+ if (sign && t->size < sizeof(value) &&+ (value & ((__u64)1 << (t->size * 8 - 1))))+ value |= ~(((__u64)1 << (t->size * 8)) - 1);+ if (kind == BTF_KIND_ENUM) {+ const struct btf_enum *vals = (const struct btf_enum *)(t + 1);+ __u32 v = (__u32)value;++ for (i = 0; i < vlen; i++)+ if ((__u32)vals[i].val == v) {+ enum_name = btf__name_by_offset(btf,+ vals[i].name_off);+ break;+ }+ } else {+ const struct btf_enum64 *vals =+ (const struct btf_enum64 *)(t + 1);++ for (i = 0; i < vlen; i++) {+ __u64 v = (__u64)vals[i].val_lo32 |+ (__u64)vals[i].val_hi32 << 32;++ if (v == value) {+ enum_name = btf__name_by_offset(btf,+ vals[i].name_off);+ break;+ }+ }+ }+ json_obj_value_open(e);+ if (enum_name && enum_name[0])+ json_kv_string(e, "name", enum_name);+ json_key(e, "value");+ json_number(e, value, sign);+ json_obj_close(e);+ return e->err;+ }+ if (kind == BTF_KIND_STRUCT) {+ const struct btf_member *m = (const struct btf_member *)(t + 1);+ __u32 vlen = BTF_INFO_VLEN(t->info), i;++ json_obj_value_open(e);+ for (i = 0; i < vlen && !e->err; i++) {+ __u32 bit_off = BTF_INFO_KFLAG(t->info) ?+ BTF_MEMBER_BIT_OFFSET(m[i].offset) : m[i].offset;+ __u32 bit_size = BTF_INFO_KFLAG(t->info) ?+ BTF_MEMBER_BITFIELD_SIZE(m[i].offset) : 0;+ __u32 byte_off = bit_off / 8;+ const char *name = btf__name_by_offset(btf,+ m[i].name_off);+ __s64 member_size = btf__resolve_size(btf, m[i].type);+ char fallback[24];++ if (!name || !name[0]) {+ if (strsprintf(fallback, sizeof(fallback), "member_%u",+ i) < 0)+ return -EINVAL;+ name = fallback;+ }+ json_key(e, name);+ if (bit_size) {+ __u32 n = (bit_off % 8 + bit_size + 7) / 8;+ __u32 j;+ const struct btf_type *member_type =+ btf__type_by_id(btf,+ btf_unwrap(btf, m[i].type));+ __u32 enc;+ __u64 val = 0;+ bool sign;++ if (bit_size > 64 || byte_off + n > size ||+ !member_type ||+ BTF_INFO_KIND(member_type->info) != BTF_KIND_INT)+ return -EINVAL;+ enc = *(__u32 *)(member_type + 1);+ sign = BTF_INT_ENCODING(enc) & BTF_INT_SIGNED;+ for (j = 0; j < bit_size; j++) {+ __u32 pos = bit_off + j;++ if (bytes[pos / 8] & (1u << (pos % 8)))+ val |= (__u64)1 << j;+ }+ if (sign && bit_size < 64 &&+ (val & ((__u64)1 << (bit_size - 1))))+ val |= ~(((__u64)1 << bit_size) - 1);+ json_number(e, val, sign);+ } else {+ if (member_size < 0 || byte_off > size ||+ (size_t)member_size > size - byte_off)+ return -EINVAL;+ rc = json_btf_value(e, btf, m[i].type,+ bytes + byte_off,+ (size_t)member_size,+ depth + 1);+ if (rc)+ return rc;+ }+ }+ json_obj_close(e);+ return e->err;+ }+ if (kind == BTF_KIND_ARRAY) {+ const struct btf_array *a = (const struct btf_array *)(t + 1);+ __s64 elem_size = btf__resolve_size(btf, a->type);+ __u32 i;++ if (elem_size < 0)+ return -EINVAL;+ if (elem_size && (__u64)elem_size * a->nelems > size)+ return -EINVAL;+ json_arr_open_value(e);+ for (i = 0; i < a->nelems && !e->err; i++) {+ if (!elem_size)+ return -EINVAL;+ rc = json_btf_value(e, btf, a->type,+ bytes + (size_t)i * elem_size,+ (size_t)elem_size, depth + 1);+ if (rc)+ return rc;+ }+ json_arr_close(e);+ return e->err;+ }+ if (kind == BTF_KIND_PTR) {+ __u64 value = 0;+ char text[32];+ int n;++ if (size > sizeof(value))+ return -EINVAL;+ memcpy(&value, bytes, size);+ n = strsprintf(text, sizeof(text), "0x%llx",+ (__u64)value);+ if (n < 0)+ return n;+ json_str_value(e, text);+ return e->err;+ }+ json_hex(e, bytes, size);+ return e->err;+}++static const char *btf_var_name(const struct btf *btf,+ const struct btf_var_secinfo *var)+{+ const struct btf_type *t = btf__type_by_id(btf, var->type);++ return t && BTF_INFO_KIND(t->info) == BTF_KIND_VAR ?+ btf__name_by_offset(btf, t->name_off) : NULL;+}++static int btf_var_type(const struct btf *btf,+ const struct btf_var_secinfo *var, __u32 *type_id)+{+ const struct btf_type *t = btf__type_by_id(btf, var->type);++ if (!t || BTF_INFO_KIND(t->info) != BTF_KIND_VAR)+ return -EINVAL;+ *type_id = t->type;+ return 0;+}++static void print_text(void *ctx, const char *fmt, va_list args)+{+ FILE *fp = ctx;++ vfprintf(fp, fmt, args);+}++static int print_rodata_text(const struct shirudo_upatch *u,+ const char *path, const struct rodata_view *view)+{+ struct btf_dump_type_data_opts opts = {+ .sz = sizeof(opts),+ .indent_str = " ",+ .emit_zeroes = true,+ .emit_strings = true,+ };+ struct btf_dump *dump;+ const struct btf_type *sec = btf__type_by_id(view->btf,+ view->type_id);+ const struct btf_var_secinfo *vars =+ (const struct btf_var_secinfo *)(sec + 1);+ __u32 i, vlen = BTF_INFO_VLEN(sec->info);+ char name[SHIRUDO_UPATCH_NAME_MAX + 1];+ int rc = 0;++ memcpy(name, u->hdr.name, SHIRUDO_UPATCH_NAME_MAX);+ name[SHIRUDO_UPATCH_NAME_MAX] = '\0';+ printf("upatch %s (%s) .rodata: %u bytes at data+%u, file+%u\n",+ name, path, view->size, view->data_offset,+ u->hdr.data_off + view->data_offset);+ dump = btf_dump__new(view->btf, print_text, stdout, NULL);+ if (libbpf_get_error(dump))+ return -EINVAL;+ for (i = 0; i < vlen; i++) {+ __u32 type_id;+ const char *var_name = btf_var_name(view->btf, &vars[i]);+ char type[256] = {};+ size_t type_off = 0;++ if (!var_name || !var_name[0] ||+ btf_var_type(view->btf, &vars[i], &type_id)) {+ rc = -EINVAL;+ goto out;+ }+ rc = append_type_name(view->btf, type_id, type,+ sizeof(type), &type_off, 0);+ if (rc)+ goto out;+ if (vars[i].offset > view->size ||+ vars[i].size > view->size - vars[i].offset) {+ rc = -EINVAL;+ goto out;+ }+ printf("\n%s: %s, size=%u, rodata+%u, data+%u, file+%u = ",+ var_name, type, vars[i].size, vars[i].offset,+ view->data_offset + vars[i].offset,+ u->hdr.data_off + view->data_offset + vars[i].offset);+ rc = btf_dump__dump_type_data(dump, type_id,+ view->bytes + vars[i].offset,+ vars[i].size, &opts);+ if (rc < 0)+ goto out;+ putchar('\n');+ }+ putchar('\n');+ btf_dump__free(dump);+ return 0;+out:+ btf_dump__free(dump);+ return rc;+}++static int print_rodata_json(const struct shirudo_upatch *u,+ const char *path, const struct rodata_view *view)+{+ const struct btf_type *sec = btf__type_by_id(view->btf,+ view->type_id);+ const struct btf_var_secinfo *vars =+ (const struct btf_var_secinfo *)(sec + 1);+ char name[SHIRUDO_UPATCH_NAME_MAX + 1];+ char *buf = xmalloc(SHIRUDO_JSON_MAX_BYTES);+ struct shirudo_json_emit e = {};+ __u32 i, vlen = BTF_INFO_VLEN(sec->info);+ int rc = 0;++ if (!buf)+ return -ENOMEM;+ e.buf = buf;+ e.cap = SHIRUDO_JSON_MAX_BYTES;+ memcpy(name, u->hdr.name, SHIRUDO_UPATCH_NAME_MAX);+ name[SHIRUDO_UPATCH_NAME_MAX] = '\0';+ json_obj_open(&e);+ json_kv_int(&e, "schema", 1);+ json_kv_string(&e, "upatch", name);+ json_kv_string(&e, "path", path);+ json_kv_string(&e, "section", ".rodata");+ json_kv_int(&e, "size", view->size);+ json_kv_int(&e, "data_offset", view->data_offset);+ json_kv_int(&e, "file_offset", u->hdr.data_off + view->data_offset);+ json_arr_open(&e, "variables");+ for (i = 0; i < vlen && !e.err; i++) {+ const char *var_name = btf_var_name(view->btf, &vars[i]);+ char type[256] = {};+ size_t type_off = 0;+ __u32 type_id;++ if (!var_name || !var_name[0] ||+ btf_var_type(view->btf, &vars[i], &type_id)) {+ rc = -EINVAL;+ break;+ }+ rc = append_type_name(view->btf, type_id, type,+ sizeof(type), &type_off, 0);+ if (rc)+ break;+ if (vars[i].offset > view->size ||+ vars[i].size > view->size - vars[i].offset) {+ rc = -EINVAL;+ break;+ }+ json_obj_open(&e);+ json_kv_string(&e, "name", var_name);+ json_kv_string(&e, "type", type);+ json_kv_int(&e, "size", vars[i].size);+ json_kv_int(&e, "rodata_offset", vars[i].offset);+ json_kv_int(&e, "data_offset",+ view->data_offset + vars[i].offset);+ json_kv_int(&e, "file_offset",+ u->hdr.data_off + view->data_offset + vars[i].offset);+ json_key(&e, "value");+ rc = json_btf_value(&e, view->btf, type_id,+ view->bytes + vars[i].offset,+ vars[i].size, 0);+ json_obj_close(&e);+ if (rc)+ break;+ }+ json_arr_close(&e);+ json_obj_close(&e);+ if (!rc && e.err)+ rc = e.err;+ if (!rc)+ rc = write_complete(STDOUT_FILENO, buf, e.len);+ if (!rc)+ rc = write_complete(STDOUT_FILENO, "\n", 1);+ if (rc == -ENOSPC)+ pr_err("BTF JSON output exceeds %u bytes", SHIRUDO_JSON_MAX_BYTES);+ xfree(buf, SHIRUDO_JSON_MAX_BYTES);+ return rc;+}++int upatch_rodata_print(const struct shirudo_upatch *u, const char *path,+ bool json)+{+ struct rodata_view view = {};+ int rc;++ if (upatch_is_unload(u))+ return -EINVAL;+ rc = btf_rodata_btf(u, &view);+ if (rc)+ goto out;+ rc = json ? print_rodata_json(u, path, &view) :+ print_rodata_text(u, path, &view);+out:+ if (view.btf)+ btf__free(view.btf);+ return rc;+}diff --git a/util/upatch_rodata.h b/util/upatch_rodata.hnew file mode 100644index 00000000..b1e3a69c--- /dev/null+++ b/util/upatch_rodata.h@@ -0,0 +1,25 @@+/* SPDX-License-Identifier: BSD-2-Clause */+/*+ * Copyright (c) 2026 Authors of shirudo+ *+ * Read the signed .rodata initial value from a gen_loader upatch.+ */++#ifndef SHIRUDO_UTIL_UPATCH_RODATA_H+#define SHIRUDO_UTIL_UPATCH_RODATA_H++#include <stdbool.h>++#include "upatch.h"++struct shirudo_rodata_range {+ __u32 offset;+ __u32 size;+};++int upatch_rodata_print(const struct shirudo_upatch *u, const char *path,+ bool json);+int upatch_rodata_watch_ranges(const struct shirudo_upatch *u,+ struct shirudo_rodata_range ranges[2]);++#endif /* SHIRUDO_UTIL_UPATCH_RODATA_H */