projects/linux·blob master · refs

61 lines · 1.9 KiB

1// SPDX-License-Identifier: GPL-2.0
2/*
3 * binfmt_misc_ops handler for the selftest's fixed-interpreter case: match a
4 * 64-bit aarch64 ELF header from the prefetched buffer and route it to a fixed
5 * interpreter chosen by the program. This is the portable, self-contained
6 * equivalent of routing a foreign binary to an emulator: it matches
7 * programmatically and computes the interpreter, but points at a test binary
8 * the harness installs rather than a system emulator.
9 */
10#include "vmlinux.h"
11#include <bpf/bpf_helpers.h>
12#include <bpf/bpf_tracing.h>
13
14char _license[] SEC("license") = "GPL";
15
16#define EI_CLASS 4
17#define ELFCLASS64 2
18#define EM_AARCH64 183
19
20extern int bpf_binprm_set_interp(struct linux_binprm *bprm, const char *path,
21 size_t path__sz) __ksym;
22
23/*
24 * A magic-style decision needs nothing beyond the prefetched bprm->buf,
25 * even though the match program could read the file.
26 */
27SEC("struct_ops.s/match")
28bool BPF_PROG(bpf_interp_match, struct linux_binprm *bprm)
29{
30 __u16 machine;
31
32 if (bprm->buf[0] != 0x7f || bprm->buf[1] != 'E' ||
33 bprm->buf[2] != 'L' || bprm->buf[3] != 'F' ||
34 bprm->buf[EI_CLASS] != ELFCLASS64)
35 return false;
36
37 /* e_machine is a 16-bit little-endian field at offset 18. */
38 machine = (__u8)bprm->buf[18] | ((__u16)(__u8)bprm->buf[19] << 8);
39 return machine == EM_AARCH64;
40}
41
42SEC("struct_ops.s/load")
43int BPF_PROG(bpf_interp_load, struct linux_binprm *bprm)
44{
45 /*
46 * Keep the path on the (writable) stack: bpf_binprm_set_interp() takes
47 * a sized memory arg and the verifier rejects a read-only .rodata
48 * buffer for it. The harness installs the interpreter at this path.
49 */
50 char interp[] = "/tmp/binfmt_bpf_interp";
51
52 /* @path__sz includes the terminating NUL; 0 commits the selection. */
53 return bpf_binprm_set_interp(bprm, interp, sizeof(interp));
54}
55
56SEC(".struct_ops.link")
57struct binfmt_misc_ops bpf_interp = {
58 .match = (void *)bpf_interp_match,
59 .load = (void *)bpf_interp_load,
60 .name = "bpf_interp",
61};