Created
July 4, 2026 21:04
-
-
Save fzakaria/bef27d2e21b0e36ffccda1cbf417b636 to your computer and use it in GitHub Desktop.
eBPF binfmt qemu aarch64 example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // SPDX-License-Identifier: GPL-2.0 | |
| /* | |
| * binfmt_misc 'B' (BPF) program: match aarch64 ELF binaries and choose the | |
| * interpreter (qemu-aarch64) dynamically via bpf_binprm_set_interp(). | |
| * | |
| * The program is given the BINPRM_BUF_SIZE file header as context. It inspects | |
| * the ELF header and, on a match, sets the interpreter and returns 1. This | |
| * makes the handler a superset of a traditional magic rule: the program both | |
| * decides the match and computes the interpreter path (it could equally derive | |
| * a path relative to the binary). | |
| */ | |
| #include <linux/bpf.h> | |
| #include <linux/types.h> | |
| #include <bpf/bpf_helpers.h> | |
| #define EI_CLASS 4 | |
| #define ELFCLASS64 2 | |
| #define EM_AARCH64 183 | |
| /* Classic helper (id 212) exposed to binfmt_misc 'B' programs. */ | |
| static long (*bpf_binprm_set_interp)(const void *path, __u32 len) = (void *)212; | |
| SEC("socket") | |
| int check_aarch64(void *ctx) | |
| { | |
| /* ctx points at the first BINPRM_BUF_SIZE bytes of the file. */ | |
| unsigned char magic[4]; | |
| unsigned char elf_class; | |
| unsigned short machine; | |
| const char interp[] = "/run/binfmt/aarch64-linux"; | |
| if (bpf_probe_read_kernel(&magic, sizeof(magic), ctx) < 0) | |
| return 0; | |
| if (magic[0] != 0x7f || magic[1] != 'E' || magic[2] != 'L' || magic[3] != 'F') | |
| return 0; | |
| if (bpf_probe_read_kernel(&elf_class, sizeof(elf_class), ctx + EI_CLASS) < 0) | |
| return 0; | |
| if (elf_class != ELFCLASS64) | |
| return 0; | |
| if (bpf_probe_read_kernel(&machine, sizeof(machine), ctx + 18) < 0) | |
| return 0; | |
| if (machine != EM_AARCH64) | |
| return 0; | |
| /* Match: choose the interpreter, then select this handler. */ | |
| bpf_binprm_set_interp(interp, sizeof(interp) - 1); | |
| return 1; | |
| } | |
| char LICENSE[] SEC("license") = "GPL"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment