| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "bpf-util.h" |
| 4 |
#include "bpf-link.h" |
| 5 |
#include "serialize.h" |
| 6 |
|
| 7 |
bool bpf_can_link_program(struct bpf_program *prog) { |
| 8 |
_cleanup_(bpf_link_freep) struct bpf_link *link = NULL; |
| 9 |
|
| 10 |
assert(prog); |
| 11 |
|
| 12 |
if (dlopen_bpf(LOG_DEBUG) < 0) |
| 13 |
return false; |
| 14 |
|
| 15 |
/* Pass invalid cgroup fd intentionally. */ |
| 16 |
link = sym_bpf_program__attach_cgroup(prog, /* cgroup_fd= */ -1); |
| 17 |
|
| 18 |
/* EBADF indicates that bpf_link is supported by kernel. */ |
| 19 |
return bpf_get_error_translated(link) == -EBADF; |
| 20 |
} |
| 21 |
|
| 22 |
bool bpf_can_link_lsm_program(struct bpf_program *prog) { |
| 23 |
_cleanup_(bpf_link_freep) struct bpf_link *link = NULL; |
| 24 |
|
| 25 |
assert(prog); |
| 26 |
|
| 27 |
if (dlopen_bpf(LOG_DEBUG) < 0) |
| 28 |
return false; |
| 29 |
|
| 30 |
link = sym_bpf_program__attach_lsm(prog); |
| 31 |
|
| 32 |
/* If bpf_program__attach_lsm fails the resulting value stores libbpf error code instead of memory |
| 33 |
* pointer. That is the case when the helper is called on architectures where BPF trampoline (hence |
| 34 |
* BPF_LSM_MAC attach type) is not supported. */ |
| 35 |
return bpf_get_error_translated(link) == 0; |
| 36 |
} |
| 37 |
|
| 38 |
int bpf_serialize_link(FILE *f, FDSet *fds, const char *key, struct bpf_link *link) { |
| 39 |
assert(key); |
| 40 |
|
| 41 |
if (!link) |
| 42 |
return -ENOENT; |
| 43 |
|
| 44 |
if (bpf_get_error_translated(link) != 0) |
| 45 |
return -EINVAL; |
| 46 |
|
| 47 |
return serialize_fd(f, fds, key, sym_bpf_link__fd(link)); |
| 48 |
} |
| 49 |
|
| 50 |
struct bpf_link* bpf_link_free(struct bpf_link *link) { |
| 51 |
/* If libbpf wasn't dlopen()ed, sym_bpf_link__destroy might be unresolved (NULL), so let's not try to |
| 52 |
* call it if link is NULL. link might also be a non-null "error pointer", but such a value can only |
| 53 |
* originate from a call to libbpf, but that means that libbpf is available, and we can let |
| 54 |
* bpf_link__destroy() handle it. */ |
| 55 |
if (link) |
| 56 |
(void) sym_bpf_link__destroy(link); |
| 57 |
|
| 58 |
return NULL; |
| 59 |
} |
| 60 |
|
| 61 |
struct ring_buffer* bpf_ring_buffer_free(struct ring_buffer *rb) { |
| 62 |
if (rb) /* See the comment in bpf_link_free(). */ |
| 63 |
sym_ring_buffer__free(rb); |
| 64 |
|
| 65 |
return NULL; |
| 66 |
} |