[PATCH bpf-next v1 12/14] selftests/bpf: Fix array bounds warning in jit_disasm_helpers

Ihor Solodrai posted 14 patches 1 month, 2 weeks ago
There is a newer version of this series
[PATCH bpf-next v1 12/14] selftests/bpf: Fix array bounds warning in jit_disasm_helpers
Posted by Ihor Solodrai 1 month, 2 weeks ago
Compiler cannot infer upper bound for labels.cnt and warns about
potential buffer overflow in snprintf. Add an explicit bounds
check (... && i < MAX_LOCAL_LABELS) in the loop condition to fix the
warning.

Signed-off-by: Ihor Solodrai <ihor.solodrai@linux.dev>
---
 .../testing/selftests/bpf/jit_disasm_helpers.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/tools/testing/selftests/bpf/jit_disasm_helpers.c b/tools/testing/selftests/bpf/jit_disasm_helpers.c
index febd6b12e372..364c557c5115 100644
--- a/tools/testing/selftests/bpf/jit_disasm_helpers.c
+++ b/tools/testing/selftests/bpf/jit_disasm_helpers.c
@@ -122,15 +122,15 @@ static int disasm_one_func(FILE *text_out, uint8_t *image, __u32 len)
 		pc += cnt;
 	}
 	qsort(labels.pcs, labels.cnt, sizeof(*labels.pcs), cmp_u32);
-	for (i = 0; i < labels.cnt; ++i)
-		/* gcc is unable to infer upper bound for labels.cnt and assumes
-		 * it to be U32_MAX. U32_MAX takes 10 decimal digits.
-		 * snprintf below prints into labels.names[*],
-		 * which has space only for two digits and a letter.
-		 * To avoid truncation warning use (i % MAX_LOCAL_LABELS),
-		 * which informs gcc about printed value upper bound.
-		 */
-		snprintf(labels.names[i], sizeof(labels.names[i]), "L%d", i % MAX_LOCAL_LABELS);
+	/* gcc is unable to infer upper bound for labels.cnt and
+	 * assumes it to be U32_MAX. U32_MAX takes 10 decimal digits.
+	 * snprintf below prints into labels.names[*], which has space
+	 * only for two digits and a letter.  To avoid truncation
+	 * warning use (i < MAX_LOCAL_LABELS), which informs gcc about
+	 * printed value upper bound.
+	 */
+	for (i = 0; i < labels.cnt && i < MAX_LOCAL_LABELS; ++i)
+		snprintf(labels.names[i], sizeof(labels.names[i]), "L%d", i);
 
 	/* now print with labels */
 	labels.print_phase = true;
-- 
2.53.0
Re: [PATCH bpf-next v1 12/14] selftests/bpf: Fix array bounds warning in jit_disasm_helpers
Posted by Eduard Zingerman 1 month, 2 weeks ago
On Wed, 2026-02-11 at 17:13 -0800, Ihor Solodrai wrote:
> Compiler cannot infer upper bound for labels.cnt and warns about
> potential buffer overflow in snprintf. Add an explicit bounds
> check (... && i < MAX_LOCAL_LABELS) in the loop condition to fix the
> warning.
> 
> Signed-off-by: Ihor Solodrai <ihor.solodrai@linux.dev>
> ---

This annoying false positive strikes again :(

Acked-by: Eduard Zingerman <eddyz87@gmail.com>

[...]