[PATCH v2 6/7] bpf: force generating code that all verifiers accept

Kris Van Hees <[email protected]>
Newsgroups dev.linux.lists.dtrace
Message-ID <SJ0PR10MB5672F6515402EC102F37A779C235A@SJ0PR10MB5672.namprd10.prod.outlook.com>
The compiler could optimize val = *valp in a way where the verifier on
older kernels would complain.  We use inline assembler to force the
not optimize this expression and instead to always read the value as a
scalar.

The kernel gained support for using map_value addresses read from the
stack with commit cd17d38f8b28f ("bpf: Permits pointers on stack for
helper calls") which first appeared in kernel 5.11.

Signed-off-by: Kris Van Hees <[email protected]>
Reviewed-by: Eugene Loh <[email protected]>
---
 bpf/get_dvar.c | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)

diff --git a/bpf/get_dvar.c b/bpf/get_dvar.c
index 073cca57c..aa14eca58 100644
--- a/bpf/get_dvar.c
+++ b/bpf/get_dvar.c
@@ -150,7 +150,24 @@ noinline void *dt_get_assoc(uint32_t id, const char *tuple, uint64_t store,
 		if (valp == 0)
 			return dt_no_dvar();
 		*valp = (uint64_t)valp;
-		val = *valp;
+		/*
+		 * We used to do:
+		 *	val = *valp;
+		 * but the compiler could use knowledge that *valp is valp from
+		 * the assignment above, and use that same value (whith is a
+		 * map_value address).  Older kernels do not allow a map_value
+		 * address to be used as map key, and a verifier failure would
+		 * be triggered by this code optimization.
+		 *
+		 * We use inline assembler to force reading the value from the
+		 * map value rather than allowing the compiler to optimize this
+		 * code.  This works for all kernels.
+		 */
+		asm ("ldxdw %0, %1" \
+			: "=r" (val) \
+			: "m" (*valp) \
+			: /* no clobber */
+		);
 	} else {
 		/*
 		 * Record the value (used as key into the dvars map), and if we
-- 
2.45.2
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.