Skip to contentSkip to conversation

Add a snprintf eBPF helper

PATCH In review Florent Revest 4 participants 23 messages Apr 19, 2021 – May 5, 2021

Subsystems (8)
Kselftest BPF Tracing BPF selftests +4 more subsystems
lore
Share & tools
lore
#0 lore raw

v5 cover Add a snprintf eBPF helper

We have a usecase where we want to audit symbol names (if available) in callback registration hooks. (ex: fentry/nf_register_net_hook)

A few months back, I proposed a bpf_kallsyms_lookup series but it was decided in the reviews that a more generic helper, bpf_snprintf, would be more useful.

This series implements the helper according to the feedback received in
https://lore.kernel.org/bpf/[email protected]/T/#u

- A new arg type guarantees the NULL-termination of string arguments and lets us pass format strings in only one arg
- A new helper is implemented using that guarantee. Because the format string is known at verification time, the format string validation is done by the verifier
- To implement a series of tests for bpf_snprintf, the logic for marshalling variadic args in a fixed-size array is reworked as per:
https://lore.kernel.org/bpf/[email protected]/T/#u

---
Changes in v5:
- Fixed the bpf_printf_buf_used counter logic in try_get_fmt_tmp_buf
- Added a couple of extra incorrect specifiers tests
- Call test_snprintf_single__destroy unconditionally
- Fixed a C++-style comment

---
Changes in v4:
- Moved bpf_snprintf, bpf_printf_prepare and bpf_printf_cleanup to kernel/bpf/helpers.c so that they get built without CONFIG_BPF_EVENTS
- Added negative test cases (various invalid format strings)
- Renamed put_fmt_tmp_buf() as bpf_printf_cleanup()
- Fixed a mistake that caused temporary buffers to be unconditionally freed in bpf_printf_prepare
- Fixed a mistake that caused missing 0 character to be ignored
- Fixed a warning about integer to pointer conversion
- Misc cleanups

---
Changes in v3:
- Simplified temporary buffer acquisition with try_get_fmt_tmp_buf()
- Made zero-termination check more consistent
- Allowed NULL output_buffer
- Simplified the BPF_CAST_FMT_ARG macro
- Three new test cases: number padding, simple string with no arg and string length extraction only with a NULL output buffer
- Clarified helper's description for edge cases (eg: str_size == 0)
- Lots of cosmetic changes

---
Changes in v2:
- Extracted the format validation/argument sanitization in a generic way for all printf-like helpers.
- bpf_snprintf's str_size can now be 0
- bpf_snprintf is now exposed to all BPF program types
- We now preempt_disable when using a per-cpu temporary buffer
- Addressed a few cosmetic changes

Florent Revest (6):
bpf: Factorize bpf_trace_printk and bpf_seq_printf
bpf: Add a ARG_PTR_TO_CONST_STR argument type
bpf: Add a bpf_snprintf helper
libbpf: Initialize the bpf_seq_printf parameters array field by field
libbpf: Introduce a BPF_SNPRINTF helper macro selftests/bpf: Add a series of tests for bpf_snprintf

 include/linux/bpf.h                           |  22 ++
 include/uapi/linux/bpf.h                      |  28 ++
 kernel/bpf/helpers.c                          | 306 ++++++++++++++
 kernel/bpf/verifier.c                         |  82 ++++
 kernel/trace/bpf_trace.c                      | 373 ++----------------
 tools/include/uapi/linux/bpf.h                |  28 ++
 tools/lib/bpf/bpf_tracing.h                   |  58 ++-
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++
 .../bpf/progs/test_snprintf_single.c          |  20 +
 10 files changed, 770 insertions(+), 345 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
Signature · 1 line
2.31.1.368.gbe11c130af-goog
#1 lore raw

PATCH v5 1/6 bpf: Factorize bpf_trace_printk and bpf_seq_printf

Two helpers (trace_printk and seq_printf) have very similar implementations of format string parsing and a third one is coming (snprintf). To avoid code duplication and make the code easier to maintain, this moves the operations associated with format string parsing (validation and argument sanitization) into one generic function.

The implementation of the two existing helpers already drifted quite a bit so unifying them entailed a lot of changes:

- bpf_trace_printk always expected fmt[fmt_size] to be the terminating NULL character, this is no longer true, the first 0 is terminating.
- bpf_trace_printk now supports %% (which produces the percentage char).
- bpf_trace_printk now skips width formating fields.
- bpf_trace_printk now supports the X modifier (capital hexadecimal).
- bpf_trace_printk now supports %pK, %px, %pB, %pi4, %pI4, %pi6 and %pI6
- argument casting on 32 bit has been simplified into one macro and using an enum instead of obscure int increments.

- bpf_seq_printf now uses bpf_trace_copy_string instead of strncpy_from_kernel_nofault and handles the %pks %pus specifiers.
- bpf_seq_printf now prints longs correctly on 32 bit architectures.

- both were changed to use a global per-cpu tmp buffer instead of one stack buffer for trace_printk and 6 small buffers for seq_printf.
- to avoid per-cpu buffer usage conflict, these helpers disable preemption while the per-cpu buffer is in use.
- both helpers now support the %ps and %pS specifiers to print symbols.

The implementation is also moved from bpf_trace.c to helpers.c because the upcoming bpf_snprintf helper will be made available to all BPF programs and will need it.

---
 include/linux/bpf.h      |  20 +++
 kernel/bpf/helpers.c     | 256 +++++++++++++++++++++++++++
 kernel/trace/bpf_trace.c | 371 ++++-----------------------------------
 3 files changed, 313 insertions(+), 334 deletions(-)
include/linux/bpf.h +20 -0
index ff8cd68c01b3..77d1d8c65b81 100644
@@ -2077,4 +2077,24 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
 struct btf_id_set;
 bool btf_id_set_contains(const struct btf_id_set *set, u32 id);
 
+enum bpf_printf_mod_type {
+	BPF_PRINTF_INT,
+	BPF_PRINTF_LONG,
+	BPF_PRINTF_LONG_LONG,
+};
+
+/* Workaround for getting va_list handling working with different argument type
+ * combinations generically for 32 and 64 bit archs.
+ */
+#define BPF_CAST_FMT_ARG(arg_nb, args, mod)				\
+	(mod[arg_nb] == BPF_PRINTF_LONG_LONG ||				\
+	 (mod[arg_nb] == BPF_PRINTF_LONG && __BITS_PER_LONG == 64)	\
+	  ? (u64)args[arg_nb]						\
+	  : (u32)args[arg_nb])
+
+int bpf_printf_prepare(char *fmt, u32 fmt_size, const u64 *raw_args,
+		       u64 *final_args, enum bpf_printf_mod_type *mod,
+		       u32 num_args);
+void bpf_printf_cleanup(void);
+
 #endif /* _LINUX_BPF_H */
kernel/bpf/helpers.c +256 -0

262 lines not on this page · raw message

kernel/trace/bpf_trace.c +37 -334

409 lines not on this page · raw message

Signature · 1 line
2.31.1.368.gbe11c130af-goog
#2 lore raw

PATCH v5 2/6 bpf: Add a ARG_PTR_TO_CONST_STR argument type

In reply to Florent Revest

This type provides the guarantee that an argument is going to be a const pointer to somewhere in a read-only map value. It also checks that this pointer is followed by a zero character before the end of the map value.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/verifier.c | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
include/linux/bpf.h +1 -0
index 77d1d8c65b81..c160526fc8bf 100644
@@ -309,6 +309,7 @@ enum bpf_arg_type {
 	ARG_PTR_TO_PERCPU_BTF_ID,	/* pointer to in-kernel percpu type */
 	ARG_PTR_TO_FUNC,	/* pointer to a bpf program function */
 	ARG_PTR_TO_STACK_OR_NULL,	/* pointer to stack or NULL */
+	ARG_PTR_TO_CONST_STR,	/* pointer to a null terminated read-only string */
 	__BPF_ARG_TYPE_MAX,
 };
 
kernel/bpf/verifier.c +41 -0

59 lines not on this page · raw message

Signature · 1 line
2.31.1.368.gbe11c130af-goog
#3 lore raw

Re: [PATCH bpf-next v5 2/6] bpf: Add a ARG_PTR_TO_CONST_STR argument type

Quoted 44 lines · Florent Revest

This type provides the guarantee that an argument is going to be a const pointer to somewhere in a read-only map value. It also checks that this pointer is followed by a zero character before the end of the map value.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/verifier.c | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
include/linux/bpf.h +1 -0
index 77d1d8c65b81..c160526fc8bf 100644
@@ -309,6 +309,7 @@ enum bpf_arg_type {
 	ARG_PTR_TO_PERCPU_BTF_ID,	/* pointer to in-kernel percpu type */
 	ARG_PTR_TO_FUNC,	/* pointer to a bpf program function */
 	ARG_PTR_TO_STACK_OR_NULL,	/* pointer to stack or NULL */
+	ARG_PTR_TO_CONST_STR,	/* pointer to a null terminated read-only string */
 	__BPF_ARG_TYPE_MAX,
 };
 
kernel/bpf/verifier.c +2 -0
index 852541a435ef..5f46dd6f3383 100644
@@ -4787,6 +4787,7 @@ static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALU
 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
+static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
 
 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
 	[ARG_PTR_TO_MAP_KEY]		= &map_key_value_types,
@@ -4817,6 +4818,7 @@ static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
 	[ARG_PTR_TO_PERCPU_BTF_ID]	= &percpu_btf_ptr_types,
 	[ARG_PTR_TO_FUNC]		= &func_ptr_types,
 	[ARG_PTR_TO_STACK_OR_NULL]	= &stack_ptr_types,
+	[ARG_PTR_TO_CONST_STR]		= &const_str_ptr_types,
 };
 
 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5078

Quoted 10 lines
kernel/bpf/verifier.c +7 -0
@@ -5067,6 +5069,45 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
 		if (err)
 			return err;
 		err = check_ptr_alignment(env, reg, 0, size, true);
+	} else if (arg_type == ARG_PTR_TO_CONST_STR) {
+		struct bpf_map *map = reg->map_ptr;
+		int map_off;
+		u64 map_addr;
+		char *str_ptr;
+
+		if (reg->type != PTR_TO_MAP_VALUE || !map ||

I think the 'type' check is redundant,
since check_reg_type() did it via compatible_reg_types. If so it's probably better to remove it here ?

'!map' looks unnecessary. Can it ever happen? If yes, it's a verifier bug. For example in check_mem_access() we just deref reg->map_ptr without checking which, I think, is correct.

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5079

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+		    !bpf_map_is_rdonly(map)) {

This check is needed, of course.

Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+			verbose(env, "R%d does not point to a readonly map'\n", regno);
+			return -EACCES;
+		}
+
+		if (!tnum_is_const(reg->var_off)) {
+			verbose(env, "R%d is not a constant address'\n", regno);
+			return -EACCES;
+		}
+
+		if (!map->ops->map_direct_value_addr) {
+			verbose(env, "no direct value access support for this map type\n");
+			return -EACCES;

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5101

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+		}
+
+		err = check_map_access(env, regno, reg->off,
+				       map->value_size - reg->off, false);
+		if (err)
+			return err;
+
+		map_off = reg->off + reg->var_off.value;
+		err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
+		if (err) {

since the code checks it here the same check in check_bpf_snprintf_call() should probably do:
if (err) {
verbose("verifier bug\n");
return -EFAULT;
}

instead of just "return err;"
?

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5102

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+			verbose(env, "direct value access on string failed\n");

I think the message doesn't tell users much, but they probably should never see it unless they try to do lookup from readonly array with more than one element.
So I guess it's fine to keep this one as-is. Just flagging.

Anyway the whole set looks great, so I've applied to bpf-next. Thanks!

#4 lore raw

Re: [PATCH bpf-next v5 2/6] bpf: Add a ARG_PTR_TO_CONST_STR argument type

Quoted 61 lines · Alexei Starovoitov
Quoted 44 lines · Florent Revest

This type provides the guarantee that an argument is going to be a const pointer to somewhere in a read-only map value. It also checks that this pointer is followed by a zero character before the end of the map value.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/verifier.c | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
include/linux/bpf.h +1 -0
index 77d1d8c65b81..c160526fc8bf 100644
@@ -309,6 +309,7 @@ enum bpf_arg_type {
      ARG_PTR_TO_PERCPU_BTF_ID,       /* pointer to in-kernel percpu type */
      ARG_PTR_TO_FUNC,        /* pointer to a bpf program function */
      ARG_PTR_TO_STACK_OR_NULL,       /* pointer to stack or NULL */
+     ARG_PTR_TO_CONST_STR,   /* pointer to a null terminated read-only string */
      __BPF_ARG_TYPE_MAX,
 };
 
kernel/bpf/verifier.c +2 -0
index 852541a435ef..5f46dd6f3383 100644
@@ -4787,6 +4787,7 @@ static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALU
 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
+static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
 
 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
@@ -4817,6 +4818,7 @@ static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
      [ARG_PTR_TO_FUNC]               = &func_ptr_types,
      [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
+     [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
 };
 
 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5078

Quoted 10 lines
kernel/bpf/verifier.c +7 -0
@@ -5067,6 +5069,45 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
              if (err)
                      return err;
              err = check_ptr_alignment(env, reg, 0, size, true);
+     } else if (arg_type == ARG_PTR_TO_CONST_STR) {
+             struct bpf_map *map = reg->map_ptr;
+             int map_off;
+             u64 map_addr;
+             char *str_ptr;
+
+             if (reg->type != PTR_TO_MAP_VALUE || !map ||

I think the 'type' check is redundant,
since check_reg_type() did it via compatible_reg_types. If so it's probably better to remove it here ?

Quoted 3 lines

'!map' looks unnecessary. Can it ever happen? If yes, it's a verifier bug. For example in check_mem_access() we just deref reg->map_ptr without checking which, I think, is correct.

I agree with all of the above. I only thought it's better to be safe than sorry but if you'd like I could follow up with a patch that removes some checks?

Quoted 29 lines

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5079

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+                 !bpf_map_is_rdonly(map)) {

This check is needed, of course.

Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+                     verbose(env, "R%d does not point to a readonly map'\n", regno);
+                     return -EACCES;
+             }
+
+             if (!tnum_is_const(reg->var_off)) {
+                     verbose(env, "R%d is not a constant address'\n", regno);
+                     return -EACCES;
+             }
+
+             if (!map->ops->map_direct_value_addr) {
+                     verbose(env, "no direct value access support for this map type\n");
+                     return -EACCES;

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5101

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+             }
+
+             err = check_map_access(env, regno, reg->off,
+                                    map->value_size - reg->off, false);
+             if (err)
+                     return err;
+
+             map_off = reg->off + reg->var_off.value;
+             err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
+             if (err) {

since the code checks it here the same check in check_bpf_snprintf_call() should probably do:

Quoted 7 lines
 if (err) {
   verbose("verifier bug\n");
   return -EFAULT;

}

instead of just "return err;"
?

Sure, does not hurt. I can also follow up with a patch unless if you prefer doing it yourself.

Quoted 6 lines

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5102

Quoted 1 line
kernel/bpf/verifier.c +1 -0
+                     verbose(env, "direct value access on string failed\n");

I think the message doesn't tell users much, but they probably should never see it unless they try to do lookup from readonly array with more than one element.
So I guess it's fine to keep this one as-is. Just flagging.

Ack

Quoted 2 lines

Anyway the whole set looks great, so I've applied to bpf-next. Thanks!

Thank you :D

#5 lore raw

Re: [PATCH bpf-next v5 2/6] bpf: Add a ARG_PTR_TO_CONST_STR argument type

Quoted 71 lines · Florent Revest
Quoted 61 lines · Alexei Starovoitov
Quoted 44 lines · Florent Revest

This type provides the guarantee that an argument is going to be a const pointer to somewhere in a read-only map value. It also checks that this pointer is followed by a zero character before the end of the map value.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/verifier.c | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
include/linux/bpf.h +1 -0
index 77d1d8c65b81..c160526fc8bf 100644
@@ -309,6 +309,7 @@ enum bpf_arg_type {
      ARG_PTR_TO_PERCPU_BTF_ID,       /* pointer to in-kernel percpu type */
      ARG_PTR_TO_FUNC,        /* pointer to a bpf program function */
      ARG_PTR_TO_STACK_OR_NULL,       /* pointer to stack or NULL */
+     ARG_PTR_TO_CONST_STR,   /* pointer to a null terminated read-only string */
      __BPF_ARG_TYPE_MAX,
 };
 
kernel/bpf/verifier.c +2 -0
index 852541a435ef..5f46dd6f3383 100644
@@ -4787,6 +4787,7 @@ static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALU
 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
+static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
 
 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
@@ -4817,6 +4818,7 @@ static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
      [ARG_PTR_TO_FUNC]               = &func_ptr_types,
      [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
+     [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
 };
 
 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5078

Quoted 10 lines
kernel/bpf/verifier.c +7 -0
@@ -5067,6 +5069,45 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
              if (err)
                      return err;
              err = check_ptr_alignment(env, reg, 0, size, true);
+     } else if (arg_type == ARG_PTR_TO_CONST_STR) {
+             struct bpf_map *map = reg->map_ptr;
+             int map_off;
+             u64 map_addr;
+             char *str_ptr;
+
+             if (reg->type != PTR_TO_MAP_VALUE || !map ||

I think the 'type' check is redundant,
since check_reg_type() did it via compatible_reg_types. If so it's probably better to remove it here ?

Quoted 3 lines

'!map' looks unnecessary. Can it ever happen? If yes, it's a verifier bug. For example in check_mem_access() we just deref reg->map_ptr without checking which, I think, is correct.

I agree with all of the above. I only thought it's better to be safe than sorry but if you'd like I could follow up with a patch that removes some checks?

...

Quoted 2 lines

Sure, does not hurt. I can also follow up with a patch unless if you prefer doing it yourself.

Please send a follow up patch.
I consider this kind of "safe than sorry" to be defensive programming that promotes less-thinking-is-fine-because-its-faster-to-code style. I'm sure you've seen my rants against defensive programming in the past :)

#6 lore raw

Re: [PATCH bpf-next v5 2/6] bpf: Add a ARG_PTR_TO_CONST_STR argument type

Quoted 70 lines · Alexei Starovoitov
Quoted 68 lines · Florent Revest
Quoted 64 lines · Alexei Starovoitov
Quoted 44 lines · Florent Revest

This type provides the guarantee that an argument is going to be a const pointer to somewhere in a read-only map value. It also checks that this pointer is followed by a zero character before the end of the map value.

---
 include/linux/bpf.h   |  1 +
 kernel/bpf/verifier.c | 41 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
include/linux/bpf.h +1 -0
index 77d1d8c65b81..c160526fc8bf 100644
@@ -309,6 +309,7 @@ enum bpf_arg_type {
      ARG_PTR_TO_PERCPU_BTF_ID,       /* pointer to in-kernel percpu type */
      ARG_PTR_TO_FUNC,        /* pointer to a bpf program function */
      ARG_PTR_TO_STACK_OR_NULL,       /* pointer to stack or NULL */
+     ARG_PTR_TO_CONST_STR,   /* pointer to a null terminated read-only string */
      __BPF_ARG_TYPE_MAX,
 };
 
kernel/bpf/verifier.c +2 -0
index 852541a435ef..5f46dd6f3383 100644
@@ -4787,6 +4787,7 @@ static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALU
 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } };
 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
+static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
 
 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_MAP_KEY]            = &map_key_value_types,
@@ -4817,6 +4818,7 @@ static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
      [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
      [ARG_PTR_TO_FUNC]               = &func_ptr_types,
      [ARG_PTR_TO_STACK_OR_NULL]      = &stack_ptr_types,
+     [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
 };
 
 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,

kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 arg, · line 5078

Quoted 10 lines
kernel/bpf/verifier.c +7 -0
@@ -5067,6 +5069,45 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
              if (err)
                      return err;
              err = check_ptr_alignment(env, reg, 0, size, true);
+     } else if (arg_type == ARG_PTR_TO_CONST_STR) {
+             struct bpf_map *map = reg->map_ptr;
+             int map_off;
+             u64 map_addr;
+             char *str_ptr;
+
+             if (reg->type != PTR_TO_MAP_VALUE || !map ||

I think the 'type' check is redundant,
since check_reg_type() did it via compatible_reg_types. If so it's probably better to remove it here ?

'!map' looks unnecessary. Can it ever happen? If yes, it's a verifier bug. For example in check_mem_access() we just deref reg->map_ptr without checking which, I think, is correct.

Quoted 8 lines
Quoted 3 lines

I agree with all of the above. I only thought it's better to be safe than sorry but if you'd like I could follow up with a patch that removes some checks?

...

Quoted 2 lines

Sure, does not hurt. I can also follow up with a patch unless if you prefer doing it yourself.

Please send a follow up patch.

Okay, doing that today :)

Quoted 2 lines

I consider this kind of "safe than sorry" to be defensive programming that promotes less-thinking-is-fine-because-its-faster-to-code style.

Fair

Quoted 1 line

I'm sure you've seen my rants against defensive programming in the past :)

Ahah, I haven't yet but I surely don't want to make you rant again ;)

#7 lore raw

PATCH v5 3/6 bpf: Add a bpf_snprintf helper

In reply to Florent Revest

The implementation takes inspiration from the existing bpf_trace_printk helper but there are a few differences:

To allow for a large number of format-specifiers, parameters are provided in an array, like in bpf_seq_printf.

Because the output string takes two arguments and the array of parameters also takes two arguments, the format string needs to fit in one argument. Thankfully, ARG_PTR_TO_CONST_STR is guaranteed to point to a zero-terminated read-only map so we don't need a format string length arg.

Because the format-string is known at verification time, we also do a first pass of format string validation in the verifier logic. This makes debugging easier.

---
 include/linux/bpf.h            |  1 +
 include/uapi/linux/bpf.h       | 28 +++++++++++++++++++
 kernel/bpf/helpers.c           | 50 ++++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c          | 41 ++++++++++++++++++++++++++++
 kernel/trace/bpf_trace.c       |  2 ++
 tools/include/uapi/linux/bpf.h | 28 +++++++++++++++++++
 6 files changed, 150 insertions(+)
include/linux/bpf.h +1 -0
index c160526fc8bf..f8a45f109e96 100644
@@ -1953,6 +1953,7 @@ extern const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto;
 extern const struct bpf_func_proto bpf_skc_to_udp6_sock_proto;
 extern const struct bpf_func_proto bpf_copy_from_user_proto;
 extern const struct bpf_func_proto bpf_snprintf_btf_proto;
+extern const struct bpf_func_proto bpf_snprintf_proto;
 extern const struct bpf_func_proto bpf_per_cpu_ptr_proto;
 extern const struct bpf_func_proto bpf_this_cpu_ptr_proto;
 extern const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto;
include/uapi/linux/bpf.h +28 -0
index df164a44bb41..ec6d85a81744 100644
@@ -4708,6 +4708,33 @@ union bpf_attr {
  *	Return
  *		The number of traversed map elements for success, **-EINVAL** for
  *		invalid **flags**.
+ *
+ * long bpf_snprintf(char *str, u32 str_size, const char *fmt, u64 *data, u32 data_len)
+ *	Description
+ *		Outputs a string into the **str** buffer of size **str_size**
+ *		based on a format string stored in a read-only map pointed by
+ *		**fmt**.
+ *
+ *		Each format specifier in **fmt** corresponds to one u64 element
+ *		in the **data** array. For strings and pointers where pointees
+ *		are accessed, only the pointer values are stored in the *data*
+ *		array. The *data_len* is the size of *data* in bytes.
+ *
+ *		Formats **%s** and **%p{i,I}{4,6}** require to read kernel
+ *		memory. Reading kernel memory may fail due to either invalid
+ *		address or valid address but requiring a major memory fault. If
+ *		reading kernel memory fails, the string for **%s** will be an
+ *		empty string, and the ip address for **%p{i,I}{4,6}** will be 0.
+ *		Not returning error to bpf program is consistent with what
+ *		**bpf_trace_printk**\ () does for now.
+ *
+ *	Return
+ *		The strictly positive length of the formatted string, including
+ *		the trailing zero character. If the return value is greater than
+ *		**str_size**, **str** contains a truncated string, guaranteed to
+ *		be zero-terminated except when **str_size** is 0.
+ *
+ *		Or **-EBUSY** if the per-CPU memory copy buffer is busy.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -4875,6 +4902,7 @@ union bpf_attr {
 	FN(sock_from_file),		\
 	FN(check_mtu),			\
 	FN(for_each_map_elem),		\
+	FN(snprintf),			\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
kernel/bpf/helpers.c +50 -0

62 lines not on this page · raw message

kernel/bpf/verifier.c +41 -0

53 lines not on this page · raw message

kernel/trace/bpf_trace.c +2 -0
index a13f8644b357..2a8bcdc927c7 100644
@@ -1076,6 +1076,8 @@ bpf_tracing_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
 		return &bpf_task_storage_delete_proto;
 	case BPF_FUNC_for_each_map_elem:
 		return &bpf_for_each_map_elem_proto;
+	case BPF_FUNC_snprintf:
+		return &bpf_snprintf_proto;
 	default:
 		return NULL;
 	}
tools/include/uapi/linux/bpf.h +28 -0
index df164a44bb41..ec6d85a81744 100644
@@ -4708,6 +4708,33 @@ union bpf_attr {
  *	Return
  *		The number of traversed map elements for success, **-EINVAL** for
  *		invalid **flags**.
+ *
+ * long bpf_snprintf(char *str, u32 str_size, const char *fmt, u64 *data, u32 data_len)
+ *	Description
+ *		Outputs a string into the **str** buffer of size **str_size**
+ *		based on a format string stored in a read-only map pointed by
+ *		**fmt**.
+ *
+ *		Each format specifier in **fmt** corresponds to one u64 element
+ *		in the **data** array. For strings and pointers where pointees
+ *		are accessed, only the pointer values are stored in the *data*
+ *		array. The *data_len* is the size of *data* in bytes.
+ *
+ *		Formats **%s** and **%p{i,I}{4,6}** require to read kernel
+ *		memory. Reading kernel memory may fail due to either invalid
+ *		address or valid address but requiring a major memory fault. If
+ *		reading kernel memory fails, the string for **%s** will be an
+ *		empty string, and the ip address for **%p{i,I}{4,6}** will be 0.
+ *		Not returning error to bpf program is consistent with what
+ *		**bpf_trace_printk**\ () does for now.
+ *
+ *	Return
+ *		The strictly positive length of the formatted string, including
+ *		the trailing zero character. If the return value is greater than
+ *		**str_size**, **str** contains a truncated string, guaranteed to
+ *		be zero-terminated except when **str_size** is 0.
+ *
+ *		Or **-EBUSY** if the per-CPU memory copy buffer is busy.
  */
 #define __BPF_FUNC_MAPPER(FN)		\
 	FN(unspec),			\
@@ -4875,6 +4902,7 @@ union bpf_attr {
 	FN(sock_from_file),		\
 	FN(check_mtu),			\
 	FN(for_each_map_elem),		\
+	FN(snprintf),			\
 	/* */
 
 /* integer value in 'imm' field of BPF_CALL instruction selects which helper
Signature · 1 line
2.31.1.368.gbe11c130af-goog
#8 lore raw

PATCH v5 4/6 libbpf: Initialize the bpf_seq_printf parameters array field by field

In reply to Florent Revest

When initializing the __param array with a one liner, if all args are const, the initial array value will be placed in the rodata section but because libbpf does not support relocation in the rodata section, any pointer in this array will stay NULL.

Fixes c09add2fbc5a ("tools/libbpf: Add bpf_iter support")
---
 tools/lib/bpf/bpf_tracing.h | 40 +++++++++++++++++++++++++++----------
 1 file changed, 29 insertions(+), 11 deletions(-)
tools/lib/bpf/bpf_tracing.h +29 -11
index f9ef37707888..1c2e91ee041d 100644
@@ -413,20 +413,38 @@ typeof(name(0)) name(struct pt_regs *ctx)				    \
 }									    \
 static __always_inline typeof(name(0)) ____##name(struct pt_regs *ctx, ##args)
 
+#define ___bpf_fill0(arr, p, x) do {} while (0)
+#define ___bpf_fill1(arr, p, x) arr[p] = x
+#define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
+#define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
+#define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
+#define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
+#define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
+#define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
+#define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
+#define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
+#define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
+#define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
+#define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
+#define ___bpf_fill(arr, args...) \
+	___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
+
 /*
  * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
  * in a structure.
  */
-#define BPF_SEQ_PRINTF(seq, fmt, args...)				    \
-	({								    \
-		_Pragma("GCC diagnostic push")				    \
-		_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	    \
-		static const char ___fmt[] = fmt;			    \
-		unsigned long long ___param[] = { args };		    \
-		_Pragma("GCC diagnostic pop")				    \
-		int ___ret = bpf_seq_printf(seq, ___fmt, sizeof(___fmt),    \
-					    ___param, sizeof(___param));    \
-		___ret;							    \
-	})
+#define BPF_SEQ_PRINTF(seq, fmt, args...)			\
+({								\
+	static const char ___fmt[] = fmt;			\
+	unsigned long long ___param[___bpf_narg(args)];		\
+								\
+	_Pragma("GCC diagnostic push")				\
+	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
+	___bpf_fill(___param, args);				\
+	_Pragma("GCC diagnostic pop")				\
+								\
+	bpf_seq_printf(seq, ___fmt, sizeof(___fmt),		\
+		       ___param, sizeof(___param));		\
+})
 
 #endif
Signature · 1 line
2.31.1.368.gbe11c130af-goog
#9 lore raw

PATCH v5 5/6 libbpf: Introduce a BPF_SNPRINTF helper macro

In reply to Florent Revest

Similarly to BPF_SEQ_PRINTF, this macro turns variadic arguments into an array of u64, making it more natural to call the bpf_snprintf helper.

---
 tools/lib/bpf/bpf_tracing.h | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
tools/lib/bpf/bpf_tracing.h +18 -0
index 1c2e91ee041d..8c954ebc0c7c 100644
@@ -447,4 +447,22 @@ static __always_inline typeof(name(0)) ____##name(struct pt_regs *ctx, ##args)
 		       ___param, sizeof(___param));		\
 })
 
+/*
+ * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
+ * an array of u64.
+ */
+#define BPF_SNPRINTF(out, out_size, fmt, args...)		\
+({								\
+	static const char ___fmt[] = fmt;			\
+	unsigned long long ___param[___bpf_narg(args)];		\
+								\
+	_Pragma("GCC diagnostic push")				\
+	_Pragma("GCC diagnostic ignored \"-Wint-conversion\"")	\
+	___bpf_fill(___param, args);				\
+	_Pragma("GCC diagnostic pop")				\
+								\
+	bpf_snprintf(out, out_size, ___fmt,			\
+		     ___param, sizeof(___param));		\
+})
+
 #endif
Signature · 1 line
2.31.1.368.gbe11c130af-goog
#10 lore raw

PATCH v5 6/6 selftests/bpf: Add a series of tests for bpf_snprintf

In reply to Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +125 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"
+#define EXP_PAD_RET 900007
+
+#define EXP_NO_ARG_OUT "simple case"
+#define EXP_NO_ARG_RET 12
+
+#define EXP_NO_BUF_RET 29
+
+void test_snprintf_positive(void)
+{
+	char exp_addr_out[] = EXP_ADDR_OUT;
+	char exp_sym_out[]  = EXP_SYM_OUT;
+	struct test_snprintf *skel;
+
+	skel = test_snprintf__open_and_load();
+	if (!ASSERT_OK_PTR(skel, "skel_open"))
+		return;
+
+	if (!ASSERT_OK(test_snprintf__attach(skel), "skel_attach"))
+		goto cleanup;
+
+	/* trigger tracepoint */
+	usleep(1);
+
+	ASSERT_STREQ(skel->bss->num_out, EXP_NUM_OUT, "num_out");
+	ASSERT_EQ(skel->bss->num_ret, EXP_NUM_RET, "num_ret");
+
+	ASSERT_STREQ(skel->bss->ip_out, EXP_IP_OUT, "ip_out");
+	ASSERT_EQ(skel->bss->ip_ret, EXP_IP_RET, "ip_ret");
+
+	ASSERT_OK(memcmp(skel->bss->sym_out, exp_sym_out,
+			 sizeof(exp_sym_out) - 1), "sym_out");
+	ASSERT_LT(MIN_SYM_RET, skel->bss->sym_ret, "sym_ret");
+
+	ASSERT_OK(memcmp(skel->bss->addr_out, exp_addr_out,
+			 sizeof(exp_addr_out) - 1), "addr_out");
+	ASSERT_EQ(skel->bss->addr_ret, EXP_ADDR_RET, "addr_ret");
+
+	ASSERT_STREQ(skel->bss->str_out, EXP_STR_OUT, "str_out");
+	ASSERT_EQ(skel->bss->str_ret, EXP_STR_RET, "str_ret");
+
+	ASSERT_STREQ(skel->bss->over_out, EXP_OVER_OUT, "over_out");
+	ASSERT_EQ(skel->bss->over_ret, EXP_OVER_RET, "over_ret");
+
+	ASSERT_STREQ(skel->bss->pad_out, EXP_PAD_OUT, "pad_out");
+	ASSERT_EQ(skel->bss->pad_ret, EXP_PAD_RET, "pad_ret");
+
+	ASSERT_STREQ(skel->bss->noarg_out, EXP_NO_ARG_OUT, "no_arg_out");
+	ASSERT_EQ(skel->bss->noarg_ret, EXP_NO_ARG_RET, "no_arg_ret");
+
+	ASSERT_EQ(skel->bss->nobuf_ret, EXP_NO_BUF_RET, "no_buf_ret");
+
+cleanup:
+	test_snprintf__destroy(skel);
+}
+
+#define min(a, b) ((a) < (b) ? (a) : (b))
+
+/* Loads an eBPF object calling bpf_snprintf with up to 10 characters of fmt */
+static int load_single_snprintf(char *fmt)
+{
+	struct test_snprintf_single *skel;
+	int ret;
+
+	skel = test_snprintf_single__open();
+	if (!skel)
+		return -EINVAL;
+
+	memcpy(skel->rodata->fmt, fmt, min(strlen(fmt) + 1, 10));
+
+	ret = test_snprintf_single__load(skel);
+	test_snprintf_single__destroy(skel);
+
+	return ret;
+}
+
+void test_snprintf_negative(void)
+{
+	ASSERT_OK(load_single_snprintf("valid %d"), "valid usage");
+
+	ASSERT_ERR(load_single_snprintf("0123456789"), "no terminating zero");
+	ASSERT_ERR(load_single_snprintf("%d %d"), "too many specifiers");
+	ASSERT_ERR(load_single_snprintf("%pi5"), "invalid specifier 1");
+	ASSERT_ERR(load_single_snprintf("%a"), "invalid specifier 2");
+	ASSERT_ERR(load_single_snprintf("%"), "invalid specifier 3");
+	ASSERT_ERR(load_single_snprintf("%12345678"), "invalid specifier 4");
+	ASSERT_ERR(load_single_snprintf("%--------"), "invalid specifier 5");
+	ASSERT_ERR(load_single_snprintf("\x80"), "non ascii character");
+	ASSERT_ERR(load_single_snprintf("\x1"), "non printable character");
+}
+
+void test_snprintf(void)
+{
+	if (test__start_subtest("snprintf_positive"))
+		test_snprintf_positive();
+	if (test__start_subtest("snprintf_negative"))
+		test_snprintf_negative();
+}
tools/testing/selftests/bpf/progs/test_snprintf.c new file +73 -0

73 lines not on this page · raw message

tools/testing/selftests/bpf/progs/test_snprintf_single.c new file +20 -0
new file mode 100644
index 000000000000..402adaf344f9
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+
+/* The format string is filled from the userspace such that loading fails */
+static const char fmt[10];
+
+SEC("raw_tp/sys_enter")
+int handler(const void *ctx)
+{
+	unsigned long long arg = 42;
+
+	bpf_snprintf(NULL, 0, fmt, &arg, sizeof(arg));
+
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";
Signature · 1 line
2.31.1.368.gbe11c130af-goog
#11 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +7 -0
+#define EXP_PAD_RET 900007
+
+#define EXP_NO_ARG_OUT "simple case"
+#define EXP_NO_ARG_RET 12
+
+#define EXP_NO_BUF_RET 29
+

[...]

#12 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

#13 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 78 lines · Florent Revest
Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

Quoted 8 lines

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

I'm puzzled too, have no idea. I also can't repro this with vmtest.sh. But I can quite reliably reproduce with my local ArchLinux-based qemu image with different config (see [0] for config itself). So please try with my config and see if that helps to repro. If not, I'll have to debug it on my own later.

[0] https://gist.github.com/anakryiko/4b6ae21680842bdeacca8fa99d378048

#14 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 89 lines · Andrii Nakryiko
Quoted 78 lines · Florent Revest
Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

Quoted 8 lines

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

Quoted 7 lines

I'm puzzled too, have no idea. I also can't repro this with vmtest.sh. But I can quite reliably reproduce with my local ArchLinux-based qemu image with different config (see [0] for config itself). So please try with my config and see if that helps to repro. If not, I'll have to debug it on my own later.

[0] https://gist.github.com/anakryiko/4b6ae21680842bdeacca8fa99d378048

I tried that config on the same commit 87bd9e602 (bpf-next/master) with my debian-based qemu image and I still can't reproduce the issue :| If I can be of any help let me know, I'd be happy to help

#15 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 97 lines · Florent Revest
Quoted 95 lines · Andrii Nakryiko
Quoted 78 lines · Florent Revest
Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

Quoted 8 lines

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

I'm puzzled too, have no idea. I also can't repro this with vmtest.sh. But I can quite reliably reproduce with my local ArchLinux-based qemu image with different config (see [0] for config itself). So please try with my config and see if that helps to repro. If not, I'll have to debug it on my own later.

Quoted 6 lines
Quoted 1 line

[0] https://gist.github.com/anakryiko/4b6ae21680842bdeacca8fa99d378048

I tried that config on the same commit 87bd9e602 (bpf-next/master) with my debian-based qemu image and I still can't reproduce the issue :| If I can be of any help let me know, I'd be happy to help

It's not really clear to me if this is before or after the rewrite to use bprintf, but regardless, in those two patches this caught my attention:

u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
- enum bpf_printf_mod_type mod[MAX_TRACE_PRINTK_VARARGS];
+ u32 *bin_args;
static char buf[BPF_TRACE_PRINTK_SIZE]; unsigned long flags;
int ret;

- ret = bpf_printf_prepare(fmt, fmt_size, args, args, mod,
- MAX_TRACE_PRINTK_VARARGS);
+ ret = bpf_bprintf_prepare(fmt, fmt_size, args, &bin_args,
+ MAX_TRACE_PRINTK_VARARGS);
if (ret < 0)
return ret;

- ret = snprintf(buf, sizeof(buf), fmt, BPF_CAST_FMT_ARG(0, args, mod),
- BPF_CAST_FMT_ARG(1, args, mod), BPF_CAST_FMT_ARG(2, args, mod));
- /* snprintf() will not append null for zero-length strings */
- if (ret == 0)
- buf[0] = '\0';
+ ret = bstr_printf(buf, sizeof(buf), fmt, bin_args);

raw_spin_lock_irqsave(&trace_printk_lock, flags); trace_bpf_trace_printk(buf); raw_spin_unlock_irqrestore(&trace_printk_lock, flags);

Why isn't the write to buf[] protected by that spinlock? Or put another way, what protects buf[] from concurrent writes?

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

Rasmus

#16 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 101 lines · Rasmus Villemoes
Quoted 99 lines · Florent Revest
Quoted 96 lines · Andrii Nakryiko
Quoted 78 lines · Florent Revest
Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

Quoted 8 lines

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

I'm puzzled too, have no idea. I also can't repro this with vmtest.sh. But I can quite reliably reproduce with my local ArchLinux-based qemu image with different config (see [0] for config itself). So please try with my config and see if that helps to repro. If not, I'll have to debug it on my own later.

[0] https://gist.github.com/anakryiko/4b6ae21680842bdeacca8fa99d378048

Quoted 7 lines
Quoted 4 lines

I tried that config on the same commit 87bd9e602 (bpf-next/master) with my debian-based qemu image and I still can't reproduce the issue :| If I can be of any help let me know, I'd be happy to help

It's not really clear to me if this is before or after the rewrite to use bprintf, but regardless, in those two patches this caught my attention:

I tried to reproduce Andrii's bug both before and after the bprintf rewrite but I think he meant before.

Quoted 25 lines
        u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
(quoted diff) +4 -8
-       enum bpf_printf_mod_type mod[MAX_TRACE_PRINTK_VARARGS];
+       u32 *bin_args;
        static char buf[BPF_TRACE_PRINTK_SIZE];
        unsigned long flags;
        int ret;
 
-       ret = bpf_printf_prepare(fmt, fmt_size, args, args, mod,
-                                MAX_TRACE_PRINTK_VARARGS);
+       ret = bpf_bprintf_prepare(fmt, fmt_size, args, &bin_args,
+                                 MAX_TRACE_PRINTK_VARARGS);
        if (ret < 0)
                return ret;
 
-       ret = snprintf(buf, sizeof(buf), fmt, BPF_CAST_FMT_ARG(0, args, mod),
-               BPF_CAST_FMT_ARG(1, args, mod), BPF_CAST_FMT_ARG(2, args, mod));
-       /* snprintf() will not append null for zero-length strings */
-       if (ret == 0)
-               buf[0] = '\0';
+       ret = bstr_printf(buf, sizeof(buf), fmt, bin_args);
 
        raw_spin_lock_irqsave(&trace_printk_lock, flags);
        trace_bpf_trace_printk(buf);
        raw_spin_unlock_irqrestore(&trace_printk_lock, flags);
Quoted 2 lines

Why isn't the write to buf[] protected by that spinlock? Or put another way, what protects buf[] from concurrent writes?

You're right, that is a bug, I missed that buf was static and thought it was just on the stack. That snprintf call should be after the raw_spin_lock_irqsave. I'll send a patch. Thank you Rasmus. (before my snprintf series, there was a vsprintf after the raw_spin_lock_irqsave)

Quoted 2 lines

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

I think it's a separate issue from what Andrii reported though because the flaky test exercises the bpf_snprintf helper and this buf spinlock bug you just found only affects the bpf_trace_printk helper.

That being said, it does smell a little bit like a concurrency issue too, indeed. The bpf_snprintf test program is a raw_tp/sys_enter so it attaches to all syscall entries and most likely gets executed many more times than necessary and probably on parallel CPUs. The "pad_out" buffer they write to is unique and not locked so maybe the test's userspace reads pad_out while another CPU is writing on it and if the
string output goes through a stage where it is " 4 0000" before
being " 4 000", we might read at the wrong time. That being said, I
would find it weird that this happens as much as 50% of the time and always specifically on that test case.

Andrii could you maybe try changing the prog type to "tp/syscalls/sys_enter_nanosleep" on the machine where you can reproduce this bug ?

Quoted 1 line

Rasmus

#17 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 109 lines · Florent Revest
Quoted 106 lines · Rasmus Villemoes
Quoted 103 lines · Florent Revest
Quoted 89 lines · Andrii Nakryiko
Quoted 78 lines · Florent Revest
Quoted 55 lines · Andrii Nakryiko
Quoted 40 lines · Florent Revest

The "positive" part tests all format specifiers when things go well.

The "negative" part makes sure that incorrect format strings fail at load time.

---
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++++++++++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++++++++
 .../bpf/progs/test_snprintf_single.c          |  20 +++
 3 files changed, 218 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +18 -0
new file mode 100644
index 000000000000..a958c22aec75
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2021 Google LLC. */
+
+#include <test_progs.h>
+#include "test_snprintf.skel.h"
+#include "test_snprintf_single.skel.h"
+
+#define EXP_NUM_OUT  "-8 9 96 -424242 1337 DABBAD00"
+#define EXP_NUM_RET  sizeof(EXP_NUM_OUT)
+
+#define EXP_IP_OUT   "127.000.000.001 0000:0000:0000:0000:0000:0000:0000:0001"
+#define EXP_IP_RET   sizeof(EXP_IP_OUT)
+
+/* The third specifier, %pB, depends on compiler inlining so don't check it */
+#define EXP_SYM_OUT  "schedule schedule+0x0/"
+#define MIN_SYM_RET  sizeof(EXP_SYM_OUT)
+
+/* The third specifier, %p, is a hashed pointer which changes on every reboot */

tools/testing/selftests/bpf/prog_tests/snprintf.c line 28

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/snprintf.c new file +10 -0
+#define EXP_ADDR_OUT "0000000000000000 ffff00000add4e55 "
+#define EXP_ADDR_RET sizeof(EXP_ADDR_OUT "unknownhashedptr")
+
+#define EXP_STR_OUT  "str1 longstr"
+#define EXP_STR_RET  sizeof(EXP_STR_OUT)
+
+#define EXP_OVER_OUT "%over"
+#define EXP_OVER_RET 10
+
+#define EXP_PAD_OUT "    4 000"

Roughly 50% of the time I get failure for this test case:

Quoted 5 lines

test_snprintf_positive:FAIL:pad_out unexpected pad_out: actual ' 4
0000' != expected ' 4 000'

Re-running this test case immediately passes. Running again most probably fails. Please take a look.

Do you have more information on how to reproduce this ?
I spinned up a VM at 87bd9e602 with ./vmtest -s and then run this script:

#!/bin/sh
for i in seq 1000
do
./test_progs -t snprintf
if [ $? -ne 0 ];
then
echo FAILURE
exit 1
fi
done

Quoted 8 lines

The thousand executions passed.

This is a bit concerning because your unexpected_pad_out seems to have an extra '0' so it ends up with strlen(pad_out)=11 but sizeof(pad_out)=10. The actual string writing is not really done by our helper code but by the snprintf implementation (str and str_size are only given to snprintf()) so I'd expect the truncation to work well there. I'm a bit puzzled

Quoted 7 lines

I'm puzzled too, have no idea. I also can't repro this with vmtest.sh. But I can quite reliably reproduce with my local ArchLinux-based qemu image with different config (see [0] for config itself). So please try with my config and see if that helps to repro. If not, I'll have to debug it on my own later.

[0] https://gist.github.com/anakryiko/4b6ae21680842bdeacca8fa99d378048

I tried that config on the same commit 87bd9e602 (bpf-next/master) with my debian-based qemu image and I still can't reproduce the issue :| If I can be of any help let me know, I'd be happy to help

Quoted 5 lines
Quoted 2 lines

It's not really clear to me if this is before or after the rewrite to use bprintf, but regardless, in those two patches this caught my attention:

I tried to reproduce Andrii's bug both before and after the bprintf rewrite but I think he meant before.

I'm running on the latest bpf-next master, but I don't think it's related to bprintf change.

Quoted 26 lines
Quoted 26 lines
        u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
(quoted diff) +4 -8
-       enum bpf_printf_mod_type mod[MAX_TRACE_PRINTK_VARARGS];
+       u32 *bin_args;
        static char buf[BPF_TRACE_PRINTK_SIZE];
        unsigned long flags;
        int ret;
 
-       ret = bpf_printf_prepare(fmt, fmt_size, args, args, mod,
-                                MAX_TRACE_PRINTK_VARARGS);
+       ret = bpf_bprintf_prepare(fmt, fmt_size, args, &bin_args,
+                                 MAX_TRACE_PRINTK_VARARGS);
        if (ret < 0)
                return ret;
 
-       ret = snprintf(buf, sizeof(buf), fmt, BPF_CAST_FMT_ARG(0, args, mod),
-               BPF_CAST_FMT_ARG(1, args, mod), BPF_CAST_FMT_ARG(2, args, mod));
-       /* snprintf() will not append null for zero-length strings */
-       if (ret == 0)
-               buf[0] = '\0';
+       ret = bstr_printf(buf, sizeof(buf), fmt, bin_args);
 
        raw_spin_lock_irqsave(&trace_printk_lock, flags);
        trace_bpf_trace_printk(buf);
        raw_spin_unlock_irqrestore(&trace_printk_lock, flags);
Quoted 7 lines
Quoted 2 lines

Why isn't the write to buf[] protected by that spinlock? Or put another way, what protects buf[] from concurrent writes?

You're right, that is a bug, I missed that buf was static and thought it was just on the stack. That snprintf call should be after the raw_spin_lock_irqsave. I'll send a patch. Thank you Rasmus. (before my snprintf series, there was a vsprintf after the raw_spin_lock_irqsave)

Can you please also clean up unnecessary ()s you added in at least a few places. Thanks.

Quoted 19 lines
Quoted 3 lines

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

I think it's a separate issue from what Andrii reported though because the flaky test exercises the bpf_snprintf helper and this buf spinlock bug you just found only affects the bpf_trace_printk helper.

That being said, it does smell a little bit like a concurrency issue too, indeed. The bpf_snprintf test program is a raw_tp/sys_enter so it attaches to all syscall entries and most likely gets executed many more times than necessary and probably on parallel CPUs. The "pad_out" buffer they write to is unique and not locked so maybe the test's userspace reads pad_out while another CPU is writing on it and if the
string output goes through a stage where it is " 4 0000" before
being " 4 000", we might read at the wrong time. That being said, I
would find it weird that this happens as much as 50% of the time and always specifically on that test case.

Quoted 3 lines

Andrii could you maybe try changing the prog type to "tp/syscalls/sys_enter_nanosleep" on the machine where you can reproduce this bug ?

Yes, it helps. I can't repro it easily anymore. I think the right fix, though, should be to filter by tid, not change the tracepoint.

I think what's happening is we see the string right before bstr_printf does zero-termination with end[-1] = '\0'; So in some cases we see truncated string, in others we see untruncated one.

Quoted 2 lines
Quoted 2 lines

Rasmus

#18 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 30 lines · Andrii Nakryiko
Quoted 28 lines · Florent Revest
Quoted 25 lines · Rasmus Villemoes
        u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
(quoted diff) +4 -8
-       enum bpf_printf_mod_type mod[MAX_TRACE_PRINTK_VARARGS];
+       u32 *bin_args;
        static char buf[BPF_TRACE_PRINTK_SIZE];
        unsigned long flags;
        int ret;
 
-       ret = bpf_printf_prepare(fmt, fmt_size, args, args, mod,
-                                MAX_TRACE_PRINTK_VARARGS);
+       ret = bpf_bprintf_prepare(fmt, fmt_size, args, &bin_args,
+                                 MAX_TRACE_PRINTK_VARARGS);
        if (ret < 0)
                return ret;
 
-       ret = snprintf(buf, sizeof(buf), fmt, BPF_CAST_FMT_ARG(0, args, mod),
-               BPF_CAST_FMT_ARG(1, args, mod), BPF_CAST_FMT_ARG(2, args, mod));
-       /* snprintf() will not append null for zero-length strings */
-       if (ret == 0)
-               buf[0] = '\0';
+       ret = bstr_printf(buf, sizeof(buf), fmt, bin_args);
 
        raw_spin_lock_irqsave(&trace_printk_lock, flags);
        trace_bpf_trace_printk(buf);
        raw_spin_unlock_irqrestore(&trace_printk_lock, flags);
Quoted 7 lines
Quoted 7 lines
Quoted 2 lines

Why isn't the write to buf[] protected by that spinlock? Or put another way, what protects buf[] from concurrent writes?

You're right, that is a bug, I missed that buf was static and thought it was just on the stack. That snprintf call should be after the raw_spin_lock_irqsave. I'll send a patch. Thank you Rasmus. (before my snprintf series, there was a vsprintf after the raw_spin_lock_irqsave)

Solved now

Quoted 2 lines

Can you please also clean up unnecessary ()s you added in at least a few places. Thanks.

Alexei said he took care of this .:)

Quoted 18 lines
Quoted 18 lines
Quoted 2 lines

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

I think it's a separate issue from what Andrii reported though because the flaky test exercises the bpf_snprintf helper and this buf spinlock bug you just found only affects the bpf_trace_printk helper.

That being said, it does smell a little bit like a concurrency issue too, indeed. The bpf_snprintf test program is a raw_tp/sys_enter so it attaches to all syscall entries and most likely gets executed many more times than necessary and probably on parallel CPUs. The "pad_out" buffer they write to is unique and not locked so maybe the test's userspace reads pad_out while another CPU is writing on it and if the
string output goes through a stage where it is " 4 0000" before
being " 4 000", we might read at the wrong time. That being said, I
would find it weird that this happens as much as 50% of the time and always specifically on that test case.

Quoted 5 lines
Quoted 3 lines

Andrii could you maybe try changing the prog type to "tp/syscalls/sys_enter_nanosleep" on the machine where you can reproduce this bug ?

Yes, it helps. I can't repro it easily anymore.

Good, so it does sound like a concurrency issue indeed

Quoted 1 line

I think the right fix, though, should be to filter by tid, not change the tracepoint.

Agreed, I'll send a patch for that today. :)

Quoted 3 lines

I think what's happening is we see the string right before bstr_printf does zero-termination with end[-1] = '\0'; So in some cases we see truncated string, in others we see untruncated one.

Makes sense but I still wonder why it happens so often (50% of the time is really a lot) and why it is consistently that one test case that fails and not the "overflow" case for example. But I'm confident that this is not a bug in the helper now and that the tid filter will fix the test.

#19 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 81 lines · Florent Revest
Quoted 30 lines · Andrii Nakryiko
Quoted 28 lines · Florent Revest
Quoted 25 lines · Rasmus Villemoes
        u64 args[MAX_TRACE_PRINTK_VARARGS] = { arg1, arg2, arg3 };
(quoted diff) +4 -8
-       enum bpf_printf_mod_type mod[MAX_TRACE_PRINTK_VARARGS];
+       u32 *bin_args;
        static char buf[BPF_TRACE_PRINTK_SIZE];
        unsigned long flags;
        int ret;
 
-       ret = bpf_printf_prepare(fmt, fmt_size, args, args, mod,
-                                MAX_TRACE_PRINTK_VARARGS);
+       ret = bpf_bprintf_prepare(fmt, fmt_size, args, &bin_args,
+                                 MAX_TRACE_PRINTK_VARARGS);
        if (ret < 0)
                return ret;
 
-       ret = snprintf(buf, sizeof(buf), fmt, BPF_CAST_FMT_ARG(0, args, mod),
-               BPF_CAST_FMT_ARG(1, args, mod), BPF_CAST_FMT_ARG(2, args, mod));
-       /* snprintf() will not append null for zero-length strings */
-       if (ret == 0)
-               buf[0] = '\0';
+       ret = bstr_printf(buf, sizeof(buf), fmt, bin_args);
 
        raw_spin_lock_irqsave(&trace_printk_lock, flags);
        trace_bpf_trace_printk(buf);
        raw_spin_unlock_irqrestore(&trace_printk_lock, flags);
Quoted 7 lines
Quoted 7 lines
Quoted 2 lines

Why isn't the write to buf[] protected by that spinlock? Or put another way, what protects buf[] from concurrent writes?

You're right, that is a bug, I missed that buf was static and thought it was just on the stack. That snprintf call should be after the raw_spin_lock_irqsave. I'll send a patch. Thank you Rasmus. (before my snprintf series, there was a vsprintf after the raw_spin_lock_irqsave)

Solved now

Quoted 2 lines

Can you please also clean up unnecessary ()s you added in at least a few places. Thanks.

Alexei said he took care of this .:)

Quoted 18 lines
Quoted 18 lines
Quoted 2 lines

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

I think it's a separate issue from what Andrii reported though because the flaky test exercises the bpf_snprintf helper and this buf spinlock bug you just found only affects the bpf_trace_printk helper.

That being said, it does smell a little bit like a concurrency issue too, indeed. The bpf_snprintf test program is a raw_tp/sys_enter so it attaches to all syscall entries and most likely gets executed many more times than necessary and probably on parallel CPUs. The "pad_out" buffer they write to is unique and not locked so maybe the test's userspace reads pad_out while another CPU is writing on it and if the
string output goes through a stage where it is " 4 0000" before
being " 4 000", we might read at the wrong time. That being said, I
would find it weird that this happens as much as 50% of the time and always specifically on that test case.

Quoted 5 lines
Quoted 3 lines

Andrii could you maybe try changing the prog type to "tp/syscalls/sys_enter_nanosleep" on the machine where you can reproduce this bug ?

Yes, it helps. I can't repro it easily anymore.

Good, so it does sound like a concurrency issue indeed

Quoted 1 line

I think the right fix, though, should be to filter by tid, not change the tracepoint.

Agreed, I'll send a patch for that today. :)

Quoted 3 lines

I think what's happening is we see the string right before bstr_printf does zero-termination with end[-1] = '\0'; So in some cases we see truncated string, in others we see untruncated one.

Quoted 6 lines

Makes sense but I still wonder why it happens so often (50% of the time is really a lot) and why it is consistently that one test case that fails and not the "overflow" case for example. But I'm confident that this is not a bug in the helper now and that the tid filter will fix the test.

If the caller, or one of its sibling threads, inspects the buffer before (v)snprintf has returned it's very obviously a bug in the caller. As for why that particular case exposes the race: It seems to be the only one that "expects" an insanely long result, and it takes a very very long time (several cycles per byte I'd assume) for the vsnprintf code to very carefully go through the

if (buf < end)
*buf = /* '0' or ' ' or whatever it is it is emitting here */
buf++;

900k times. So there's simply a very large window where the buffer
contents is " 4 0000" while number() is still 'emitting' 0s until
control returns to vsnprintf() which does that final end[-1] = '\0'.

Rasmus

#20 lore raw

Re: [PATCH bpf-next v5 6/6] selftests/bpf: Add a series of tests for bpf_snprintf

Quoted 50 lines · Rasmus Villemoes
Quoted 41 lines · Florent Revest
Quoted 23 lines · Andrii Nakryiko
Quoted 21 lines · Florent Revest
Quoted 2 lines · Rasmus Villemoes

Probably the test cases are not run in parallel, but this is the kind of thing that would give those symptoms.

I think it's a separate issue from what Andrii reported though because the flaky test exercises the bpf_snprintf helper and this buf spinlock bug you just found only affects the bpf_trace_printk helper.

That being said, it does smell a little bit like a concurrency issue too, indeed. The bpf_snprintf test program is a raw_tp/sys_enter so it attaches to all syscall entries and most likely gets executed many more times than necessary and probably on parallel CPUs. The "pad_out" buffer they write to is unique and not locked so maybe the test's userspace reads pad_out while another CPU is writing on it and if the
string output goes through a stage where it is " 4 0000" before
being " 4 000", we might read at the wrong time. That being said, I
would find it weird that this happens as much as 50% of the time and always specifically on that test case.

Quoted 5 lines
Quoted 3 lines

Andrii could you maybe try changing the prog type to "tp/syscalls/sys_enter_nanosleep" on the machine where you can reproduce this bug ?

Yes, it helps. I can't repro it easily anymore.

Good, so it does sound like a concurrency issue indeed

Quoted 1 line

I think the right fix, though, should be to filter by tid, not change the tracepoint.

Agreed, I'll send a patch for that today. :)

Quoted 3 lines

I think what's happening is we see the string right before bstr_printf does zero-termination with end[-1] = '\0'; So in some cases we see truncated string, in others we see untruncated one.

Quoted 6 lines

Makes sense but I still wonder why it happens so often (50% of the time is really a lot) and why it is consistently that one test case that fails and not the "overflow" case for example. But I'm confident that this is not a bug in the helper now and that the tid filter will fix the test.

Quoted 2 lines

If the caller, or one of its sibling threads, inspects the buffer before (v)snprintf has returned it's very obviously a bug in the caller. As for

Absolutely

Quoted 5 lines

why that particular case exposes the race: It seems to be the only one that "expects" an insanely long result, and it takes a very very long time (several cycles per byte I'd assume) for the vsnprintf code to very carefully go through the

Quoted 7 lines

if (buf < end)
*buf = /* '0' or ' ' or whatever it is it is emitting here */
buf++;

900k times. So there's simply a very large window where the buffer
contents is " 4 0000" while number() is still 'emitting' 0s until
control returns to vsnprintf() which does that final end[-1] = '\0'.

Aaah, of course, it makes complete sense! :) Thank you Rasmus

Acked-by on the v5 series
#21 lore raw
In reply to Florent Revest
Quoted 82 lines · Florent Revest

We have a usecase where we want to audit symbol names (if available) in callback registration hooks. (ex: fentry/nf_register_net_hook)

A few months back, I proposed a bpf_kallsyms_lookup series but it was decided in the reviews that a more generic helper, bpf_snprintf, would be more useful.

This series implements the helper according to the feedback received in
https://lore.kernel.org/bpf/[email protected]/T/#u

- A new arg type guarantees the NULL-termination of string arguments and lets us pass format strings in only one arg
- A new helper is implemented using that guarantee. Because the format string is known at verification time, the format string validation is done by the verifier
- To implement a series of tests for bpf_snprintf, the logic for marshalling variadic args in a fixed-size array is reworked as per:
https://lore.kernel.org/bpf/[email protected]/T/#u

---
Changes in v5:
- Fixed the bpf_printf_buf_used counter logic in try_get_fmt_tmp_buf
- Added a couple of extra incorrect specifiers tests
- Call test_snprintf_single__destroy unconditionally
- Fixed a C++-style comment

---
Changes in v4:
- Moved bpf_snprintf, bpf_printf_prepare and bpf_printf_cleanup to kernel/bpf/helpers.c so that they get built without CONFIG_BPF_EVENTS
- Added negative test cases (various invalid format strings)
- Renamed put_fmt_tmp_buf() as bpf_printf_cleanup()
- Fixed a mistake that caused temporary buffers to be unconditionally freed in bpf_printf_prepare
- Fixed a mistake that caused missing 0 character to be ignored
- Fixed a warning about integer to pointer conversion
- Misc cleanups

---
Changes in v3:
- Simplified temporary buffer acquisition with try_get_fmt_tmp_buf()
- Made zero-termination check more consistent
- Allowed NULL output_buffer
- Simplified the BPF_CAST_FMT_ARG macro
- Three new test cases: number padding, simple string with no arg and string length extraction only with a NULL output buffer
- Clarified helper's description for edge cases (eg: str_size == 0)
- Lots of cosmetic changes

---
Changes in v2:
- Extracted the format validation/argument sanitization in a generic way for all printf-like helpers.
- bpf_snprintf's str_size can now be 0
- bpf_snprintf is now exposed to all BPF program types
- We now preempt_disable when using a per-cpu temporary buffer
- Addressed a few cosmetic changes

Florent Revest (6):
bpf: Factorize bpf_trace_printk and bpf_seq_printf
bpf: Add a ARG_PTR_TO_CONST_STR argument type
bpf: Add a bpf_snprintf helper
libbpf: Initialize the bpf_seq_printf parameters array field by field
libbpf: Introduce a BPF_SNPRINTF helper macro selftests/bpf: Add a series of tests for bpf_snprintf

 include/linux/bpf.h                           |  22 ++
 include/uapi/linux/bpf.h                      |  28 ++
 kernel/bpf/helpers.c                          | 306 ++++++++++++++
 kernel/bpf/verifier.c                         |  82 ++++
 kernel/trace/bpf_trace.c                      | 373 ++----------------
 tools/include/uapi/linux/bpf.h                |  28 ++
 tools/lib/bpf/bpf_tracing.h                   |  58 ++-
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++
 .../bpf/progs/test_snprintf_single.c          |  20 +
 10 files changed, 770 insertions(+), 345 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
Quoted 3 lines

--
2.31.1.368.gbe11c130af-goog

Looks great, thank you!

For the series:

#22 lore raw
Quoted 88 lines · Andrii Nakryiko
Quoted 82 lines · Florent Revest

We have a usecase where we want to audit symbol names (if available) in callback registration hooks. (ex: fentry/nf_register_net_hook)

A few months back, I proposed a bpf_kallsyms_lookup series but it was decided in the reviews that a more generic helper, bpf_snprintf, would be more useful.

This series implements the helper according to the feedback received in
https://lore.kernel.org/bpf/[email protected]/T/#u

- A new arg type guarantees the NULL-termination of string arguments and lets us pass format strings in only one arg
- A new helper is implemented using that guarantee. Because the format string is known at verification time, the format string validation is done by the verifier
- To implement a series of tests for bpf_snprintf, the logic for marshalling variadic args in a fixed-size array is reworked as per:
https://lore.kernel.org/bpf/[email protected]/T/#u

---
Changes in v5:
- Fixed the bpf_printf_buf_used counter logic in try_get_fmt_tmp_buf
- Added a couple of extra incorrect specifiers tests
- Call test_snprintf_single__destroy unconditionally
- Fixed a C++-style comment

---
Changes in v4:
- Moved bpf_snprintf, bpf_printf_prepare and bpf_printf_cleanup to kernel/bpf/helpers.c so that they get built without CONFIG_BPF_EVENTS
- Added negative test cases (various invalid format strings)
- Renamed put_fmt_tmp_buf() as bpf_printf_cleanup()
- Fixed a mistake that caused temporary buffers to be unconditionally freed in bpf_printf_prepare
- Fixed a mistake that caused missing 0 character to be ignored
- Fixed a warning about integer to pointer conversion
- Misc cleanups

---
Changes in v3:
- Simplified temporary buffer acquisition with try_get_fmt_tmp_buf()
- Made zero-termination check more consistent
- Allowed NULL output_buffer
- Simplified the BPF_CAST_FMT_ARG macro
- Three new test cases: number padding, simple string with no arg and string length extraction only with a NULL output buffer
- Clarified helper's description for edge cases (eg: str_size == 0)
- Lots of cosmetic changes

---
Changes in v2:
- Extracted the format validation/argument sanitization in a generic way for all printf-like helpers.
- bpf_snprintf's str_size can now be 0
- bpf_snprintf is now exposed to all BPF program types
- We now preempt_disable when using a per-cpu temporary buffer
- Addressed a few cosmetic changes

Florent Revest (6):
bpf: Factorize bpf_trace_printk and bpf_seq_printf
bpf: Add a ARG_PTR_TO_CONST_STR argument type
bpf: Add a bpf_snprintf helper
libbpf: Initialize the bpf_seq_printf parameters array field by field
libbpf: Introduce a BPF_SNPRINTF helper macro selftests/bpf: Add a series of tests for bpf_snprintf

 include/linux/bpf.h                           |  22 ++
 include/uapi/linux/bpf.h                      |  28 ++
 kernel/bpf/helpers.c                          | 306 ++++++++++++++
 kernel/bpf/verifier.c                         |  82 ++++
 kernel/trace/bpf_trace.c                      | 373 ++----------------
 tools/include/uapi/linux/bpf.h                |  28 ++
 tools/lib/bpf/bpf_tracing.h                   |  58 ++-
 .../selftests/bpf/prog_tests/snprintf.c       | 125 ++++++
 .../selftests/bpf/progs/test_snprintf.c       |  73 ++++
 .../bpf/progs/test_snprintf_single.c          |  20 +
 10 files changed, 770 insertions(+), 345 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf.c
 create mode 100644 tools/testing/selftests/bpf/progs/test_snprintf_single.c
Quoted 3 lines

--
2.31.1.368.gbe11c130af-goog

Quoted 5 lines

Looks great, thank you!

For the series:

Thank you for the all the fast and in-depth reviews Andrii! :)