| From | Wang Nan <> | Subject | [RFC PATCH v3 10/37] bpf tools: Check endianess and set swap flag according to EHDR | Date | Sun, 17 May 2015 10:56:35 +0000 |
| |
Check endianess according to EHDR to support loading eBPF objects into big endian machines. Code is taken from tools/perf/util/symbol-elf.c.
Signed-off-by: Wang Nan <wangnan0@huawei.com> --- tools/lib/bpf/libbpf.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+)
diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c index 43c16bc..a4910a8 100644 --- a/tools/lib/bpf/libbpf.c +++ b/tools/lib/bpf/libbpf.c @@ -69,6 +69,7 @@ void libbpf_set_print(int (*warn)(const char *format, ...), struct bpf_object { char *path; + bool needs_swap; /* * Information when doing elf related work. Only valid if fd @@ -109,6 +110,7 @@ static struct bpf_object *bpf_obj_alloc(const char *path) if (!obj) goto out; + obj->needs_swap = false; obj->elf.fd = -1; return obj; out: @@ -179,6 +181,31 @@ errout: return err; } +static int +bpf_obj_swap_init(struct bpf_object *obj) +{ + static unsigned int const endian = 1; + + obj->needs_swap = false; + + switch (obj->elf.ehdr.e_ident[EI_DATA]) { + case ELFDATA2LSB: + /* We are big endian, BPF obj is little endian. */ + if (*(unsigned char const *)&endian != 1) + obj->needs_swap = true; + return 0; + + case ELFDATA2MSB: + /* We are little endian, BPF obj is big endian. */ + if (*(unsigned char const *)&endian != 0) + obj->needs_swap = true; + return 0; + + default: + return -EINVAL; + } +} + struct bpf_object *bpf_open_object(const char *path) { struct bpf_object *obj; @@ -200,6 +227,8 @@ struct bpf_object *bpf_open_object(const char *path) if (bpf_obj_elf_init(obj)) goto out; + if (bpf_obj_swap_init(obj)) + goto out; return obj; -- 1.8.3.4
|