1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2023 Meta Platforms, Inc. and affiliates. */
7 #include <bpf/bpf_helpers.h>
10 char _license[] SEC("license") = "GPL";
12 #define ITER_HELPERS \
13 __imm(bpf_iter_num_new), \
14 __imm(bpf_iter_num_next), \
15 __imm(bpf_iter_num_destroy)
19 int force_clang_to_emit_btf_for_externs(void *ctx)
21 /* we need this as a workaround to enforce compiler emitting BTF
22 * information for bpf_iter_num_{new,next,destroy}() kfuncs,
23 * as, apparently, it doesn't emit it for symbols only referenced from
24 * assembly (or cleanup attribute, for that matter, as well)
33 int consume_first_item_only(void *ctx)
35 struct bpf_iter_num iter;
42 "call %[bpf_iter_num_new];"
44 /* consume first item */
46 "call %[bpf_iter_num_next];"
49 "r0 = *(u32 *)(r0 + 0);"
51 /* destroy iterator */
53 "call %[bpf_iter_num_destroy];"
55 : __imm_ptr(iter), ITER_HELPERS
63 __failure __msg("R0 invalid mem access 'scalar'")
64 int missing_null_check_fail(void *ctx)
66 struct bpf_iter_num iter;
73 "call %[bpf_iter_num_new];"
75 /* consume first element */
77 "call %[bpf_iter_num_next];"
79 /* FAIL: deref with no NULL check */
80 "r1 = *(u32 *)(r0 + 0);"
82 /* destroy iterator */
84 "call %[bpf_iter_num_destroy];"
86 : __imm_ptr(iter), ITER_HELPERS
95 __msg("invalid access to memory, mem_size=4 off=0 size=8")
96 __msg("R0 min value is outside of the allowed memory range")
97 int wrong_sized_read_fail(void *ctx)
99 struct bpf_iter_num iter;
102 /* create iterator */
106 "call %[bpf_iter_num_new];"
108 /* consume first element */
110 "call %[bpf_iter_num_next];"
112 "if r0 == 0 goto +1;"
113 /* FAIL: deref more than available 4 bytes */
114 "r0 = *(u64 *)(r0 + 0);"
116 /* destroy iterator */
118 "call %[bpf_iter_num_destroy];"
120 : __imm_ptr(iter), ITER_HELPERS
128 __success __log_level(2)
129 __flag(BPF_F_TEST_STATE_FREQ)
130 int simplest_loop(void *ctx)
132 struct bpf_iter_num iter;
135 "r6 = 0;" /* init sum */
137 /* create iterator */
141 "call %[bpf_iter_num_new];"
144 /* consume next item */
146 "call %[bpf_iter_num_next];"
148 "if r0 == 0 goto 2f;"
149 "r0 = *(u32 *)(r0 + 0);"
150 "r6 += r0;" /* accumulate sum */
154 /* destroy iterator */
156 "call %[bpf_iter_num_destroy];"
158 : __imm_ptr(iter), ITER_HELPERS
159 : __clobber_common, "r6"