Dynamic pointers
Subsystems (5)
v5 cover Dynamic pointers
This patchset implements the basics of dynamic pointers in bpf.
A dynamic pointer (struct bpf_dynptr) is a pointer that stores extra metadata alongside the address it points to. This abstraction is useful in bpf given that every memory access in a bpf program must be safe. The verifier and bpf helper functions can use the metadata to enforce safety guarantees for things such as dynamically sized strings and kernel heap allocations.
From the program side, the bpf_dynptr is an opaque struct and the verifier will enforce that its contents are never written to by the program. It can only be written to through specific bpf helper functions.
There are several uses cases for dynamic pointers in bpf programs. Some examples include: dynamically sized ringbuf reservations without extra memcpys, dynamic string parsing and memory comparisons, dynamic memory allocations that can be persisted in maps, and dynamic + ergonomic parsing of sk_buff and xdp_md packet data.
At a high-level, the patches are as follows:
1/6 - Adds verifier support for dynptrs
2/6 - Adds bpf_dynptr_from_mem (local dynptr)
3/6 - Adds dynptr support for ring buffers
4/6 - Adds bpf_dynptr_read and bpf_dynptr_write
5/6 - Adds dynptr data slices (ptr to the dynptr data)
6/6 - Tests to check that the verifier rejects invalid cases and passes valid ones
This is the first dynptr patchset in a larger series. The next series of patches will add dynptrs that support dynamic memory allocations that can also be persisted in maps, support for parsing packet data through dynptrs, convenience helpers for using dynptrs as iterators, and more helper functions for interacting with strings and memory dynamically.
Changelog:
----------
v4 -> v5:
v4:
https://lore.kernel.org/bpf/[email protected]/
* Remove malloc dynptr; this will be part of the 2nd patchset while we figure out memory accounting
* For data slices, only set the register's ref_obj_id to dynptr_id (Alexei)
* Tidying (eg remove "inline", move offset checking to "check_func_arg_reg_off") (David)
* Add a few new test cases, remove malloc-only ones.
v3 -> v4:
v3:
https://lore.kernel.org/bpf/[email protected]/
1/6 - Change mem ptr + size check to use more concise inequality expression (David + Andrii)
2/6 - Add check for meta->uninit_dynptr_regno not already set (Andrii)
Move DYNPTR_TYPE_FLAG_MASK to include/linux/bpf.h (Andrii)
3/6 - Remove four underscores for invoking BPF_CALL (Andrii)
Add __BPF_TYPE_FLAG_MAX and use it for __BPF_TYPE_LAST_FLAG (Andrii)
4/6 - Fix capacity to be bpf_dynptr size value in check_off_len (Andrii)
Change -EINVAL to -E2BIG if len + offset is out of bounds (Andrii)
5/6 - Add check for only 1 dynptr arg for dynptr data function (Andrii) 6/6 - For ringbuf map, set max_entries from userspace (Andrii)
Use err ?: ... for interactring with dynptr APIs (Andrii) Define array_map2 for add_dynptr_to_map2 test where value is a struct
with an embedded dynptr
Remove ref id from missing_put_callback message, since on different
environments, ref id is not always = 1
v2 -> v3:
v2:
https://lore.kernel.org/bpf/[email protected]/
* Reorder patches (move ringbuffer patch to be right after the verifier +
* malloc
dynptr patchset)
* Remove local type dynptrs (Andrii + Alexei)
* Mark stack slot as STACK_MISC after any writes into a dynptr instead of
* explicitly prohibiting writes (Alexei)
* Pass number of slots, not memory size to is_spi_bounds_valid (Kumar)
* Check reference leaks by adding dynptr id to state->refs instead of checking stack slots (Alexei)
v1 -> v2:
v1: https://lore.kernel.org/bpf/[email protected]/
1/7 -
* Remove ARG_PTR_TO_MAP_VALUE_UNINIT alias and use ARG_PTR_TO_MAP_VALUE | MEM_UNINIT directly (Andrii)
* Drop arg_type_is_mem_ptr() wrapper function (Andrii)
2/7 -
* Change name from MEM_RELEASE to OBJ_RELEASE (Andrii)
* Use meta.release_ref instead of ref_obj_id != 0 to determine whether to release reference (Kumar)
* Drop type_is_release_mem() wrapper function (Andrii)
3/7 -
* Add checks for nested dynptrs edge-cases, which could lead to corrupt
* writes of the dynptr stack variable.
* Add u64 flags to bpf_dynptr_from_mem() and bpf_dynptr_alloc() (Andrii)
* Rename from bpf_malloc/bpf_free to bpf_dynptr_alloc/bpf_dynptr_put (Alexei)
* Support alloc flag __GFP_ZERO (Andrii)
* Reserve upper 8 bits in dynptr size and offset fields instead of reserving just the upper 4 bits (Andrii)
* Allow dynptr zero-slices (Andrii)
* Use the highest bit for is_rdonly instead of the 28th bit (Andrii)
* Rename check_* functions to is_* functions for better readability (Andrii)
* Add comment for code that checks the spi bounds (Andrii)
4/7 -
* Fix doc description for bpf_dynpt_read (Toke)
* Move bpf_dynptr_check_off_len() from function patch 1 to here (Andrii)
5/7 -
* When finding the id for the dynptr to associate the data slice with, look for dynptr arg instead of assuming it is BPF_REG_1.
6/7 -
* Add __force when casting from unsigned long to void * (kernel test
* robot)
* Expand on docs for ringbuf dynptr APIs (Andrii)
7/7 -
* Use table approach for defining test programs and error messages
* (Andrii)
* Print out full log if there’s an error (Andrii)
* Use bpf_object__find_program_by_name() instead of specifying program name as a string (Andrii)
* Add 6 extra cases: invalid_nested_dynptrs1, invalid_nested_dynptrs2, invalid_ref_mem1, invalid_ref_mem2, zero_slice_access,
and test_alloc_zero_bytes
* Add checking for edge cases (eg allocing with invalid flags)
Joanne Koong (6):
bpf: Add verifier support for dynptrs
bpf: Add bpf_dynptr_from_mem for local dynptrs
bpf: Dynptr support for ring buffers
bpf: Add bpf_dynptr_read and bpf_dynptr_write
bpf: Add dynptr data slices
selftests/bpf: Dynptr tests
include/linux/bpf.h | 45 ++ include/linux/bpf_verifier.h | 20 + include/uapi/linux/bpf.h | 83 +++ kernel/bpf/helpers.c | 177 ++++++ kernel/bpf/ringbuf.c | 78 +++ kernel/bpf/verifier.c | 271 +++++++- scripts/bpf_doc.py | 2 + tools/include/uapi/linux/bpf.h | 83 +++ .../testing/selftests/bpf/prog_tests/dynptr.c | 137 ++++ .../testing/selftests/bpf/progs/dynptr_fail.c | 588 ++++++++++++++++++ .../selftests/bpf/progs/dynptr_success.c | 164 +++++ 11 files changed, 1643 insertions(+), 5 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/dynptr.c create mode 100644 tools/testing/selftests/bpf/progs/dynptr_fail.c create mode 100644 tools/testing/selftests/bpf/progs/dynptr_success.c
Signature · 1 line
2.30.2
PATCH v5 1/6 bpf: Add verifier support for dynptrs
This patch adds the bulk of the verifier work for supporting dynamic pointers (dynptrs) in bpf.
A bpf_dynptr is opaque to the bpf program. It is a 16-byte structure defined internally as:
struct bpf_dynptr_kern {
void *data;
u32 size;
u32 offset;
} __aligned(8);The upper 8 bits of *size* is reserved (it contains extra metadata about read-only status and dynptr type). Consequently, a dynptr only supports memory less than 16 MB.
There are different types of dynptrs (eg malloc, ringbuf, ...). In this patchset, the most basic one, dynptrs to a bpf program's local memory, is added. For now only local memory that is of reg type PTR_TO_MAP_VALUE is supported.
In the verifier, dynptr state information will be tracked in stack slots. When the program passes in an uninitialized dynptr (ARG_PTR_TO_DYNPTR | MEM_UNINIT), the stack slots corresponding to the frame pointer where the dynptr resides at are marked STACK_DYNPTR. For helper functions that take in initialized dynptrs (eg bpf_dynptr_read + bpf_dynptr_write which are added later in this patchset), the verifier enforces that the dynptr has been initialized properly by checking that their corresponding stack slots have been marked as STACK_DYNPTR.
The 6th patch in this patchset adds test cases that the verifier should successfully reject, such as for example attempting to use a dynptr after doing a direct write into it inside the bpf program.
--- include/linux/bpf.h | 28 +++++ include/linux/bpf_verifier.h | 18 ++++ include/uapi/linux/bpf.h | 5 + kernel/bpf/verifier.c | 188 ++++++++++++++++++++++++++++++++- scripts/bpf_doc.py | 2 + tools/include/uapi/linux/bpf.h | 5 + 6 files changed, 243 insertions(+), 3 deletions(-)
include/linux/bpf.h +28 -0
@@ -392,10 +392,15 @@ enum bpf_type_flag {MEM_UNINIT =BIT (7 +BPF_BASE_TYPE_BITS ), +/* DYNPTR points to memory local to the bpf program. */ +DYNPTR_TYPE_LOCAL =BIT (8 +BPF_BASE_TYPE_BITS ), + __BPF_TYPE_FLAG_MAX, __BPF_TYPE_LAST_FLAG = __BPF_TYPE_FLAG_MAX - 1, }; +#define DYNPTR_TYPE_FLAG_MASK DYNPTR_TYPE_LOCAL +/* Max number of base types. */ #define BPF_BASE_TYPE_LIMIT (1UL << BPF_BASE_TYPE_BITS)
@@ -438,6 +443,7 @@ enum bpf_arg_type {ARG_PTR_TO_CONST_STR ,/* pointer to a null terminated read-only string */ ARG_PTR_TO_TIMER ,/* pointer to bpf_timer */ ARG_PTR_TO_KPTR ,/* pointer to referenced kptr */ +ARG_PTR_TO_DYNPTR ,/* pointer to bpf_dynptr. See bpf_type_flag for dynptr type */ __BPF_ARG_TYPE_MAX,/* Extended arg_types. */
@@ -2374,4 +2380,26 @@ int bpf_bprintf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args, u32 **bin_buf, u32 num_args);void bpf_bprintf_cleanup (void ); +/* the implementation of the opaque uapi struct bpf_dynptr */ +struct bpf_dynptr_kern { +void *data; +/* Size represents the number of usable bytes of dynptr data. +* If for example the offset is at 4 for a local dynptr whose data is +* of type u64, the number of usable bytes is 4. +* +* The upper 8 bits are reserved. It is as follows: +* Bits 0 - 23 = size +* Bits 24 - 30 = dynptr type +* Bit 31 = whether dynptr is read-only +*/ +u32 size; +u32 offset; +}__aligned(8) ; + +enum bpf_dynptr_type { +BPF_DYNPTR_TYPE_INVALID , +/* Points to memory that is local to the bpf program */ +BPF_DYNPTR_TYPE_LOCAL , +}; +#endif /* _LINUX_BPF_H */
include/linux/bpf_verifier.h +18 -0
@@ -72,6 +72,18 @@ struct bpf_reg_state {u32 mem_size;/* for PTR_TO_MEM | PTR_TO_MEM_OR_NULL */ +/* For dynptr stack slots */ +struct { +enum bpf_dynptr_type type; +/* A dynptr is 16 bytes so it takes up 2 stack slots. +* We need to track which slot is the first slot +* to protect against cases where the user may try to +* pass in an address starting at the second slot of the +* dynptr. +*/ +bool first_slot; + } dynptr; +/* Max size from any of the above. */ struct {unsigned long raw1;
@@ -174,9 +186,15 @@ enum bpf_stack_slot_type { STACK_SPILL, /* register spilled into stack */STACK_MISC ,/* BPF program wrote some data into this slot */ STACK_ZERO ,/* BPF program wrote constant zero */ +/* A dynptr is stored in this stack slot. The type of dynptr +* is stored in bpf_stack_state->spilled_ptr.dynptr.type +*/ + STACK_DYNPTR, };#define BPF_REG_SIZE 8/* size of eBPF register in bytes */ +#define BPF_DYNPTR_SIZE sizeof(struct bpf_dynptr_kern) +#define BPF_DYNPTR_NR_SLOTS (BPF_DYNPTR_SIZE / BPF_REG_SIZE)struct bpf_stack_state {struct bpf_reg_state spilled_ptr;
include/uapi/linux/bpf.h +5 -0
@@ -6521,6 +6521,11 @@ struct bpf_timer { __u64 :64 ; } __attribute__((aligned(8))); +struct bpf_dynptr { + __u64 :64; + __u64 :64; +} __attribute__((aligned (8 ))); +struct bpf_sysctl {__u32 write;/* Sysctl is being read (= 0) or written (= 1). * Allows 1,2,4-byte read, but no write.
kernel/bpf/verifier.c +185 -3
251 lines not on this page · raw message
scripts/bpf_doc.py +2 -0
@@ -633,6 +633,7 @@ class PrinterHelpers(Printer): 'struct socket', 'struct file', 'struct bpf_timer', + 'struct bpf_dynptr', ] known_types = { '...',
@@ -682,6 +683,7 @@ class PrinterHelpers(Printer): 'struct socket', 'struct file', 'struct bpf_timer', + 'struct bpf_dynptr', } mapped_types = { 'u8': '__u8',
tools/include/uapi/linux/bpf.h +5 -0
@@ -6521,6 +6521,11 @@ struct bpf_timer { __u64 :64 ; } __attribute__((aligned(8))); +struct bpf_dynptr { + __u64 :64; + __u64 :64; +} __attribute__((aligned (8 ))); +struct bpf_sysctl {__u32 write;/* Sysctl is being read (= 0) or written (= 1). * Allows 1,2,4-byte read, but no write.
Signature · 1 line
2.30.2
PATCH v5 2/6 bpf: Add bpf_dynptr_from_mem for local dynptrs
In reply to Joanne KoongThis patch adds a new api bpf_dynptr_from_mem:
long bpf_dynptr_from_mem(void *data, u32 size, u64 flags, struct bpf_dynptr *ptr);
which initializes a dynptr to point to a bpf program's local memory. For now only local memory that is of reg type PTR_TO_MAP_VALUE is supported.
--- include/uapi/linux/bpf.h | 12 +++++++ kernel/bpf/helpers.c | 65 ++++++++++++++++++++++++++++++++++ kernel/bpf/verifier.c | 6 ++++ tools/include/uapi/linux/bpf.h | 12 +++++++ 4 files changed, 95 insertions(+)
include/uapi/linux/bpf.h +12 -0
@@ -5172,6 +5172,17 @@ union bpf_attr {* Return * Map value associated to *key* on *cpu*, or **NULL** if no entry * was found or *cpu* is invalid. +* +* long bpf_dynptr_from_mem(void *data, u32 size, u64 flags, struct bpf_dynptr *ptr) +* Description +* Get a dynptr to local memory *data*. +* +* *data* must be a ptr to a map value. +* The maximum *size* supported is DYNPTR_MAX_SIZE. +* *flags* is currently unused. +* Return +* 0 on success, -E2BIG if the size exceeds DYNPTR_MAX_SIZE, +* -EINVAL if flags is not 0. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5370,6 +5381,7 @@ union bpf_attr {FN (ima_file_hash), \FN (kptr_xchg), \FN (map_lookup_percpu_elem), \ +FN (bpf_dynptr_from_mem), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +65 -0
77 lines not on this page · raw message
kernel/bpf/verifier.c +6 -0
@@ -5744,6 +5744,12 @@ static int check_reg_type(struct bpf_verifier_env *env, u32 regno,return -EACCES ; } } +if (base_type (arg_type) ==ARG_PTR_TO_MEM && (arg_type &DYNPTR_TYPE_LOCAL )) +if (reg->type !=PTR_TO_MAP_VALUE ) { +verbose (env,"Unsupported reg type %s for arg type ARG_PTR_TO_MEM with DYNPTR_TYPE_LOCAL set\n" , +reg_type_str (env, reg->type)); +return -EACCES ; + }return 0 ; }
tools/include/uapi/linux/bpf.h +12 -0
@@ -5172,6 +5172,17 @@ union bpf_attr {* Return * Map value associated to *key* on *cpu*, or **NULL** if no entry * was found or *cpu* is invalid. +* +* long bpf_dynptr_from_mem(void *data, u32 size, u64 flags, struct bpf_dynptr *ptr) +* Description +* Get a dynptr to local memory *data*. +* +* *data* must be a ptr to a map value. +* The maximum *size* supported is DYNPTR_MAX_SIZE. +* *flags* is currently unused. +* Return +* 0 on success, -E2BIG if the size exceeds DYNPTR_MAX_SIZE, +* -EINVAL if flags is not 0. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5370,6 +5381,7 @@ union bpf_attr {FN (ima_file_hash), \FN (kptr_xchg), \FN (map_lookup_percpu_elem), \ +FN (bpf_dynptr_from_mem), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
PATCH v5 3/6 bpf: Dynptr support for ring buffers
In reply to Joanne KoongCurrently, our only way of writing dynamically-sized data into a ring buffer is through bpf_ringbuf_output but this incurs an extra memcpy cost. bpf_ringbuf_reserve + bpf_ringbuf_commit avoids this extra memcpy, but it can only safely support reservation sizes that are statically known since the verifier cannot guarantee that the bpf program won’t access memory outside the reserved space.
The bpf_dynptr abstraction allows for dynamically-sized ring buffer reservations without the extra memcpy.
There are 3 new APIs:
long bpf_ringbuf_reserve_dynptr(void *ringbuf, u32 size, u64 flags, struct bpf_dynptr *ptr); void bpf_ringbuf_submit_dynptr(struct bpf_dynptr *ptr, u64 flags);
void bpf_ringbuf_discard_dynptr(struct bpf_dynptr *ptr, u64 flags);
These closely follow the functionalities of the original ringbuf APIs. For example, all ringbuffer dynptrs that have been reserved must be either submitted or discarded before the program exits.
--- include/linux/bpf.h | 15 ++++++- include/linux/bpf_verifier.h | 2 + include/uapi/linux/bpf.h | 35 +++++++++++++++ kernel/bpf/helpers.c | 14 ++++-- kernel/bpf/ringbuf.c | 78 ++++++++++++++++++++++++++++++++++ kernel/bpf/verifier.c | 52 +++++++++++++++++++++-- tools/include/uapi/linux/bpf.h | 35 +++++++++++++++ 7 files changed, 223 insertions(+), 8 deletions(-)
include/linux/bpf.h +14 -1
@@ -395,11 +395,14 @@ enum bpf_type_flag {/* DYNPTR points to memory local to the bpf program. */ DYNPTR_TYPE_LOCAL =BIT (8 +BPF_BASE_TYPE_BITS ), +/* DYNPTR points to a ringbuf record. */ +DYNPTR_TYPE_RINGBUF =BIT (9 +BPF_BASE_TYPE_BITS ), + __BPF_TYPE_FLAG_MAX, __BPF_TYPE_LAST_FLAG = __BPF_TYPE_FLAG_MAX - 1, }; -#define DYNPTR_TYPE_FLAG_MASK DYNPTR_TYPE_LOCAL +#define DYNPTR_TYPE_FLAG_MASK (DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF)/* Max number of base types. */ #define BPF_BASE_TYPE_LIMIT (1UL << BPF_BASE_TYPE_BITS)
@@ -2231,6 +2234,9 @@ extern const struct bpf_func_proto bpf_ringbuf_reserve_proto;extern const struct bpf_func_proto bpf_ringbuf_submit_proto;extern const struct bpf_func_proto bpf_ringbuf_discard_proto;extern const struct bpf_func_proto bpf_ringbuf_query_proto; +extern const struct bpf_func_proto bpf_ringbuf_reserve_dynptr_proto; +extern const struct bpf_func_proto bpf_ringbuf_submit_dynptr_proto; +extern const struct bpf_func_proto bpf_ringbuf_discard_dynptr_proto;extern const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto;extern const struct bpf_func_proto bpf_skc_to_tcp_sock_proto;extern const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto;
@@ -2400,6 +2406,13 @@ enum bpf_dynptr_type {BPF_DYNPTR_TYPE_INVALID ,/* Points to memory that is local to the bpf program */ BPF_DYNPTR_TYPE_LOCAL , +/* Underlying data is a ringbuf record */ + BPF_DYNPTR_TYPE_RINGBUF, }; +void bpf_dynptr_init (struct bpf_dynptr_kern *ptr,void *data, +enum bpf_dynptr_type type,u32 offset,u32 size); +void bpf_dynptr_set_null (struct bpf_dynptr_kern *ptr); +int bpf_dynptr_check_size (u32 size); +#endif /* _LINUX_BPF_H */
include/linux/bpf_verifier.h +2 -0
@@ -100,6 +100,8 @@ struct bpf_reg_state {* for the purpose of tracking that it's freed. * For PTR_TO_SOCKET this is used to share which pointers retain the * same reference to the socket, to determine proper reference freeing. +* For stack slots that are dynptrs, this is used to track references to +* the dynptr to determine proper reference freeing. */ u32 id;/* PTR_TO_SOCKET and PTR_TO_TCP_SOCK could be a ptr returned
include/uapi/linux/bpf.h +35 -0
@@ -5183,6 +5183,38 @@ union bpf_attr {* Return * 0 on success, -E2BIG if the size exceeds DYNPTR_MAX_SIZE, * -EINVAL if flags is not 0. +* +* long bpf_ringbuf_reserve_dynptr(void *ringbuf, u32 size, u64 flags, struct bpf_dynptr *ptr) +* Description +* Reserve *size* bytes of payload in a ring buffer *ringbuf* +* through the dynptr interface. *flags* must be 0. +* +* Please note that a corresponding bpf_ringbuf_submit_dynptr or +* bpf_ringbuf_discard_dynptr must be called on *ptr*, even if the +* reservation fails. This is enforced by the verifier. +* Return +* 0 on success, or a negative error in case of failure. +* +* void bpf_ringbuf_submit_dynptr(struct bpf_dynptr *ptr, u64 flags) +* Description +* Submit reserved ring buffer sample, pointed to by *data*, +* through the dynptr interface. This is a no-op if the dynptr is +* invalid/null. +* +* For more information on *flags*, please see +* 'bpf_ringbuf_submit'. +* Return +* Nothing. Always succeeds. +* +* void bpf_ringbuf_discard_dynptr(struct bpf_dynptr *ptr, u64 flags) +* Description +* Discard reserved ring buffer sample through the dynptr +* interface. This is a no-op if the dynptr is invalid/null. +* +* For more information on *flags*, please see +* 'bpf_ringbuf_discard'. +* Return +* Nothing. Always succeeds. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5382,6 +5414,9 @@ union bpf_attr {FN (kptr_xchg), \FN (map_lookup_percpu_elem), \FN (bpf_dynptr_from_mem), \ +FN (ringbuf_reserve_dynptr), \ +FN (ringbuf_submit_dynptr), \ +FN (ringbuf_discard_dynptr), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +10 -4
@@ -1423,13 +1423,13 @@ static void bpf_dynptr_set_type(struct bpf_dynptr_kern *ptr, enum bpf_dynptr_typ ptr->size |= type <<DYNPTR_TYPE_SHIFT ; } -static int bpf_dynptr_check_size (u32 size) +int bpf_dynptr_check_size (u32 size) {return size >DYNPTR_MAX_SIZE ? -E2BIG :0 ; } -static void bpf_dynptr_init (struct bpf_dynptr_kern *ptr,void *data, -enum bpf_dynptr_type type,u32 offset,u32 size) +void bpf_dynptr_init (struct bpf_dynptr_kern *ptr,void *data, +enum bpf_dynptr_type type,u32 offset,u32 size) { ptr->data = data; ptr->offset = offset;
@@ -1437,7 +1437,7 @@ static void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,bpf_dynptr_set_type (ptr, type); } -static void bpf_dynptr_set_null (struct bpf_dynptr_kern *ptr) +void bpf_dynptr_set_null (struct bpf_dynptr_kern *ptr) {memset (ptr,0 ,sizeof (*ptr)); }
@@ -1523,6 +1523,12 @@ bpf_base_func_proto(enum bpf_func_id func_id)return &bpf_ringbuf_discard_proto;case BPF_FUNC_ringbuf_query:return &bpf_ringbuf_query_proto; +case BPF_FUNC_ringbuf_reserve_dynptr: +return &bpf_ringbuf_reserve_dynptr_proto; +case BPF_FUNC_ringbuf_submit_dynptr: +return &bpf_ringbuf_submit_dynptr_proto; +case BPF_FUNC_ringbuf_discard_dynptr: +return &bpf_ringbuf_discard_dynptr_proto;case BPF_FUNC_for_each_map_elem:return &bpf_for_each_map_elem_proto;case BPF_FUNC_loop:
kernel/bpf/ringbuf.c +78 -0
81 lines not on this page · raw message
kernel/bpf/verifier.c +49 -3
113 lines not on this page · raw message
tools/include/uapi/linux/bpf.h +35 -0
@@ -5183,6 +5183,38 @@ union bpf_attr {* Return * 0 on success, -E2BIG if the size exceeds DYNPTR_MAX_SIZE, * -EINVAL if flags is not 0. +* +* long bpf_ringbuf_reserve_dynptr(void *ringbuf, u32 size, u64 flags, struct bpf_dynptr *ptr) +* Description +* Reserve *size* bytes of payload in a ring buffer *ringbuf* +* through the dynptr interface. *flags* must be 0. +* +* Please note that a corresponding bpf_ringbuf_submit_dynptr or +* bpf_ringbuf_discard_dynptr must be called on *ptr*, even if the +* reservation fails. This is enforced by the verifier. +* Return +* 0 on success, or a negative error in case of failure. +* +* void bpf_ringbuf_submit_dynptr(struct bpf_dynptr *ptr, u64 flags) +* Description +* Submit reserved ring buffer sample, pointed to by *data*, +* through the dynptr interface. This is a no-op if the dynptr is +* invalid/null. +* +* For more information on *flags*, please see +* 'bpf_ringbuf_submit'. +* Return +* Nothing. Always succeeds. +* +* void bpf_ringbuf_discard_dynptr(struct bpf_dynptr *ptr, u64 flags) +* Description +* Discard reserved ring buffer sample through the dynptr +* interface. This is a no-op if the dynptr is invalid/null. +* +* For more information on *flags*, please see +* 'bpf_ringbuf_discard'. +* Return +* Nothing. Always succeeds. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5382,6 +5414,9 @@ union bpf_attr {FN (kptr_xchg), \FN (map_lookup_percpu_elem), \FN (bpf_dynptr_from_mem), \ +FN (ringbuf_reserve_dynptr), \ +FN (ringbuf_submit_dynptr), \ +FN (ringbuf_discard_dynptr), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
PATCH v5 4/6 bpf: Add bpf_dynptr_read and bpf_dynptr_write
In reply to Joanne KoongThis patch adds two helper functions, bpf_dynptr_read and bpf_dynptr_write:
long bpf_dynptr_read(void *dst, u32 len, struct bpf_dynptr *src, u32 offset);
long bpf_dynptr_write(struct bpf_dynptr *dst, u32 offset, void *src, u32 len);
The dynptr passed into these functions must be valid dynptrs that have been initialized.
--- include/uapi/linux/bpf.h | 19 +++++++++ kernel/bpf/helpers.c | 78 ++++++++++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 19 +++++++++ 3 files changed, 116 insertions(+)
include/uapi/linux/bpf.h +19 -0
@@ -5215,6 +5215,23 @@ union bpf_attr {* 'bpf_ringbuf_discard'. * Return * Nothing. Always succeeds. +* +* long bpf_dynptr_read(void *dst, u32 len, struct bpf_dynptr *src, u32 offset) +* Description +* Read *len* bytes from *src* into *dst*, starting from *offset* +* into *src*. +* Return +* 0 on success, -E2BIG if *offset* + *len* exceeds the length +* of *src*'s data, -EINVAL if *src* is an invalid dynptr. +* +* long bpf_dynptr_write(struct bpf_dynptr *dst, u32 offset, void *src, u32 len) +* Description +* Write *len* bytes from *src* into *dst*, starting from *offset* +* into *dst*. +* Return +* 0 on success, -E2BIG if *offset* + *len* exceeds the length +* of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst* +* is a read-only dynptr. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5417,6 +5434,8 @@ union bpf_attr {FN (ringbuf_reserve_dynptr), \FN (ringbuf_submit_dynptr), \FN (ringbuf_discard_dynptr), \ +FN (dynptr_read), \ +FN (dynptr_write), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +78 -0
108 lines not on this page · raw message
tools/include/uapi/linux/bpf.h +19 -0
@@ -5215,6 +5215,23 @@ union bpf_attr {* 'bpf_ringbuf_discard'. * Return * Nothing. Always succeeds. +* +* long bpf_dynptr_read(void *dst, u32 len, struct bpf_dynptr *src, u32 offset) +* Description +* Read *len* bytes from *src* into *dst*, starting from *offset* +* into *src*. +* Return +* 0 on success, -E2BIG if *offset* + *len* exceeds the length +* of *src*'s data, -EINVAL if *src* is an invalid dynptr. +* +* long bpf_dynptr_write(struct bpf_dynptr *dst, u32 offset, void *src, u32 len) +* Description +* Write *len* bytes from *src* into *dst*, starting from *offset* +* into *dst*. +* Return +* 0 on success, -E2BIG if *offset* + *len* exceeds the length +* of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst* +* is a read-only dynptr. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5417,6 +5434,8 @@ union bpf_attr {FN (ringbuf_reserve_dynptr), \FN (ringbuf_submit_dynptr), \FN (ringbuf_discard_dynptr), \ +FN (dynptr_read), \ +FN (dynptr_write), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
PATCH v5 5/6 bpf: Add dynptr data slices
In reply to Joanne KoongThis patch adds a new helper function
void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len);
which returns a pointer to the underlying data of a dynptr. *len* must be a statically known value. The bpf program may access the returned data slice as a normal buffer (eg can do direct reads and writes), since the verifier associates the length with the returned pointer, and enforces that no out of bounds accesses occur.
--- include/linux/bpf.h | 4 ++++ include/uapi/linux/bpf.h | 12 ++++++++++++ kernel/bpf/helpers.c | 28 ++++++++++++++++++++++++++++ kernel/bpf/verifier.c | 27 +++++++++++++++++++++++++++ tools/include/uapi/linux/bpf.h | 12 ++++++++++++ 5 files changed, 83 insertions(+)
include/linux/bpf.h +4 -0
@@ -398,6 +398,9 @@ enum bpf_type_flag {/* DYNPTR points to a ringbuf record. */ DYNPTR_TYPE_RINGBUF =BIT (9 +BPF_BASE_TYPE_BITS ), +/* MEM is memory owned by a dynptr */ +MEM_DYNPTR =BIT (10 +BPF_BASE_TYPE_BITS ), + __BPF_TYPE_FLAG_MAX, __BPF_TYPE_LAST_FLAG = __BPF_TYPE_FLAG_MAX - 1, };
@@ -488,6 +491,7 @@ enum bpf_return_type {RET_PTR_TO_TCP_SOCK_OR_NULL =PTR_MAYBE_NULL |RET_PTR_TO_TCP_SOCK ,RET_PTR_TO_SOCK_COMMON_OR_NULL =PTR_MAYBE_NULL |RET_PTR_TO_SOCK_COMMON ,RET_PTR_TO_ALLOC_MEM_OR_NULL =PTR_MAYBE_NULL |MEM_ALLOC |RET_PTR_TO_ALLOC_MEM , +RET_PTR_TO_DYNPTR_MEM_OR_NULL =PTR_MAYBE_NULL |MEM_DYNPTR |RET_PTR_TO_ALLOC_MEM , RET_PTR_TO_BTF_ID_OR_NULL = PTR_MAYBE_NULL | RET_PTR_TO_BTF_ID,/* This must be the last entry. Its purpose is to ensure the enum is
include/uapi/linux/bpf.h +12 -0
@@ -5232,6 +5232,17 @@ union bpf_attr {* 0 on success, -E2BIG if *offset* + *len* exceeds the length * of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst* * is a read-only dynptr. +* +* void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len) +* Description +* Get a pointer to the underlying dynptr data. +* +* *len* must be a statically known value. The returned data slice +* is invalidated whenever the dynptr is invalidated. +* Return +* Pointer to the underlying dynptr data, NULL if the dynptr is +* read-only, if the dynptr is invalid, or if the offset and length +* is out of bounds. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5436,6 +5447,7 @@ union bpf_attr {FN (ringbuf_discard_dynptr), \FN (dynptr_read), \FN (dynptr_write), \ +FN (dynptr_data), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +28 -0
@@ -1549,6 +1549,32 @@ const struct bpf_func_proto bpf_dynptr_write_proto = { .arg4_type = ARG_CONST_SIZE_OR_ZERO, }; +BPF_CALL_3(bpf_dynptr_data, struct bpf_dynptr_kern *, ptr, u32, offset, u32, len) +{ +int err; + +if (!ptr->data) +return 0 ; + + err =bpf_dynptr_check_off_len (ptr, offset, len); +if (err) +return 0 ; + +if (bpf_dynptr_is_rdonly (ptr)) +return 0 ; + +return (unsigned long )(ptr->data + ptr->offset + offset); +} + +const struct bpf_func_proto bpf_dynptr_data_proto = { + .func = bpf_dynptr_data, + .gpl_only = false, + .ret_type =RET_PTR_TO_DYNPTR_MEM_OR_NULL , + .arg1_type =ARG_PTR_TO_DYNPTR , + .arg2_type =ARG_ANYTHING , + .arg3_type =ARG_CONST_ALLOC_SIZE_OR_ZERO , +}; +const struct bpf_func_proto bpf_get_current_task_proto__weak ;const struct bpf_func_proto bpf_get_current_task_btf_proto__weak ;const struct bpf_func_proto bpf_probe_read_user_proto__weak ;
@@ -1615,6 +1641,8 @@ bpf_base_func_proto(enum bpf_func_id func_id)return &bpf_dynptr_read_proto;case BPF_FUNC_dynptr_write:return &bpf_dynptr_write_proto; +case BPF_FUNC_dynptr_data: +return &bpf_dynptr_data_proto;default :break ; }
kernel/bpf/verifier.c +27 -0
@@ -567,6 +567,8 @@ static const char *reg_type_str(struct bpf_verifier_env *env,strncpy (prefix,"rdonly_" ,32 );if (type &MEM_ALLOC )strncpy (prefix,"alloc_" ,32 ); +if (type &MEM_DYNPTR ) +strncpy (prefix,"dynptr_" ,32 );if (type &MEM_USER )strncpy (prefix,"user_" ,32 );if (type &MEM_PERCPU )
@@ -5640,6 +5642,7 @@ static const struct bpf_reg_types mem_types = { PTR_TO_MAP_VALUE,PTR_TO_MEM , PTR_TO_MEM | MEM_ALLOC, + PTR_TO_MEM | MEM_DYNPTR, PTR_TO_BUF, }, };
@@ -5803,6 +5806,7 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,case PTR_TO_MEM :case PTR_TO_MEM |MEM_RDONLY :case PTR_TO_MEM |MEM_ALLOC : +case PTR_TO_MEM |MEM_DYNPTR :case PTR_TO_BUF :case PTR_TO_BUF |MEM_RDONLY :case SCALAR_VALUE :
@@ -5837,6 +5841,14 @@ int check_func_arg_reg_off(struct bpf_verifier_env *env,return __check_ptr_off_reg (env, reg, regno, fixed_off_ok); } +static u32 stack_slot_get_id (struct bpf_verifier_env *env,struct bpf_reg_state *reg) +{ +struct bpf_func_state *state =func (env, reg); +int spi =get_spi (reg->off); + +return state->stack[spi].spilled_ptr.id; +} +static int check_func_arg (struct bpf_verifier_env *env,u32 arg,struct bpf_call_arg_meta *meta,const struct bpf_func_proto *fn)
@@ -7383,6 +7395,21 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn regs[BPF_REG_0 ].id = id;/* For release_reference() */ regs[BPF_REG_0 ].ref_obj_id = id; + }else if (func_id == BPF_FUNC_dynptr_data) { +int dynptr_id =0 , i; + +/* Find the id of the dynptr we're acquiring a reference to */ +for (i =0 ; i <MAX_BPF_FUNC_REG_ARGS ; i++) { +if (arg_type_is_dynptr (fn->arg_type[i])) { +if (dynptr_id) { +verbose (env,"verifier internal error: multiple dynptr args in func\n" ); +return -EFAULT ; + } + dynptr_id =stack_slot_get_id (env, ®s[BPF_REG_1 + i]); + } + } +/* For release_reference() */ + regs[BPF_REG_0 ].ref_obj_id = dynptr_id; }do_refine_retval_range (regs, fn->ret_type, func_id, &meta);
tools/include/uapi/linux/bpf.h +12 -0
@@ -5232,6 +5232,17 @@ union bpf_attr {* 0 on success, -E2BIG if *offset* + *len* exceeds the length * of *dst*'s data, -EINVAL if *dst* is an invalid dynptr or if *dst* * is a read-only dynptr. +* +* void *bpf_dynptr_data(struct bpf_dynptr *ptr, u32 offset, u32 len) +* Description +* Get a pointer to the underlying dynptr data. +* +* *len* must be a statically known value. The returned data slice +* is invalidated whenever the dynptr is invalidated. +* Return +* Pointer to the underlying dynptr data, NULL if the dynptr is +* read-only, if the dynptr is invalid, or if the offset and length +* is out of bounds. */ #define __BPF_FUNC_MAPPER (FN ) \ FN(unspec), \
@@ -5436,6 +5447,7 @@ union bpf_attr {FN (ringbuf_discard_dynptr), \FN (dynptr_read), \FN (dynptr_write), \ +FN (dynptr_data), \/* */ /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.30.2
Re: [PATCH bpf-next v5 5/6] bpf: Add dynptr data slices
Quoted 11 lines · Joanne Koong
This patch adds a new helper function
void *bpf_dynptr_data(struct
bpf_dynptr*ptr, u32 offset, u32 len);which returns a pointer to the underlying data of a dynptr. *len* must be a statically known value. The bpf program may access the returned data slice as a normal buffer (eg can do direct reads and writes), since the verifier associates the length with the returned pointer, and enforces that no out of bounds accesses occur.
Signed-off-by Joanne Koong <[email protected]>
PATCH v5 6/6 selftests/bpf: Dynptr tests
In reply to Joanne KoongThis patch adds tests for dynptrs, which include cases that the verifier needs to reject (for example, a bpf_ringbuf_reserve_dynptr without a corresponding bpf_ringbuf_submit/discard_dynptr) as well as cases that should successfully pass.
--- .../testing/selftests/bpf/prog_tests/dynptr.c | 137 ++++ .../testing/selftests/bpf/progs/dynptr_fail.c | 588 ++++++++++++++++++ .../selftests/bpf/progs/dynptr_success.c | 164 +++++ 3 files changed, 889 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/dynptr.c create mode 100644 tools/testing/selftests/bpf/progs/dynptr_fail.c create mode 100644 tools/testing/selftests/bpf/progs/dynptr_success.c
tools/testing/selftests/bpf/prog_tests/dynptr.c new file +137 -0
@@ -0,0 +1,137 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2022 Facebook */ + +#include <test_progs.h> +#include "dynptr_fail.skel.h" +#include "dynptr_success.skel.h" + +static size_t log_buf_sz =1048576 ;/* 1 MB */ +static char obj_log_buf[1048576 ]; + +static struct { +const char *prog_name; +const char *expected_err_msg; +} dynptr_tests[] = { +/* failure cases */ + {"ringbuf_missing_release1" ,"Unreleased reference id=1" }, + {"ringbuf_missing_release2" ,"Unreleased reference id=2" }, + {"ringbuf_missing_release_callback" ,"Unreleased reference id" }, + {"use_after_invalid" ,"Expected an initialized dynptr as arg #3" }, + {"ringbuf_invalid_api" ,"type=dynptr_mem expected=alloc_mem" }, + {"add_dynptr_to_map1" ,"invalid indirect read from stack" }, + {"add_dynptr_to_map2" ,"invalid indirect read from stack" }, + {"data_slice_out_of_bounds_ringbuf" ,"value is outside of the allowed memory range" }, + {"data_slice_out_of_bounds_map_value" ,"value is outside of the allowed memory range" }, + {"data_slice_use_after_release" ,"invalid mem access 'scalar'" }, + {"data_slice_missing_null_check1" ,"invalid mem access 'dynptr_mem_or_null'" }, + {"data_slice_missing_null_check2" ,"invalid mem access 'dynptr_mem_or_null'" }, + {"invalid_helper1" ,"invalid indirect read from stack" }, + {"invalid_helper2" ,"Expected an initialized dynptr as arg #3" }, + {"invalid_write1" ,"Expected an initialized dynptr as arg #1" }, + {"invalid_write2" ,"Expected an initialized dynptr as arg #3" }, + {"invalid_write3" ,"Expected an initialized ringbuf dynptr as arg #1" }, + {"invalid_write4" ,"arg 1 is an unacquired reference" }, + {"invalid_read1" ,"invalid read from stack" }, + {"invalid_read2" ,"cannot pass in dynptr at an offset" }, + {"invalid_read3" ,"invalid read from stack" }, + {"invalid_read4" ,"invalid read from stack" }, + {"invalid_offset" ,"invalid write to stack" }, + {"global" ,"type=map_value expected=fp" }, + {"release_twice" ,"arg 1 is an unacquired reference" }, + {"release_twice_callback" ,"arg 1 is an unacquired reference" }, + {"dynptr_from_mem_invalid_api" , +"Unsupported reg type fp for arg type ARG_PTR_TO_MEM with DYNPTR_TYPE_LOCAL set" }, + +/* success cases */ + {"test_read_write" ,NULL }, + {"test_data_slice" ,NULL }, + {"test_ringbuf" ,NULL }, +}; + +static void verify_fail (const char *prog_name,const char *expected_err_msg) +{ +LIBBPF_OPTS (bpf_object_open_opts, opts); +struct bpf_program *prog; +struct dynptr_fail *skel; +int err; + + opts.kernel_log_buf = obj_log_buf; + opts.kernel_log_size = log_buf_sz; + opts.kernel_log_level =1 ; + + skel =dynptr_fail__open_opts (&opts); +if (!ASSERT_OK_PTR (skel,"dynptr_fail__open_opts" )) + goto cleanup; + + prog =bpf_object__find_program_by_name (skel->obj, prog_name); +if (!ASSERT_OK_PTR (prog,"bpf_object__find_program_by_name" )) + goto cleanup; + +bpf_program__set_autoload (prog, true); + +bpf_map__set_max_entries (skel->maps.ringbuf,getpagesize ()); + + err =dynptr_fail__load (skel); +if (!ASSERT_ERR (err,"unexpected load success" )) + goto cleanup; + +if (!ASSERT_OK_PTR (strstr (obj_log_buf, expected_err_msg),"expected_err_msg" )) { +fprintf (stderr,"Expected err_msg: %s\n" , expected_err_msg); +fprintf (stderr,"Verifier output: %s\n" , obj_log_buf); + } + +cleanup: +dynptr_fail__destroy (skel); +} + +static void verify_success (const char *prog_name) +{ +struct dynptr_success *skel; +struct bpf_program *prog; +struct bpf_link *link; + + skel =dynptr_success__open (); +if (!ASSERT_OK_PTR (skel,"dynptr_success__open" )) +return ; + + skel->bss->pid =getpid (); + +bpf_map__set_max_entries (skel->maps.ringbuf,getpagesize ()); + +dynptr_success__load (skel); +if (!ASSERT_OK_PTR (skel,"dynptr_success__load" )) + goto cleanup; + + prog =bpf_object__find_program_by_name (skel->obj, prog_name); +if (!ASSERT_OK_PTR (prog,"bpf_object__find_program_by_name" )) + goto cleanup; + + link =bpf_program__attach (prog); +if (!ASSERT_OK_PTR (link,"bpf_program__attach" )) + goto cleanup; + +usleep (1 ); + +ASSERT_EQ (skel->bss->err,0 ,"err" ); + +bpf_link__destroy (link); + +cleanup: +dynptr_success__destroy (skel); +} + +void test_dynptr (void ) +{ +int i; + +for (i =0 ; i <ARRAY_SIZE (dynptr_tests); i++) { +if (!test__start_subtest (dynptr_tests[i].prog_name)) +continue ; + +if (dynptr_tests[i].expected_err_msg) +verify_fail (dynptr_tests[i].prog_name, + dynptr_tests[i].expected_err_msg); +else +verify_success (dynptr_tests[i].prog_name); + } +}
tools/testing/selftests/bpf/progs/dynptr_fail.c new file +588 -0
588 lines not on this page · raw message
tools/testing/selftests/bpf/progs/dynptr_success.c new file +164 -0
164 lines not on this page · raw message
Signature · 1 line
2.30.2