[RFC PATCH v2 09/37] tools lib bpf: check swap according to EHDR.

From: Wang Nan
Date: Fri May 15 2015 - 03:57:39 EST


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@xxxxxxxxxx>
---
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

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/