bpf: fix compilation error without CGROUPS
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30
31 #include "disasm.h"
32
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35         [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171         /* verifer state is 'st'
172          * before processing instruction 'insn_idx'
173          * and after processing instruction 'prev_insn_idx'
174          */
175         struct bpf_verifier_state st;
176         int insn_idx;
177         int prev_insn_idx;
178         struct bpf_verifier_stack_elem *next;
179         /* length of verifier log at the time this state was pushed on stack */
180         u32 log_pos;
181 };
182
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
184 #define BPF_COMPLEXITY_LIMIT_STATES     64
185
186 #define BPF_MAP_KEY_POISON      (1ULL << 63)
187 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
188
189 #define BPF_MAP_PTR_UNPRIV      1UL
190 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
191                                           POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199                               struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201                              u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215                               const struct bpf_map *map, bool unpriv)
216 {
217         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218         unpriv |= bpf_map_ptr_unpriv(aux);
219         aux->map_ptr_state = (unsigned long)map |
220                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240         bool poisoned = bpf_map_key_poisoned(aux);
241
242         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248         return insn->code == (BPF_JMP | BPF_CALL) &&
249                insn->src_reg == 0;
250 }
251
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254         return insn->code == (BPF_JMP | BPF_CALL) &&
255                insn->src_reg == BPF_PSEUDO_CALL;
256 }
257
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260         return insn->code == (BPF_JMP | BPF_CALL) &&
261                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263
264 struct bpf_call_arg_meta {
265         struct bpf_map *map_ptr;
266         bool raw_mode;
267         bool pkt_access;
268         u8 release_regno;
269         int regno;
270         int access_size;
271         int mem_size;
272         u64 msize_max_value;
273         int ref_obj_id;
274         int dynptr_id;
275         int map_uid;
276         int func_id;
277         struct btf *btf;
278         u32 btf_id;
279         struct btf *ret_btf;
280         u32 ret_btf_id;
281         u32 subprogno;
282         struct btf_field *kptr_field;
283 };
284
285 struct bpf_kfunc_call_arg_meta {
286         /* In parameters */
287         struct btf *btf;
288         u32 func_id;
289         u32 kfunc_flags;
290         const struct btf_type *func_proto;
291         const char *func_name;
292         /* Out parameters */
293         u32 ref_obj_id;
294         u8 release_regno;
295         bool r0_rdonly;
296         u32 ret_btf_id;
297         u64 r0_size;
298         u32 subprogno;
299         struct {
300                 u64 value;
301                 bool found;
302         } arg_constant;
303
304         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305          * generally to pass info about user-defined local kptr types to later
306          * verification logic
307          *   bpf_obj_drop/bpf_percpu_obj_drop
308          *     Record the local kptr type to be drop'd
309          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310          *     Record the local kptr type to be refcount_incr'd and use
311          *     arg_owning_ref to determine whether refcount_acquire should be
312          *     fallible
313          */
314         struct btf *arg_btf;
315         u32 arg_btf_id;
316         bool arg_owning_ref;
317
318         struct {
319                 struct btf_field *field;
320         } arg_list_head;
321         struct {
322                 struct btf_field *field;
323         } arg_rbtree_root;
324         struct {
325                 enum bpf_dynptr_type type;
326                 u32 id;
327                 u32 ref_obj_id;
328         } initialized_dynptr;
329         struct {
330                 u8 spi;
331                 u8 frameno;
332         } iter;
333         u64 mem_size;
334 };
335
336 struct btf *btf_vmlinux;
337
338 static DEFINE_MUTEX(bpf_verifier_lock);
339
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343         const struct bpf_line_info *linfo;
344         const struct bpf_prog *prog;
345         u32 i, nr_linfo;
346
347         prog = env->prog;
348         nr_linfo = prog->aux->nr_linfo;
349
350         if (!nr_linfo || insn_off >= prog->len)
351                 return NULL;
352
353         linfo = prog->aux->linfo;
354         for (i = 1; i < nr_linfo; i++)
355                 if (insn_off < linfo[i].insn_off)
356                         break;
357
358         return &linfo[i - 1];
359 }
360
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363         struct bpf_verifier_env *env = private_data;
364         va_list args;
365
366         if (!bpf_verifier_log_needed(&env->log))
367                 return;
368
369         va_start(args, fmt);
370         bpf_verifier_vlog(&env->log, fmt, args);
371         va_end(args);
372 }
373
374 static const char *ltrim(const char *s)
375 {
376         while (isspace(*s))
377                 s++;
378
379         return s;
380 }
381
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383                                          u32 insn_off,
384                                          const char *prefix_fmt, ...)
385 {
386         const struct bpf_line_info *linfo;
387
388         if (!bpf_verifier_log_needed(&env->log))
389                 return;
390
391         linfo = find_linfo(env, insn_off);
392         if (!linfo || linfo == env->prev_linfo)
393                 return;
394
395         if (prefix_fmt) {
396                 va_list args;
397
398                 va_start(args, prefix_fmt);
399                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400                 va_end(args);
401         }
402
403         verbose(env, "%s\n",
404                 ltrim(btf_name_by_offset(env->prog->aux->btf,
405                                          linfo->line_off)));
406
407         env->prev_linfo = linfo;
408 }
409
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411                                    struct bpf_reg_state *reg,
412                                    struct tnum *range, const char *ctx,
413                                    const char *reg_name)
414 {
415         char tn_buf[48];
416
417         verbose(env, "At %s the register %s ", ctx, reg_name);
418         if (!tnum_is_unknown(reg->var_off)) {
419                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420                 verbose(env, "has value %s", tn_buf);
421         } else {
422                 verbose(env, "has unknown scalar value");
423         }
424         tnum_strn(tn_buf, sizeof(tn_buf), *range);
425         verbose(env, " should have been in %s\n", tn_buf);
426 }
427
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430         type = base_type(type);
431         return type == PTR_TO_PACKET ||
432                type == PTR_TO_PACKET_META;
433 }
434
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437         return type == PTR_TO_SOCKET ||
438                 type == PTR_TO_SOCK_COMMON ||
439                 type == PTR_TO_TCP_SOCK ||
440                 type == PTR_TO_XDP_SOCK;
441 }
442
443 static bool type_may_be_null(u32 type)
444 {
445         return type & PTR_MAYBE_NULL;
446 }
447
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450         enum bpf_reg_type type;
451
452         type = reg->type;
453         if (type_may_be_null(type))
454                 return false;
455
456         type = base_type(type);
457         return type == PTR_TO_SOCKET ||
458                 type == PTR_TO_TCP_SOCK ||
459                 type == PTR_TO_MAP_VALUE ||
460                 type == PTR_TO_MAP_KEY ||
461                 type == PTR_TO_SOCK_COMMON ||
462                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463                 type == PTR_TO_MEM;
464 }
465
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470
471 static bool type_is_non_owning_ref(u32 type)
472 {
473         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478         struct btf_record *rec = NULL;
479         struct btf_struct_meta *meta;
480
481         if (reg->type == PTR_TO_MAP_VALUE) {
482                 rec = reg->map_ptr->record;
483         } else if (type_is_ptr_alloc_obj(reg->type)) {
484                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485                 if (meta)
486                         rec = meta->record;
487         }
488         return rec;
489 }
490
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494
495         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502
503 static bool type_is_rdonly_mem(u32 type)
504 {
505         return type & MEM_RDONLY;
506 }
507
508 static bool is_acquire_function(enum bpf_func_id func_id,
509                                 const struct bpf_map *map)
510 {
511         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512
513         if (func_id == BPF_FUNC_sk_lookup_tcp ||
514             func_id == BPF_FUNC_sk_lookup_udp ||
515             func_id == BPF_FUNC_skc_lookup_tcp ||
516             func_id == BPF_FUNC_ringbuf_reserve ||
517             func_id == BPF_FUNC_kptr_xchg)
518                 return true;
519
520         if (func_id == BPF_FUNC_map_lookup_elem &&
521             (map_type == BPF_MAP_TYPE_SOCKMAP ||
522              map_type == BPF_MAP_TYPE_SOCKHASH))
523                 return true;
524
525         return false;
526 }
527
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530         return func_id == BPF_FUNC_tcp_sock ||
531                 func_id == BPF_FUNC_sk_fullsock ||
532                 func_id == BPF_FUNC_skc_to_tcp_sock ||
533                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
534                 func_id == BPF_FUNC_skc_to_udp6_sock ||
535                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542         return func_id == BPF_FUNC_dynptr_data;
543 }
544
545 static bool is_callback_calling_kfunc(u32 btf_id);
546 static bool is_bpf_throw_kfunc(struct bpf_insn *insn);
547
548 static bool is_callback_calling_function(enum bpf_func_id func_id)
549 {
550         return func_id == BPF_FUNC_for_each_map_elem ||
551                func_id == BPF_FUNC_timer_set_callback ||
552                func_id == BPF_FUNC_find_vma ||
553                func_id == BPF_FUNC_loop ||
554                func_id == BPF_FUNC_user_ringbuf_drain;
555 }
556
557 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
558 {
559         return func_id == BPF_FUNC_timer_set_callback;
560 }
561
562 static bool is_storage_get_function(enum bpf_func_id func_id)
563 {
564         return func_id == BPF_FUNC_sk_storage_get ||
565                func_id == BPF_FUNC_inode_storage_get ||
566                func_id == BPF_FUNC_task_storage_get ||
567                func_id == BPF_FUNC_cgrp_storage_get;
568 }
569
570 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
571                                         const struct bpf_map *map)
572 {
573         int ref_obj_uses = 0;
574
575         if (is_ptr_cast_function(func_id))
576                 ref_obj_uses++;
577         if (is_acquire_function(func_id, map))
578                 ref_obj_uses++;
579         if (is_dynptr_ref_function(func_id))
580                 ref_obj_uses++;
581
582         return ref_obj_uses > 1;
583 }
584
585 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
586 {
587         return BPF_CLASS(insn->code) == BPF_STX &&
588                BPF_MODE(insn->code) == BPF_ATOMIC &&
589                insn->imm == BPF_CMPXCHG;
590 }
591
592 /* string representation of 'enum bpf_reg_type'
593  *
594  * Note that reg_type_str() can not appear more than once in a single verbose()
595  * statement.
596  */
597 static const char *reg_type_str(struct bpf_verifier_env *env,
598                                 enum bpf_reg_type type)
599 {
600         char postfix[16] = {0}, prefix[64] = {0};
601         static const char * const str[] = {
602                 [NOT_INIT]              = "?",
603                 [SCALAR_VALUE]          = "scalar",
604                 [PTR_TO_CTX]            = "ctx",
605                 [CONST_PTR_TO_MAP]      = "map_ptr",
606                 [PTR_TO_MAP_VALUE]      = "map_value",
607                 [PTR_TO_STACK]          = "fp",
608                 [PTR_TO_PACKET]         = "pkt",
609                 [PTR_TO_PACKET_META]    = "pkt_meta",
610                 [PTR_TO_PACKET_END]     = "pkt_end",
611                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
612                 [PTR_TO_SOCKET]         = "sock",
613                 [PTR_TO_SOCK_COMMON]    = "sock_common",
614                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
615                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
616                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
617                 [PTR_TO_BTF_ID]         = "ptr_",
618                 [PTR_TO_MEM]            = "mem",
619                 [PTR_TO_BUF]            = "buf",
620                 [PTR_TO_FUNC]           = "func",
621                 [PTR_TO_MAP_KEY]        = "map_key",
622                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
623         };
624
625         if (type & PTR_MAYBE_NULL) {
626                 if (base_type(type) == PTR_TO_BTF_ID)
627                         strncpy(postfix, "or_null_", 16);
628                 else
629                         strncpy(postfix, "_or_null", 16);
630         }
631
632         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
633                  type & MEM_RDONLY ? "rdonly_" : "",
634                  type & MEM_RINGBUF ? "ringbuf_" : "",
635                  type & MEM_USER ? "user_" : "",
636                  type & MEM_PERCPU ? "percpu_" : "",
637                  type & MEM_RCU ? "rcu_" : "",
638                  type & PTR_UNTRUSTED ? "untrusted_" : "",
639                  type & PTR_TRUSTED ? "trusted_" : ""
640         );
641
642         snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
643                  prefix, str[base_type(type)], postfix);
644         return env->tmp_str_buf;
645 }
646
647 static char slot_type_char[] = {
648         [STACK_INVALID] = '?',
649         [STACK_SPILL]   = 'r',
650         [STACK_MISC]    = 'm',
651         [STACK_ZERO]    = '0',
652         [STACK_DYNPTR]  = 'd',
653         [STACK_ITER]    = 'i',
654 };
655
656 static void print_liveness(struct bpf_verifier_env *env,
657                            enum bpf_reg_liveness live)
658 {
659         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
660             verbose(env, "_");
661         if (live & REG_LIVE_READ)
662                 verbose(env, "r");
663         if (live & REG_LIVE_WRITTEN)
664                 verbose(env, "w");
665         if (live & REG_LIVE_DONE)
666                 verbose(env, "D");
667 }
668
669 static int __get_spi(s32 off)
670 {
671         return (-off - 1) / BPF_REG_SIZE;
672 }
673
674 static struct bpf_func_state *func(struct bpf_verifier_env *env,
675                                    const struct bpf_reg_state *reg)
676 {
677         struct bpf_verifier_state *cur = env->cur_state;
678
679         return cur->frame[reg->frameno];
680 }
681
682 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
683 {
684        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
685
686        /* We need to check that slots between [spi - nr_slots + 1, spi] are
687         * within [0, allocated_stack).
688         *
689         * Please note that the spi grows downwards. For example, a dynptr
690         * takes the size of two stack slots; the first slot will be at
691         * spi and the second slot will be at spi - 1.
692         */
693        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
694 }
695
696 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
697                                   const char *obj_kind, int nr_slots)
698 {
699         int off, spi;
700
701         if (!tnum_is_const(reg->var_off)) {
702                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
703                 return -EINVAL;
704         }
705
706         off = reg->off + reg->var_off.value;
707         if (off % BPF_REG_SIZE) {
708                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
709                 return -EINVAL;
710         }
711
712         spi = __get_spi(off);
713         if (spi + 1 < nr_slots) {
714                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
715                 return -EINVAL;
716         }
717
718         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
719                 return -ERANGE;
720         return spi;
721 }
722
723 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
724 {
725         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
726 }
727
728 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
729 {
730         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
731 }
732
733 static const char *btf_type_name(const struct btf *btf, u32 id)
734 {
735         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
736 }
737
738 static const char *dynptr_type_str(enum bpf_dynptr_type type)
739 {
740         switch (type) {
741         case BPF_DYNPTR_TYPE_LOCAL:
742                 return "local";
743         case BPF_DYNPTR_TYPE_RINGBUF:
744                 return "ringbuf";
745         case BPF_DYNPTR_TYPE_SKB:
746                 return "skb";
747         case BPF_DYNPTR_TYPE_XDP:
748                 return "xdp";
749         case BPF_DYNPTR_TYPE_INVALID:
750                 return "<invalid>";
751         default:
752                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
753                 return "<unknown>";
754         }
755 }
756
757 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
758 {
759         if (!btf || btf_id == 0)
760                 return "<invalid>";
761
762         /* we already validated that type is valid and has conforming name */
763         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
764 }
765
766 static const char *iter_state_str(enum bpf_iter_state state)
767 {
768         switch (state) {
769         case BPF_ITER_STATE_ACTIVE:
770                 return "active";
771         case BPF_ITER_STATE_DRAINED:
772                 return "drained";
773         case BPF_ITER_STATE_INVALID:
774                 return "<invalid>";
775         default:
776                 WARN_ONCE(1, "unknown iter state %d\n", state);
777                 return "<unknown>";
778         }
779 }
780
781 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
782 {
783         env->scratched_regs |= 1U << regno;
784 }
785
786 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
787 {
788         env->scratched_stack_slots |= 1ULL << spi;
789 }
790
791 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
792 {
793         return (env->scratched_regs >> regno) & 1;
794 }
795
796 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
797 {
798         return (env->scratched_stack_slots >> regno) & 1;
799 }
800
801 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
802 {
803         return env->scratched_regs || env->scratched_stack_slots;
804 }
805
806 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
807 {
808         env->scratched_regs = 0U;
809         env->scratched_stack_slots = 0ULL;
810 }
811
812 /* Used for printing the entire verifier state. */
813 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
814 {
815         env->scratched_regs = ~0U;
816         env->scratched_stack_slots = ~0ULL;
817 }
818
819 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
820 {
821         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
822         case DYNPTR_TYPE_LOCAL:
823                 return BPF_DYNPTR_TYPE_LOCAL;
824         case DYNPTR_TYPE_RINGBUF:
825                 return BPF_DYNPTR_TYPE_RINGBUF;
826         case DYNPTR_TYPE_SKB:
827                 return BPF_DYNPTR_TYPE_SKB;
828         case DYNPTR_TYPE_XDP:
829                 return BPF_DYNPTR_TYPE_XDP;
830         default:
831                 return BPF_DYNPTR_TYPE_INVALID;
832         }
833 }
834
835 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
836 {
837         switch (type) {
838         case BPF_DYNPTR_TYPE_LOCAL:
839                 return DYNPTR_TYPE_LOCAL;
840         case BPF_DYNPTR_TYPE_RINGBUF:
841                 return DYNPTR_TYPE_RINGBUF;
842         case BPF_DYNPTR_TYPE_SKB:
843                 return DYNPTR_TYPE_SKB;
844         case BPF_DYNPTR_TYPE_XDP:
845                 return DYNPTR_TYPE_XDP;
846         default:
847                 return 0;
848         }
849 }
850
851 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
852 {
853         return type == BPF_DYNPTR_TYPE_RINGBUF;
854 }
855
856 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
857                               enum bpf_dynptr_type type,
858                               bool first_slot, int dynptr_id);
859
860 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
861                                 struct bpf_reg_state *reg);
862
863 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
864                                    struct bpf_reg_state *sreg1,
865                                    struct bpf_reg_state *sreg2,
866                                    enum bpf_dynptr_type type)
867 {
868         int id = ++env->id_gen;
869
870         __mark_dynptr_reg(sreg1, type, true, id);
871         __mark_dynptr_reg(sreg2, type, false, id);
872 }
873
874 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
875                                struct bpf_reg_state *reg,
876                                enum bpf_dynptr_type type)
877 {
878         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
879 }
880
881 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
882                                         struct bpf_func_state *state, int spi);
883
884 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
885                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
886 {
887         struct bpf_func_state *state = func(env, reg);
888         enum bpf_dynptr_type type;
889         int spi, i, err;
890
891         spi = dynptr_get_spi(env, reg);
892         if (spi < 0)
893                 return spi;
894
895         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
896          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
897          * to ensure that for the following example:
898          *      [d1][d1][d2][d2]
899          * spi    3   2   1   0
900          * So marking spi = 2 should lead to destruction of both d1 and d2. In
901          * case they do belong to same dynptr, second call won't see slot_type
902          * as STACK_DYNPTR and will simply skip destruction.
903          */
904         err = destroy_if_dynptr_stack_slot(env, state, spi);
905         if (err)
906                 return err;
907         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
908         if (err)
909                 return err;
910
911         for (i = 0; i < BPF_REG_SIZE; i++) {
912                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
913                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
914         }
915
916         type = arg_to_dynptr_type(arg_type);
917         if (type == BPF_DYNPTR_TYPE_INVALID)
918                 return -EINVAL;
919
920         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
921                                &state->stack[spi - 1].spilled_ptr, type);
922
923         if (dynptr_type_refcounted(type)) {
924                 /* The id is used to track proper releasing */
925                 int id;
926
927                 if (clone_ref_obj_id)
928                         id = clone_ref_obj_id;
929                 else
930                         id = acquire_reference_state(env, insn_idx);
931
932                 if (id < 0)
933                         return id;
934
935                 state->stack[spi].spilled_ptr.ref_obj_id = id;
936                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
937         }
938
939         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
940         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
941
942         return 0;
943 }
944
945 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
946 {
947         int i;
948
949         for (i = 0; i < BPF_REG_SIZE; i++) {
950                 state->stack[spi].slot_type[i] = STACK_INVALID;
951                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
952         }
953
954         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
955         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
956
957         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
958          *
959          * While we don't allow reading STACK_INVALID, it is still possible to
960          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
961          * helpers or insns can do partial read of that part without failing,
962          * but check_stack_range_initialized, check_stack_read_var_off, and
963          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
964          * the slot conservatively. Hence we need to prevent those liveness
965          * marking walks.
966          *
967          * This was not a problem before because STACK_INVALID is only set by
968          * default (where the default reg state has its reg->parent as NULL), or
969          * in clean_live_states after REG_LIVE_DONE (at which point
970          * mark_reg_read won't walk reg->parent chain), but not randomly during
971          * verifier state exploration (like we did above). Hence, for our case
972          * parentage chain will still be live (i.e. reg->parent may be
973          * non-NULL), while earlier reg->parent was NULL, so we need
974          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
975          * done later on reads or by mark_dynptr_read as well to unnecessary
976          * mark registers in verifier state.
977          */
978         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
979         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
980 }
981
982 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
983 {
984         struct bpf_func_state *state = func(env, reg);
985         int spi, ref_obj_id, i;
986
987         spi = dynptr_get_spi(env, reg);
988         if (spi < 0)
989                 return spi;
990
991         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
992                 invalidate_dynptr(env, state, spi);
993                 return 0;
994         }
995
996         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
997
998         /* If the dynptr has a ref_obj_id, then we need to invalidate
999          * two things:
1000          *
1001          * 1) Any dynptrs with a matching ref_obj_id (clones)
1002          * 2) Any slices derived from this dynptr.
1003          */
1004
1005         /* Invalidate any slices associated with this dynptr */
1006         WARN_ON_ONCE(release_reference(env, ref_obj_id));
1007
1008         /* Invalidate any dynptr clones */
1009         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1010                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1011                         continue;
1012
1013                 /* it should always be the case that if the ref obj id
1014                  * matches then the stack slot also belongs to a
1015                  * dynptr
1016                  */
1017                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1018                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1019                         return -EFAULT;
1020                 }
1021                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1022                         invalidate_dynptr(env, state, i);
1023         }
1024
1025         return 0;
1026 }
1027
1028 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1029                                struct bpf_reg_state *reg);
1030
1031 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1032 {
1033         if (!env->allow_ptr_leaks)
1034                 __mark_reg_not_init(env, reg);
1035         else
1036                 __mark_reg_unknown(env, reg);
1037 }
1038
1039 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1040                                         struct bpf_func_state *state, int spi)
1041 {
1042         struct bpf_func_state *fstate;
1043         struct bpf_reg_state *dreg;
1044         int i, dynptr_id;
1045
1046         /* We always ensure that STACK_DYNPTR is never set partially,
1047          * hence just checking for slot_type[0] is enough. This is
1048          * different for STACK_SPILL, where it may be only set for
1049          * 1 byte, so code has to use is_spilled_reg.
1050          */
1051         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1052                 return 0;
1053
1054         /* Reposition spi to first slot */
1055         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1056                 spi = spi + 1;
1057
1058         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1059                 verbose(env, "cannot overwrite referenced dynptr\n");
1060                 return -EINVAL;
1061         }
1062
1063         mark_stack_slot_scratched(env, spi);
1064         mark_stack_slot_scratched(env, spi - 1);
1065
1066         /* Writing partially to one dynptr stack slot destroys both. */
1067         for (i = 0; i < BPF_REG_SIZE; i++) {
1068                 state->stack[spi].slot_type[i] = STACK_INVALID;
1069                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1070         }
1071
1072         dynptr_id = state->stack[spi].spilled_ptr.id;
1073         /* Invalidate any slices associated with this dynptr */
1074         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1075                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1076                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1077                         continue;
1078                 if (dreg->dynptr_id == dynptr_id)
1079                         mark_reg_invalid(env, dreg);
1080         }));
1081
1082         /* Do not release reference state, we are destroying dynptr on stack,
1083          * not using some helper to release it. Just reset register.
1084          */
1085         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1086         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1087
1088         /* Same reason as unmark_stack_slots_dynptr above */
1089         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1090         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1091
1092         return 0;
1093 }
1094
1095 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1096 {
1097         int spi;
1098
1099         if (reg->type == CONST_PTR_TO_DYNPTR)
1100                 return false;
1101
1102         spi = dynptr_get_spi(env, reg);
1103
1104         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1105          * error because this just means the stack state hasn't been updated yet.
1106          * We will do check_mem_access to check and update stack bounds later.
1107          */
1108         if (spi < 0 && spi != -ERANGE)
1109                 return false;
1110
1111         /* We don't need to check if the stack slots are marked by previous
1112          * dynptr initializations because we allow overwriting existing unreferenced
1113          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1114          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1115          * touching are completely destructed before we reinitialize them for a new
1116          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1117          * instead of delaying it until the end where the user will get "Unreleased
1118          * reference" error.
1119          */
1120         return true;
1121 }
1122
1123 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1124 {
1125         struct bpf_func_state *state = func(env, reg);
1126         int i, spi;
1127
1128         /* This already represents first slot of initialized bpf_dynptr.
1129          *
1130          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1131          * check_func_arg_reg_off's logic, so we don't need to check its
1132          * offset and alignment.
1133          */
1134         if (reg->type == CONST_PTR_TO_DYNPTR)
1135                 return true;
1136
1137         spi = dynptr_get_spi(env, reg);
1138         if (spi < 0)
1139                 return false;
1140         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1141                 return false;
1142
1143         for (i = 0; i < BPF_REG_SIZE; i++) {
1144                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1145                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1146                         return false;
1147         }
1148
1149         return true;
1150 }
1151
1152 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1153                                     enum bpf_arg_type arg_type)
1154 {
1155         struct bpf_func_state *state = func(env, reg);
1156         enum bpf_dynptr_type dynptr_type;
1157         int spi;
1158
1159         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1160         if (arg_type == ARG_PTR_TO_DYNPTR)
1161                 return true;
1162
1163         dynptr_type = arg_to_dynptr_type(arg_type);
1164         if (reg->type == CONST_PTR_TO_DYNPTR) {
1165                 return reg->dynptr.type == dynptr_type;
1166         } else {
1167                 spi = dynptr_get_spi(env, reg);
1168                 if (spi < 0)
1169                         return false;
1170                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1171         }
1172 }
1173
1174 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1175
1176 static bool in_rcu_cs(struct bpf_verifier_env *env);
1177
1178 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta);
1179
1180 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1181                                  struct bpf_kfunc_call_arg_meta *meta,
1182                                  struct bpf_reg_state *reg, int insn_idx,
1183                                  struct btf *btf, u32 btf_id, int nr_slots)
1184 {
1185         struct bpf_func_state *state = func(env, reg);
1186         int spi, i, j, id;
1187
1188         spi = iter_get_spi(env, reg, nr_slots);
1189         if (spi < 0)
1190                 return spi;
1191
1192         id = acquire_reference_state(env, insn_idx);
1193         if (id < 0)
1194                 return id;
1195
1196         for (i = 0; i < nr_slots; i++) {
1197                 struct bpf_stack_state *slot = &state->stack[spi - i];
1198                 struct bpf_reg_state *st = &slot->spilled_ptr;
1199
1200                 __mark_reg_known_zero(st);
1201                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1202                 if (is_kfunc_rcu_protected(meta)) {
1203                         if (in_rcu_cs(env))
1204                                 st->type |= MEM_RCU;
1205                         else
1206                                 st->type |= PTR_UNTRUSTED;
1207                 }
1208                 st->live |= REG_LIVE_WRITTEN;
1209                 st->ref_obj_id = i == 0 ? id : 0;
1210                 st->iter.btf = btf;
1211                 st->iter.btf_id = btf_id;
1212                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1213                 st->iter.depth = 0;
1214
1215                 for (j = 0; j < BPF_REG_SIZE; j++)
1216                         slot->slot_type[j] = STACK_ITER;
1217
1218                 mark_stack_slot_scratched(env, spi - i);
1219         }
1220
1221         return 0;
1222 }
1223
1224 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1225                                    struct bpf_reg_state *reg, int nr_slots)
1226 {
1227         struct bpf_func_state *state = func(env, reg);
1228         int spi, i, j;
1229
1230         spi = iter_get_spi(env, reg, nr_slots);
1231         if (spi < 0)
1232                 return spi;
1233
1234         for (i = 0; i < nr_slots; i++) {
1235                 struct bpf_stack_state *slot = &state->stack[spi - i];
1236                 struct bpf_reg_state *st = &slot->spilled_ptr;
1237
1238                 if (i == 0)
1239                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1240
1241                 __mark_reg_not_init(env, st);
1242
1243                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1244                 st->live |= REG_LIVE_WRITTEN;
1245
1246                 for (j = 0; j < BPF_REG_SIZE; j++)
1247                         slot->slot_type[j] = STACK_INVALID;
1248
1249                 mark_stack_slot_scratched(env, spi - i);
1250         }
1251
1252         return 0;
1253 }
1254
1255 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1256                                      struct bpf_reg_state *reg, int nr_slots)
1257 {
1258         struct bpf_func_state *state = func(env, reg);
1259         int spi, i, j;
1260
1261         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1262          * will do check_mem_access to check and update stack bounds later, so
1263          * return true for that case.
1264          */
1265         spi = iter_get_spi(env, reg, nr_slots);
1266         if (spi == -ERANGE)
1267                 return true;
1268         if (spi < 0)
1269                 return false;
1270
1271         for (i = 0; i < nr_slots; i++) {
1272                 struct bpf_stack_state *slot = &state->stack[spi - i];
1273
1274                 for (j = 0; j < BPF_REG_SIZE; j++)
1275                         if (slot->slot_type[j] == STACK_ITER)
1276                                 return false;
1277         }
1278
1279         return true;
1280 }
1281
1282 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1283                                    struct btf *btf, u32 btf_id, int nr_slots)
1284 {
1285         struct bpf_func_state *state = func(env, reg);
1286         int spi, i, j;
1287
1288         spi = iter_get_spi(env, reg, nr_slots);
1289         if (spi < 0)
1290                 return -EINVAL;
1291
1292         for (i = 0; i < nr_slots; i++) {
1293                 struct bpf_stack_state *slot = &state->stack[spi - i];
1294                 struct bpf_reg_state *st = &slot->spilled_ptr;
1295
1296                 if (st->type & PTR_UNTRUSTED)
1297                         return -EPROTO;
1298                 /* only main (first) slot has ref_obj_id set */
1299                 if (i == 0 && !st->ref_obj_id)
1300                         return -EINVAL;
1301                 if (i != 0 && st->ref_obj_id)
1302                         return -EINVAL;
1303                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1304                         return -EINVAL;
1305
1306                 for (j = 0; j < BPF_REG_SIZE; j++)
1307                         if (slot->slot_type[j] != STACK_ITER)
1308                                 return -EINVAL;
1309         }
1310
1311         return 0;
1312 }
1313
1314 /* Check if given stack slot is "special":
1315  *   - spilled register state (STACK_SPILL);
1316  *   - dynptr state (STACK_DYNPTR);
1317  *   - iter state (STACK_ITER).
1318  */
1319 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1320 {
1321         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1322
1323         switch (type) {
1324         case STACK_SPILL:
1325         case STACK_DYNPTR:
1326         case STACK_ITER:
1327                 return true;
1328         case STACK_INVALID:
1329         case STACK_MISC:
1330         case STACK_ZERO:
1331                 return false;
1332         default:
1333                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1334                 return true;
1335         }
1336 }
1337
1338 /* The reg state of a pointer or a bounded scalar was saved when
1339  * it was spilled to the stack.
1340  */
1341 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1342 {
1343         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1344 }
1345
1346 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1347 {
1348         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1349                stack->spilled_ptr.type == SCALAR_VALUE;
1350 }
1351
1352 static void scrub_spilled_slot(u8 *stype)
1353 {
1354         if (*stype != STACK_INVALID)
1355                 *stype = STACK_MISC;
1356 }
1357
1358 static void print_scalar_ranges(struct bpf_verifier_env *env,
1359                                 const struct bpf_reg_state *reg,
1360                                 const char **sep)
1361 {
1362         struct {
1363                 const char *name;
1364                 u64 val;
1365                 bool omit;
1366         } minmaxs[] = {
1367                 {"smin",   reg->smin_value,         reg->smin_value == S64_MIN},
1368                 {"smax",   reg->smax_value,         reg->smax_value == S64_MAX},
1369                 {"umin",   reg->umin_value,         reg->umin_value == 0},
1370                 {"umax",   reg->umax_value,         reg->umax_value == U64_MAX},
1371                 {"smin32", (s64)reg->s32_min_value, reg->s32_min_value == S32_MIN},
1372                 {"smax32", (s64)reg->s32_max_value, reg->s32_max_value == S32_MAX},
1373                 {"umin32", reg->u32_min_value,      reg->u32_min_value == 0},
1374                 {"umax32", reg->u32_max_value,      reg->u32_max_value == U32_MAX},
1375         }, *m1, *m2, *mend = &minmaxs[ARRAY_SIZE(minmaxs)];
1376         bool neg1, neg2;
1377
1378         for (m1 = &minmaxs[0]; m1 < mend; m1++) {
1379                 if (m1->omit)
1380                         continue;
1381
1382                 neg1 = m1->name[0] == 's' && (s64)m1->val < 0;
1383
1384                 verbose(env, "%s%s=", *sep, m1->name);
1385                 *sep = ",";
1386
1387                 for (m2 = m1 + 2; m2 < mend; m2 += 2) {
1388                         if (m2->omit || m2->val != m1->val)
1389                                 continue;
1390                         /* don't mix negatives with positives */
1391                         neg2 = m2->name[0] == 's' && (s64)m2->val < 0;
1392                         if (neg2 != neg1)
1393                                 continue;
1394                         m2->omit = true;
1395                         verbose(env, "%s=", m2->name);
1396                 }
1397
1398                 verbose(env, m1->name[0] == 's' ? "%lld" : "%llu", m1->val);
1399         }
1400 }
1401
1402 static void print_verifier_state(struct bpf_verifier_env *env,
1403                                  const struct bpf_func_state *state,
1404                                  bool print_all)
1405 {
1406         const struct bpf_reg_state *reg;
1407         enum bpf_reg_type t;
1408         int i;
1409
1410         if (state->frameno)
1411                 verbose(env, " frame%d:", state->frameno);
1412         for (i = 0; i < MAX_BPF_REG; i++) {
1413                 reg = &state->regs[i];
1414                 t = reg->type;
1415                 if (t == NOT_INIT)
1416                         continue;
1417                 if (!print_all && !reg_scratched(env, i))
1418                         continue;
1419                 verbose(env, " R%d", i);
1420                 print_liveness(env, reg->live);
1421                 verbose(env, "=");
1422                 if (t == SCALAR_VALUE && reg->precise)
1423                         verbose(env, "P");
1424                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1425                     tnum_is_const(reg->var_off)) {
1426                         /* reg->off should be 0 for SCALAR_VALUE */
1427                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1428                         verbose(env, "%lld", reg->var_off.value + reg->off);
1429                 } else {
1430                         const char *sep = "";
1431
1432                         verbose(env, "%s", reg_type_str(env, t));
1433                         if (base_type(t) == PTR_TO_BTF_ID)
1434                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1435                         verbose(env, "(");
1436 /*
1437  * _a stands for append, was shortened to avoid multiline statements below.
1438  * This macro is used to output a comma separated list of attributes.
1439  */
1440 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1441
1442                         if (reg->id)
1443                                 verbose_a("id=%d", reg->id);
1444                         if (reg->ref_obj_id)
1445                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1446                         if (type_is_non_owning_ref(reg->type))
1447                                 verbose_a("%s", "non_own_ref");
1448                         if (t != SCALAR_VALUE)
1449                                 verbose_a("off=%d", reg->off);
1450                         if (type_is_pkt_pointer(t))
1451                                 verbose_a("r=%d", reg->range);
1452                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1453                                  base_type(t) == PTR_TO_MAP_KEY ||
1454                                  base_type(t) == PTR_TO_MAP_VALUE)
1455                                 verbose_a("ks=%d,vs=%d",
1456                                           reg->map_ptr->key_size,
1457                                           reg->map_ptr->value_size);
1458                         if (tnum_is_const(reg->var_off)) {
1459                                 /* Typically an immediate SCALAR_VALUE, but
1460                                  * could be a pointer whose offset is too big
1461                                  * for reg->off
1462                                  */
1463                                 verbose_a("imm=%llx", reg->var_off.value);
1464                         } else {
1465                                 print_scalar_ranges(env, reg, &sep);
1466                                 if (!tnum_is_unknown(reg->var_off)) {
1467                                         char tn_buf[48];
1468
1469                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1470                                         verbose_a("var_off=%s", tn_buf);
1471                                 }
1472                         }
1473 #undef verbose_a
1474
1475                         verbose(env, ")");
1476                 }
1477         }
1478         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1479                 char types_buf[BPF_REG_SIZE + 1];
1480                 bool valid = false;
1481                 int j;
1482
1483                 for (j = 0; j < BPF_REG_SIZE; j++) {
1484                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1485                                 valid = true;
1486                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1487                 }
1488                 types_buf[BPF_REG_SIZE] = 0;
1489                 if (!valid)
1490                         continue;
1491                 if (!print_all && !stack_slot_scratched(env, i))
1492                         continue;
1493                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1494                 case STACK_SPILL:
1495                         reg = &state->stack[i].spilled_ptr;
1496                         t = reg->type;
1497
1498                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1499                         print_liveness(env, reg->live);
1500                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1501                         if (t == SCALAR_VALUE && reg->precise)
1502                                 verbose(env, "P");
1503                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1504                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1505                         break;
1506                 case STACK_DYNPTR:
1507                         i += BPF_DYNPTR_NR_SLOTS - 1;
1508                         reg = &state->stack[i].spilled_ptr;
1509
1510                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1511                         print_liveness(env, reg->live);
1512                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1513                         if (reg->ref_obj_id)
1514                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1515                         break;
1516                 case STACK_ITER:
1517                         /* only main slot has ref_obj_id set; skip others */
1518                         reg = &state->stack[i].spilled_ptr;
1519                         if (!reg->ref_obj_id)
1520                                 continue;
1521
1522                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1523                         print_liveness(env, reg->live);
1524                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1525                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1526                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1527                                 reg->iter.depth);
1528                         break;
1529                 case STACK_MISC:
1530                 case STACK_ZERO:
1531                 default:
1532                         reg = &state->stack[i].spilled_ptr;
1533
1534                         for (j = 0; j < BPF_REG_SIZE; j++)
1535                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1536                         types_buf[BPF_REG_SIZE] = 0;
1537
1538                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1539                         print_liveness(env, reg->live);
1540                         verbose(env, "=%s", types_buf);
1541                         break;
1542                 }
1543         }
1544         if (state->acquired_refs && state->refs[0].id) {
1545                 verbose(env, " refs=%d", state->refs[0].id);
1546                 for (i = 1; i < state->acquired_refs; i++)
1547                         if (state->refs[i].id)
1548                                 verbose(env, ",%d", state->refs[i].id);
1549         }
1550         if (state->in_callback_fn)
1551                 verbose(env, " cb");
1552         if (state->in_async_callback_fn)
1553                 verbose(env, " async_cb");
1554         verbose(env, "\n");
1555         if (!print_all)
1556                 mark_verifier_state_clean(env);
1557 }
1558
1559 static inline u32 vlog_alignment(u32 pos)
1560 {
1561         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1562                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1563 }
1564
1565 static void print_insn_state(struct bpf_verifier_env *env,
1566                              const struct bpf_func_state *state)
1567 {
1568         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1569                 /* remove new line character */
1570                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1571                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1572         } else {
1573                 verbose(env, "%d:", env->insn_idx);
1574         }
1575         print_verifier_state(env, state, false);
1576 }
1577
1578 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1579  * small to hold src. This is different from krealloc since we don't want to preserve
1580  * the contents of dst.
1581  *
1582  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1583  * not be allocated.
1584  */
1585 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1586 {
1587         size_t alloc_bytes;
1588         void *orig = dst;
1589         size_t bytes;
1590
1591         if (ZERO_OR_NULL_PTR(src))
1592                 goto out;
1593
1594         if (unlikely(check_mul_overflow(n, size, &bytes)))
1595                 return NULL;
1596
1597         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1598         dst = krealloc(orig, alloc_bytes, flags);
1599         if (!dst) {
1600                 kfree(orig);
1601                 return NULL;
1602         }
1603
1604         memcpy(dst, src, bytes);
1605 out:
1606         return dst ? dst : ZERO_SIZE_PTR;
1607 }
1608
1609 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1610  * small to hold new_n items. new items are zeroed out if the array grows.
1611  *
1612  * Contrary to krealloc_array, does not free arr if new_n is zero.
1613  */
1614 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1615 {
1616         size_t alloc_size;
1617         void *new_arr;
1618
1619         if (!new_n || old_n == new_n)
1620                 goto out;
1621
1622         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1623         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1624         if (!new_arr) {
1625                 kfree(arr);
1626                 return NULL;
1627         }
1628         arr = new_arr;
1629
1630         if (new_n > old_n)
1631                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1632
1633 out:
1634         return arr ? arr : ZERO_SIZE_PTR;
1635 }
1636
1637 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1638 {
1639         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1640                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1641         if (!dst->refs)
1642                 return -ENOMEM;
1643
1644         dst->acquired_refs = src->acquired_refs;
1645         return 0;
1646 }
1647
1648 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1649 {
1650         size_t n = src->allocated_stack / BPF_REG_SIZE;
1651
1652         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1653                                 GFP_KERNEL);
1654         if (!dst->stack)
1655                 return -ENOMEM;
1656
1657         dst->allocated_stack = src->allocated_stack;
1658         return 0;
1659 }
1660
1661 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1662 {
1663         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1664                                     sizeof(struct bpf_reference_state));
1665         if (!state->refs)
1666                 return -ENOMEM;
1667
1668         state->acquired_refs = n;
1669         return 0;
1670 }
1671
1672 static int grow_stack_state(struct bpf_func_state *state, int size)
1673 {
1674         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1675
1676         if (old_n >= n)
1677                 return 0;
1678
1679         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1680         if (!state->stack)
1681                 return -ENOMEM;
1682
1683         state->allocated_stack = size;
1684         return 0;
1685 }
1686
1687 /* Acquire a pointer id from the env and update the state->refs to include
1688  * this new pointer reference.
1689  * On success, returns a valid pointer id to associate with the register
1690  * On failure, returns a negative errno.
1691  */
1692 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1693 {
1694         struct bpf_func_state *state = cur_func(env);
1695         int new_ofs = state->acquired_refs;
1696         int id, err;
1697
1698         err = resize_reference_state(state, state->acquired_refs + 1);
1699         if (err)
1700                 return err;
1701         id = ++env->id_gen;
1702         state->refs[new_ofs].id = id;
1703         state->refs[new_ofs].insn_idx = insn_idx;
1704         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1705
1706         return id;
1707 }
1708
1709 /* release function corresponding to acquire_reference_state(). Idempotent. */
1710 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1711 {
1712         int i, last_idx;
1713
1714         last_idx = state->acquired_refs - 1;
1715         for (i = 0; i < state->acquired_refs; i++) {
1716                 if (state->refs[i].id == ptr_id) {
1717                         /* Cannot release caller references in callbacks */
1718                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1719                                 return -EINVAL;
1720                         if (last_idx && i != last_idx)
1721                                 memcpy(&state->refs[i], &state->refs[last_idx],
1722                                        sizeof(*state->refs));
1723                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1724                         state->acquired_refs--;
1725                         return 0;
1726                 }
1727         }
1728         return -EINVAL;
1729 }
1730
1731 static void free_func_state(struct bpf_func_state *state)
1732 {
1733         if (!state)
1734                 return;
1735         kfree(state->refs);
1736         kfree(state->stack);
1737         kfree(state);
1738 }
1739
1740 static void clear_jmp_history(struct bpf_verifier_state *state)
1741 {
1742         kfree(state->jmp_history);
1743         state->jmp_history = NULL;
1744         state->jmp_history_cnt = 0;
1745 }
1746
1747 static void free_verifier_state(struct bpf_verifier_state *state,
1748                                 bool free_self)
1749 {
1750         int i;
1751
1752         for (i = 0; i <= state->curframe; i++) {
1753                 free_func_state(state->frame[i]);
1754                 state->frame[i] = NULL;
1755         }
1756         clear_jmp_history(state);
1757         if (free_self)
1758                 kfree(state);
1759 }
1760
1761 /* copy verifier state from src to dst growing dst stack space
1762  * when necessary to accommodate larger src stack
1763  */
1764 static int copy_func_state(struct bpf_func_state *dst,
1765                            const struct bpf_func_state *src)
1766 {
1767         int err;
1768
1769         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1770         err = copy_reference_state(dst, src);
1771         if (err)
1772                 return err;
1773         return copy_stack_state(dst, src);
1774 }
1775
1776 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1777                                const struct bpf_verifier_state *src)
1778 {
1779         struct bpf_func_state *dst;
1780         int i, err;
1781
1782         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1783                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1784                                             GFP_USER);
1785         if (!dst_state->jmp_history)
1786                 return -ENOMEM;
1787         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1788
1789         /* if dst has more stack frames then src frame, free them, this is also
1790          * necessary in case of exceptional exits using bpf_throw.
1791          */
1792         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1793                 free_func_state(dst_state->frame[i]);
1794                 dst_state->frame[i] = NULL;
1795         }
1796         dst_state->speculative = src->speculative;
1797         dst_state->active_rcu_lock = src->active_rcu_lock;
1798         dst_state->curframe = src->curframe;
1799         dst_state->active_lock.ptr = src->active_lock.ptr;
1800         dst_state->active_lock.id = src->active_lock.id;
1801         dst_state->branches = src->branches;
1802         dst_state->parent = src->parent;
1803         dst_state->first_insn_idx = src->first_insn_idx;
1804         dst_state->last_insn_idx = src->last_insn_idx;
1805         dst_state->dfs_depth = src->dfs_depth;
1806         dst_state->used_as_loop_entry = src->used_as_loop_entry;
1807         for (i = 0; i <= src->curframe; i++) {
1808                 dst = dst_state->frame[i];
1809                 if (!dst) {
1810                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1811                         if (!dst)
1812                                 return -ENOMEM;
1813                         dst_state->frame[i] = dst;
1814                 }
1815                 err = copy_func_state(dst, src->frame[i]);
1816                 if (err)
1817                         return err;
1818         }
1819         return 0;
1820 }
1821
1822 static u32 state_htab_size(struct bpf_verifier_env *env)
1823 {
1824         return env->prog->len;
1825 }
1826
1827 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx)
1828 {
1829         struct bpf_verifier_state *cur = env->cur_state;
1830         struct bpf_func_state *state = cur->frame[cur->curframe];
1831
1832         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
1833 }
1834
1835 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b)
1836 {
1837         int fr;
1838
1839         if (a->curframe != b->curframe)
1840                 return false;
1841
1842         for (fr = a->curframe; fr >= 0; fr--)
1843                 if (a->frame[fr]->callsite != b->frame[fr]->callsite)
1844                         return false;
1845
1846         return true;
1847 }
1848
1849 /* Open coded iterators allow back-edges in the state graph in order to
1850  * check unbounded loops that iterators.
1851  *
1852  * In is_state_visited() it is necessary to know if explored states are
1853  * part of some loops in order to decide whether non-exact states
1854  * comparison could be used:
1855  * - non-exact states comparison establishes sub-state relation and uses
1856  *   read and precision marks to do so, these marks are propagated from
1857  *   children states and thus are not guaranteed to be final in a loop;
1858  * - exact states comparison just checks if current and explored states
1859  *   are identical (and thus form a back-edge).
1860  *
1861  * Paper "A New Algorithm for Identifying Loops in Decompilation"
1862  * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient
1863  * algorithm for loop structure detection and gives an overview of
1864  * relevant terminology. It also has helpful illustrations.
1865  *
1866  * [1] https://api.semanticscholar.org/CorpusID:15784067
1867  *
1868  * We use a similar algorithm but because loop nested structure is
1869  * irrelevant for verifier ours is significantly simpler and resembles
1870  * strongly connected components algorithm from Sedgewick's textbook.
1871  *
1872  * Define topmost loop entry as a first node of the loop traversed in a
1873  * depth first search starting from initial state. The goal of the loop
1874  * tracking algorithm is to associate topmost loop entries with states
1875  * derived from these entries.
1876  *
1877  * For each step in the DFS states traversal algorithm needs to identify
1878  * the following situations:
1879  *
1880  *          initial                     initial                   initial
1881  *            |                           |                         |
1882  *            V                           V                         V
1883  *           ...                         ...           .---------> hdr
1884  *            |                           |            |            |
1885  *            V                           V            |            V
1886  *           cur                     .-> succ          |    .------...
1887  *            |                      |    |            |    |       |
1888  *            V                      |    V            |    V       V
1889  *           succ                    '-- cur           |   ...     ...
1890  *                                                     |    |       |
1891  *                                                     |    V       V
1892  *                                                     |   succ <- cur
1893  *                                                     |    |
1894  *                                                     |    V
1895  *                                                     |   ...
1896  *                                                     |    |
1897  *                                                     '----'
1898  *
1899  *  (A) successor state of cur   (B) successor state of cur or it's entry
1900  *      not yet traversed            are in current DFS path, thus cur and succ
1901  *                                   are members of the same outermost loop
1902  *
1903  *                      initial                  initial
1904  *                        |                        |
1905  *                        V                        V
1906  *                       ...                      ...
1907  *                        |                        |
1908  *                        V                        V
1909  *                .------...               .------...
1910  *                |       |                |       |
1911  *                V       V                V       V
1912  *           .-> hdr     ...              ...     ...
1913  *           |    |       |                |       |
1914  *           |    V       V                V       V
1915  *           |   succ <- cur              succ <- cur
1916  *           |    |                        |
1917  *           |    V                        V
1918  *           |   ...                      ...
1919  *           |    |                        |
1920  *           '----'                       exit
1921  *
1922  * (C) successor state of cur is a part of some loop but this loop
1923  *     does not include cur or successor state is not in a loop at all.
1924  *
1925  * Algorithm could be described as the following python code:
1926  *
1927  *     traversed = set()   # Set of traversed nodes
1928  *     entries = {}        # Mapping from node to loop entry
1929  *     depths = {}         # Depth level assigned to graph node
1930  *     path = set()        # Current DFS path
1931  *
1932  *     # Find outermost loop entry known for n
1933  *     def get_loop_entry(n):
1934  *         h = entries.get(n, None)
1935  *         while h in entries and entries[h] != h:
1936  *             h = entries[h]
1937  *         return h
1938  *
1939  *     # Update n's loop entry if h's outermost entry comes
1940  *     # before n's outermost entry in current DFS path.
1941  *     def update_loop_entry(n, h):
1942  *         n1 = get_loop_entry(n) or n
1943  *         h1 = get_loop_entry(h) or h
1944  *         if h1 in path and depths[h1] <= depths[n1]:
1945  *             entries[n] = h1
1946  *
1947  *     def dfs(n, depth):
1948  *         traversed.add(n)
1949  *         path.add(n)
1950  *         depths[n] = depth
1951  *         for succ in G.successors(n):
1952  *             if succ not in traversed:
1953  *                 # Case A: explore succ and update cur's loop entry
1954  *                 #         only if succ's entry is in current DFS path.
1955  *                 dfs(succ, depth + 1)
1956  *                 h = get_loop_entry(succ)
1957  *                 update_loop_entry(n, h)
1958  *             else:
1959  *                 # Case B or C depending on `h1 in path` check in update_loop_entry().
1960  *                 update_loop_entry(n, succ)
1961  *         path.remove(n)
1962  *
1963  * To adapt this algorithm for use with verifier:
1964  * - use st->branch == 0 as a signal that DFS of succ had been finished
1965  *   and cur's loop entry has to be updated (case A), handle this in
1966  *   update_branch_counts();
1967  * - use st->branch > 0 as a signal that st is in the current DFS path;
1968  * - handle cases B and C in is_state_visited();
1969  * - update topmost loop entry for intermediate states in get_loop_entry().
1970  */
1971 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st)
1972 {
1973         struct bpf_verifier_state *topmost = st->loop_entry, *old;
1974
1975         while (topmost && topmost->loop_entry && topmost != topmost->loop_entry)
1976                 topmost = topmost->loop_entry;
1977         /* Update loop entries for intermediate states to avoid this
1978          * traversal in future get_loop_entry() calls.
1979          */
1980         while (st && st->loop_entry != topmost) {
1981                 old = st->loop_entry;
1982                 st->loop_entry = topmost;
1983                 st = old;
1984         }
1985         return topmost;
1986 }
1987
1988 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr)
1989 {
1990         struct bpf_verifier_state *cur1, *hdr1;
1991
1992         cur1 = get_loop_entry(cur) ?: cur;
1993         hdr1 = get_loop_entry(hdr) ?: hdr;
1994         /* The head1->branches check decides between cases B and C in
1995          * comment for get_loop_entry(). If hdr1->branches == 0 then
1996          * head's topmost loop entry is not in current DFS path,
1997          * hence 'cur' and 'hdr' are not in the same loop and there is
1998          * no need to update cur->loop_entry.
1999          */
2000         if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) {
2001                 cur->loop_entry = hdr;
2002                 hdr->used_as_loop_entry = true;
2003         }
2004 }
2005
2006 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
2007 {
2008         while (st) {
2009                 u32 br = --st->branches;
2010
2011                 /* br == 0 signals that DFS exploration for 'st' is finished,
2012                  * thus it is necessary to update parent's loop entry if it
2013                  * turned out that st is a part of some loop.
2014                  * This is a part of 'case A' in get_loop_entry() comment.
2015                  */
2016                 if (br == 0 && st->parent && st->loop_entry)
2017                         update_loop_entry(st->parent, st->loop_entry);
2018
2019                 /* WARN_ON(br > 1) technically makes sense here,
2020                  * but see comment in push_stack(), hence:
2021                  */
2022                 WARN_ONCE((int)br < 0,
2023                           "BUG update_branch_counts:branches_to_explore=%d\n",
2024                           br);
2025                 if (br)
2026                         break;
2027                 st = st->parent;
2028         }
2029 }
2030
2031 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
2032                      int *insn_idx, bool pop_log)
2033 {
2034         struct bpf_verifier_state *cur = env->cur_state;
2035         struct bpf_verifier_stack_elem *elem, *head = env->head;
2036         int err;
2037
2038         if (env->head == NULL)
2039                 return -ENOENT;
2040
2041         if (cur) {
2042                 err = copy_verifier_state(cur, &head->st);
2043                 if (err)
2044                         return err;
2045         }
2046         if (pop_log)
2047                 bpf_vlog_reset(&env->log, head->log_pos);
2048         if (insn_idx)
2049                 *insn_idx = head->insn_idx;
2050         if (prev_insn_idx)
2051                 *prev_insn_idx = head->prev_insn_idx;
2052         elem = head->next;
2053         free_verifier_state(&head->st, false);
2054         kfree(head);
2055         env->head = elem;
2056         env->stack_size--;
2057         return 0;
2058 }
2059
2060 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
2061                                              int insn_idx, int prev_insn_idx,
2062                                              bool speculative)
2063 {
2064         struct bpf_verifier_state *cur = env->cur_state;
2065         struct bpf_verifier_stack_elem *elem;
2066         int err;
2067
2068         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2069         if (!elem)
2070                 goto err;
2071
2072         elem->insn_idx = insn_idx;
2073         elem->prev_insn_idx = prev_insn_idx;
2074         elem->next = env->head;
2075         elem->log_pos = env->log.end_pos;
2076         env->head = elem;
2077         env->stack_size++;
2078         err = copy_verifier_state(&elem->st, cur);
2079         if (err)
2080                 goto err;
2081         elem->st.speculative |= speculative;
2082         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2083                 verbose(env, "The sequence of %d jumps is too complex.\n",
2084                         env->stack_size);
2085                 goto err;
2086         }
2087         if (elem->st.parent) {
2088                 ++elem->st.parent->branches;
2089                 /* WARN_ON(branches > 2) technically makes sense here,
2090                  * but
2091                  * 1. speculative states will bump 'branches' for non-branch
2092                  * instructions
2093                  * 2. is_state_visited() heuristics may decide not to create
2094                  * a new state for a sequence of branches and all such current
2095                  * and cloned states will be pointing to a single parent state
2096                  * which might have large 'branches' count.
2097                  */
2098         }
2099         return &elem->st;
2100 err:
2101         free_verifier_state(env->cur_state, true);
2102         env->cur_state = NULL;
2103         /* pop all elements and return */
2104         while (!pop_stack(env, NULL, NULL, false));
2105         return NULL;
2106 }
2107
2108 #define CALLER_SAVED_REGS 6
2109 static const int caller_saved[CALLER_SAVED_REGS] = {
2110         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
2111 };
2112
2113 /* This helper doesn't clear reg->id */
2114 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2115 {
2116         reg->var_off = tnum_const(imm);
2117         reg->smin_value = (s64)imm;
2118         reg->smax_value = (s64)imm;
2119         reg->umin_value = imm;
2120         reg->umax_value = imm;
2121
2122         reg->s32_min_value = (s32)imm;
2123         reg->s32_max_value = (s32)imm;
2124         reg->u32_min_value = (u32)imm;
2125         reg->u32_max_value = (u32)imm;
2126 }
2127
2128 /* Mark the unknown part of a register (variable offset or scalar value) as
2129  * known to have the value @imm.
2130  */
2131 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
2132 {
2133         /* Clear off and union(map_ptr, range) */
2134         memset(((u8 *)reg) + sizeof(reg->type), 0,
2135                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
2136         reg->id = 0;
2137         reg->ref_obj_id = 0;
2138         ___mark_reg_known(reg, imm);
2139 }
2140
2141 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
2142 {
2143         reg->var_off = tnum_const_subreg(reg->var_off, imm);
2144         reg->s32_min_value = (s32)imm;
2145         reg->s32_max_value = (s32)imm;
2146         reg->u32_min_value = (u32)imm;
2147         reg->u32_max_value = (u32)imm;
2148 }
2149
2150 /* Mark the 'variable offset' part of a register as zero.  This should be
2151  * used only on registers holding a pointer type.
2152  */
2153 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
2154 {
2155         __mark_reg_known(reg, 0);
2156 }
2157
2158 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
2159 {
2160         __mark_reg_known(reg, 0);
2161         reg->type = SCALAR_VALUE;
2162 }
2163
2164 static void mark_reg_known_zero(struct bpf_verifier_env *env,
2165                                 struct bpf_reg_state *regs, u32 regno)
2166 {
2167         if (WARN_ON(regno >= MAX_BPF_REG)) {
2168                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
2169                 /* Something bad happened, let's kill all regs */
2170                 for (regno = 0; regno < MAX_BPF_REG; regno++)
2171                         __mark_reg_not_init(env, regs + regno);
2172                 return;
2173         }
2174         __mark_reg_known_zero(regs + regno);
2175 }
2176
2177 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
2178                               bool first_slot, int dynptr_id)
2179 {
2180         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
2181          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
2182          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
2183          */
2184         __mark_reg_known_zero(reg);
2185         reg->type = CONST_PTR_TO_DYNPTR;
2186         /* Give each dynptr a unique id to uniquely associate slices to it. */
2187         reg->id = dynptr_id;
2188         reg->dynptr.type = type;
2189         reg->dynptr.first_slot = first_slot;
2190 }
2191
2192 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
2193 {
2194         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
2195                 const struct bpf_map *map = reg->map_ptr;
2196
2197                 if (map->inner_map_meta) {
2198                         reg->type = CONST_PTR_TO_MAP;
2199                         reg->map_ptr = map->inner_map_meta;
2200                         /* transfer reg's id which is unique for every map_lookup_elem
2201                          * as UID of the inner map.
2202                          */
2203                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
2204                                 reg->map_uid = reg->id;
2205                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
2206                         reg->type = PTR_TO_XDP_SOCK;
2207                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
2208                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
2209                         reg->type = PTR_TO_SOCKET;
2210                 } else {
2211                         reg->type = PTR_TO_MAP_VALUE;
2212                 }
2213                 return;
2214         }
2215
2216         reg->type &= ~PTR_MAYBE_NULL;
2217 }
2218
2219 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
2220                                 struct btf_field_graph_root *ds_head)
2221 {
2222         __mark_reg_known_zero(&regs[regno]);
2223         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
2224         regs[regno].btf = ds_head->btf;
2225         regs[regno].btf_id = ds_head->value_btf_id;
2226         regs[regno].off = ds_head->node_offset;
2227 }
2228
2229 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
2230 {
2231         return type_is_pkt_pointer(reg->type);
2232 }
2233
2234 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2235 {
2236         return reg_is_pkt_pointer(reg) ||
2237                reg->type == PTR_TO_PACKET_END;
2238 }
2239
2240 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2241 {
2242         return base_type(reg->type) == PTR_TO_MEM &&
2243                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2244 }
2245
2246 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2247 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2248                                     enum bpf_reg_type which)
2249 {
2250         /* The register can already have a range from prior markings.
2251          * This is fine as long as it hasn't been advanced from its
2252          * origin.
2253          */
2254         return reg->type == which &&
2255                reg->id == 0 &&
2256                reg->off == 0 &&
2257                tnum_equals_const(reg->var_off, 0);
2258 }
2259
2260 /* Reset the min/max bounds of a register */
2261 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2262 {
2263         reg->smin_value = S64_MIN;
2264         reg->smax_value = S64_MAX;
2265         reg->umin_value = 0;
2266         reg->umax_value = U64_MAX;
2267
2268         reg->s32_min_value = S32_MIN;
2269         reg->s32_max_value = S32_MAX;
2270         reg->u32_min_value = 0;
2271         reg->u32_max_value = U32_MAX;
2272 }
2273
2274 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2275 {
2276         reg->smin_value = S64_MIN;
2277         reg->smax_value = S64_MAX;
2278         reg->umin_value = 0;
2279         reg->umax_value = U64_MAX;
2280 }
2281
2282 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2283 {
2284         reg->s32_min_value = S32_MIN;
2285         reg->s32_max_value = S32_MAX;
2286         reg->u32_min_value = 0;
2287         reg->u32_max_value = U32_MAX;
2288 }
2289
2290 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2291 {
2292         struct tnum var32_off = tnum_subreg(reg->var_off);
2293
2294         /* min signed is max(sign bit) | min(other bits) */
2295         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2296                         var32_off.value | (var32_off.mask & S32_MIN));
2297         /* max signed is min(sign bit) | max(other bits) */
2298         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2299                         var32_off.value | (var32_off.mask & S32_MAX));
2300         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2301         reg->u32_max_value = min(reg->u32_max_value,
2302                                  (u32)(var32_off.value | var32_off.mask));
2303 }
2304
2305 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2306 {
2307         /* min signed is max(sign bit) | min(other bits) */
2308         reg->smin_value = max_t(s64, reg->smin_value,
2309                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2310         /* max signed is min(sign bit) | max(other bits) */
2311         reg->smax_value = min_t(s64, reg->smax_value,
2312                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2313         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2314         reg->umax_value = min(reg->umax_value,
2315                               reg->var_off.value | reg->var_off.mask);
2316 }
2317
2318 static void __update_reg_bounds(struct bpf_reg_state *reg)
2319 {
2320         __update_reg32_bounds(reg);
2321         __update_reg64_bounds(reg);
2322 }
2323
2324 /* Uses signed min/max values to inform unsigned, and vice-versa */
2325 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2326 {
2327         /* Learn sign from signed bounds.
2328          * If we cannot cross the sign boundary, then signed and unsigned bounds
2329          * are the same, so combine.  This works even in the negative case, e.g.
2330          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2331          */
2332         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2333                 reg->s32_min_value = reg->u32_min_value =
2334                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2335                 reg->s32_max_value = reg->u32_max_value =
2336                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2337                 return;
2338         }
2339         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2340          * boundary, so we must be careful.
2341          */
2342         if ((s32)reg->u32_max_value >= 0) {
2343                 /* Positive.  We can't learn anything from the smin, but smax
2344                  * is positive, hence safe.
2345                  */
2346                 reg->s32_min_value = reg->u32_min_value;
2347                 reg->s32_max_value = reg->u32_max_value =
2348                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2349         } else if ((s32)reg->u32_min_value < 0) {
2350                 /* Negative.  We can't learn anything from the smax, but smin
2351                  * is negative, hence safe.
2352                  */
2353                 reg->s32_min_value = reg->u32_min_value =
2354                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2355                 reg->s32_max_value = reg->u32_max_value;
2356         }
2357 }
2358
2359 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2360 {
2361         /* Learn sign from signed bounds.
2362          * If we cannot cross the sign boundary, then signed and unsigned bounds
2363          * are the same, so combine.  This works even in the negative case, e.g.
2364          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2365          */
2366         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2367                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2368                                                           reg->umin_value);
2369                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2370                                                           reg->umax_value);
2371                 return;
2372         }
2373         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2374          * boundary, so we must be careful.
2375          */
2376         if ((s64)reg->umax_value >= 0) {
2377                 /* Positive.  We can't learn anything from the smin, but smax
2378                  * is positive, hence safe.
2379                  */
2380                 reg->smin_value = reg->umin_value;
2381                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2382                                                           reg->umax_value);
2383         } else if ((s64)reg->umin_value < 0) {
2384                 /* Negative.  We can't learn anything from the smax, but smin
2385                  * is negative, hence safe.
2386                  */
2387                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2388                                                           reg->umin_value);
2389                 reg->smax_value = reg->umax_value;
2390         }
2391 }
2392
2393 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2394 {
2395         __reg32_deduce_bounds(reg);
2396         __reg64_deduce_bounds(reg);
2397 }
2398
2399 /* Attempts to improve var_off based on unsigned min/max information */
2400 static void __reg_bound_offset(struct bpf_reg_state *reg)
2401 {
2402         struct tnum var64_off = tnum_intersect(reg->var_off,
2403                                                tnum_range(reg->umin_value,
2404                                                           reg->umax_value));
2405         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2406                                                tnum_range(reg->u32_min_value,
2407                                                           reg->u32_max_value));
2408
2409         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2410 }
2411
2412 static void reg_bounds_sync(struct bpf_reg_state *reg)
2413 {
2414         /* We might have learned new bounds from the var_off. */
2415         __update_reg_bounds(reg);
2416         /* We might have learned something about the sign bit. */
2417         __reg_deduce_bounds(reg);
2418         /* We might have learned some bits from the bounds. */
2419         __reg_bound_offset(reg);
2420         /* Intersecting with the old var_off might have improved our bounds
2421          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2422          * then new var_off is (0; 0x7f...fc) which improves our umax.
2423          */
2424         __update_reg_bounds(reg);
2425 }
2426
2427 static bool __reg32_bound_s64(s32 a)
2428 {
2429         return a >= 0 && a <= S32_MAX;
2430 }
2431
2432 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2433 {
2434         reg->umin_value = reg->u32_min_value;
2435         reg->umax_value = reg->u32_max_value;
2436
2437         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2438          * be positive otherwise set to worse case bounds and refine later
2439          * from tnum.
2440          */
2441         if (__reg32_bound_s64(reg->s32_min_value) &&
2442             __reg32_bound_s64(reg->s32_max_value)) {
2443                 reg->smin_value = reg->s32_min_value;
2444                 reg->smax_value = reg->s32_max_value;
2445         } else {
2446                 reg->smin_value = 0;
2447                 reg->smax_value = U32_MAX;
2448         }
2449 }
2450
2451 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2452 {
2453         /* special case when 64-bit register has upper 32-bit register
2454          * zeroed. Typically happens after zext or <<32, >>32 sequence
2455          * allowing us to use 32-bit bounds directly,
2456          */
2457         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2458                 __reg_assign_32_into_64(reg);
2459         } else {
2460                 /* Otherwise the best we can do is push lower 32bit known and
2461                  * unknown bits into register (var_off set from jmp logic)
2462                  * then learn as much as possible from the 64-bit tnum
2463                  * known and unknown bits. The previous smin/smax bounds are
2464                  * invalid here because of jmp32 compare so mark them unknown
2465                  * so they do not impact tnum bounds calculation.
2466                  */
2467                 __mark_reg64_unbounded(reg);
2468         }
2469         reg_bounds_sync(reg);
2470 }
2471
2472 static bool __reg64_bound_s32(s64 a)
2473 {
2474         return a >= S32_MIN && a <= S32_MAX;
2475 }
2476
2477 static bool __reg64_bound_u32(u64 a)
2478 {
2479         return a >= U32_MIN && a <= U32_MAX;
2480 }
2481
2482 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2483 {
2484         __mark_reg32_unbounded(reg);
2485         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2486                 reg->s32_min_value = (s32)reg->smin_value;
2487                 reg->s32_max_value = (s32)reg->smax_value;
2488         }
2489         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2490                 reg->u32_min_value = (u32)reg->umin_value;
2491                 reg->u32_max_value = (u32)reg->umax_value;
2492         }
2493         reg_bounds_sync(reg);
2494 }
2495
2496 /* Mark a register as having a completely unknown (scalar) value. */
2497 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2498                                struct bpf_reg_state *reg)
2499 {
2500         /*
2501          * Clear type, off, and union(map_ptr, range) and
2502          * padding between 'type' and union
2503          */
2504         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2505         reg->type = SCALAR_VALUE;
2506         reg->id = 0;
2507         reg->ref_obj_id = 0;
2508         reg->var_off = tnum_unknown;
2509         reg->frameno = 0;
2510         reg->precise = !env->bpf_capable;
2511         __mark_reg_unbounded(reg);
2512 }
2513
2514 static void mark_reg_unknown(struct bpf_verifier_env *env,
2515                              struct bpf_reg_state *regs, u32 regno)
2516 {
2517         if (WARN_ON(regno >= MAX_BPF_REG)) {
2518                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2519                 /* Something bad happened, let's kill all regs except FP */
2520                 for (regno = 0; regno < BPF_REG_FP; regno++)
2521                         __mark_reg_not_init(env, regs + regno);
2522                 return;
2523         }
2524         __mark_reg_unknown(env, regs + regno);
2525 }
2526
2527 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2528                                 struct bpf_reg_state *reg)
2529 {
2530         __mark_reg_unknown(env, reg);
2531         reg->type = NOT_INIT;
2532 }
2533
2534 static void mark_reg_not_init(struct bpf_verifier_env *env,
2535                               struct bpf_reg_state *regs, u32 regno)
2536 {
2537         if (WARN_ON(regno >= MAX_BPF_REG)) {
2538                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2539                 /* Something bad happened, let's kill all regs except FP */
2540                 for (regno = 0; regno < BPF_REG_FP; regno++)
2541                         __mark_reg_not_init(env, regs + regno);
2542                 return;
2543         }
2544         __mark_reg_not_init(env, regs + regno);
2545 }
2546
2547 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2548                             struct bpf_reg_state *regs, u32 regno,
2549                             enum bpf_reg_type reg_type,
2550                             struct btf *btf, u32 btf_id,
2551                             enum bpf_type_flag flag)
2552 {
2553         if (reg_type == SCALAR_VALUE) {
2554                 mark_reg_unknown(env, regs, regno);
2555                 return;
2556         }
2557         mark_reg_known_zero(env, regs, regno);
2558         regs[regno].type = PTR_TO_BTF_ID | flag;
2559         regs[regno].btf = btf;
2560         regs[regno].btf_id = btf_id;
2561 }
2562
2563 #define DEF_NOT_SUBREG  (0)
2564 static void init_reg_state(struct bpf_verifier_env *env,
2565                            struct bpf_func_state *state)
2566 {
2567         struct bpf_reg_state *regs = state->regs;
2568         int i;
2569
2570         for (i = 0; i < MAX_BPF_REG; i++) {
2571                 mark_reg_not_init(env, regs, i);
2572                 regs[i].live = REG_LIVE_NONE;
2573                 regs[i].parent = NULL;
2574                 regs[i].subreg_def = DEF_NOT_SUBREG;
2575         }
2576
2577         /* frame pointer */
2578         regs[BPF_REG_FP].type = PTR_TO_STACK;
2579         mark_reg_known_zero(env, regs, BPF_REG_FP);
2580         regs[BPF_REG_FP].frameno = state->frameno;
2581 }
2582
2583 #define BPF_MAIN_FUNC (-1)
2584 static void init_func_state(struct bpf_verifier_env *env,
2585                             struct bpf_func_state *state,
2586                             int callsite, int frameno, int subprogno)
2587 {
2588         state->callsite = callsite;
2589         state->frameno = frameno;
2590         state->subprogno = subprogno;
2591         state->callback_ret_range = tnum_range(0, 0);
2592         init_reg_state(env, state);
2593         mark_verifier_state_scratched(env);
2594 }
2595
2596 /* Similar to push_stack(), but for async callbacks */
2597 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2598                                                 int insn_idx, int prev_insn_idx,
2599                                                 int subprog)
2600 {
2601         struct bpf_verifier_stack_elem *elem;
2602         struct bpf_func_state *frame;
2603
2604         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2605         if (!elem)
2606                 goto err;
2607
2608         elem->insn_idx = insn_idx;
2609         elem->prev_insn_idx = prev_insn_idx;
2610         elem->next = env->head;
2611         elem->log_pos = env->log.end_pos;
2612         env->head = elem;
2613         env->stack_size++;
2614         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2615                 verbose(env,
2616                         "The sequence of %d jumps is too complex for async cb.\n",
2617                         env->stack_size);
2618                 goto err;
2619         }
2620         /* Unlike push_stack() do not copy_verifier_state().
2621          * The caller state doesn't matter.
2622          * This is async callback. It starts in a fresh stack.
2623          * Initialize it similar to do_check_common().
2624          */
2625         elem->st.branches = 1;
2626         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2627         if (!frame)
2628                 goto err;
2629         init_func_state(env, frame,
2630                         BPF_MAIN_FUNC /* callsite */,
2631                         0 /* frameno within this callchain */,
2632                         subprog /* subprog number within this prog */);
2633         elem->st.frame[0] = frame;
2634         return &elem->st;
2635 err:
2636         free_verifier_state(env->cur_state, true);
2637         env->cur_state = NULL;
2638         /* pop all elements and return */
2639         while (!pop_stack(env, NULL, NULL, false));
2640         return NULL;
2641 }
2642
2643
2644 enum reg_arg_type {
2645         SRC_OP,         /* register is used as source operand */
2646         DST_OP,         /* register is used as destination operand */
2647         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2648 };
2649
2650 static int cmp_subprogs(const void *a, const void *b)
2651 {
2652         return ((struct bpf_subprog_info *)a)->start -
2653                ((struct bpf_subprog_info *)b)->start;
2654 }
2655
2656 static int find_subprog(struct bpf_verifier_env *env, int off)
2657 {
2658         struct bpf_subprog_info *p;
2659
2660         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2661                     sizeof(env->subprog_info[0]), cmp_subprogs);
2662         if (!p)
2663                 return -ENOENT;
2664         return p - env->subprog_info;
2665
2666 }
2667
2668 static int add_subprog(struct bpf_verifier_env *env, int off)
2669 {
2670         int insn_cnt = env->prog->len;
2671         int ret;
2672
2673         if (off >= insn_cnt || off < 0) {
2674                 verbose(env, "call to invalid destination\n");
2675                 return -EINVAL;
2676         }
2677         ret = find_subprog(env, off);
2678         if (ret >= 0)
2679                 return ret;
2680         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2681                 verbose(env, "too many subprograms\n");
2682                 return -E2BIG;
2683         }
2684         /* determine subprog starts. The end is one before the next starts */
2685         env->subprog_info[env->subprog_cnt++].start = off;
2686         sort(env->subprog_info, env->subprog_cnt,
2687              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2688         return env->subprog_cnt - 1;
2689 }
2690
2691 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env)
2692 {
2693         struct bpf_prog_aux *aux = env->prog->aux;
2694         struct btf *btf = aux->btf;
2695         const struct btf_type *t;
2696         u32 main_btf_id, id;
2697         const char *name;
2698         int ret, i;
2699
2700         /* Non-zero func_info_cnt implies valid btf */
2701         if (!aux->func_info_cnt)
2702                 return 0;
2703         main_btf_id = aux->func_info[0].type_id;
2704
2705         t = btf_type_by_id(btf, main_btf_id);
2706         if (!t) {
2707                 verbose(env, "invalid btf id for main subprog in func_info\n");
2708                 return -EINVAL;
2709         }
2710
2711         name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:");
2712         if (IS_ERR(name)) {
2713                 ret = PTR_ERR(name);
2714                 /* If there is no tag present, there is no exception callback */
2715                 if (ret == -ENOENT)
2716                         ret = 0;
2717                 else if (ret == -EEXIST)
2718                         verbose(env, "multiple exception callback tags for main subprog\n");
2719                 return ret;
2720         }
2721
2722         ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
2723         if (ret < 0) {
2724                 verbose(env, "exception callback '%s' could not be found in BTF\n", name);
2725                 return ret;
2726         }
2727         id = ret;
2728         t = btf_type_by_id(btf, id);
2729         if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) {
2730                 verbose(env, "exception callback '%s' must have global linkage\n", name);
2731                 return -EINVAL;
2732         }
2733         ret = 0;
2734         for (i = 0; i < aux->func_info_cnt; i++) {
2735                 if (aux->func_info[i].type_id != id)
2736                         continue;
2737                 ret = aux->func_info[i].insn_off;
2738                 /* Further func_info and subprog checks will also happen
2739                  * later, so assume this is the right insn_off for now.
2740                  */
2741                 if (!ret) {
2742                         verbose(env, "invalid exception callback insn_off in func_info: 0\n");
2743                         ret = -EINVAL;
2744                 }
2745         }
2746         if (!ret) {
2747                 verbose(env, "exception callback type id not found in func_info\n");
2748                 ret = -EINVAL;
2749         }
2750         return ret;
2751 }
2752
2753 #define MAX_KFUNC_DESCS 256
2754 #define MAX_KFUNC_BTFS  256
2755
2756 struct bpf_kfunc_desc {
2757         struct btf_func_model func_model;
2758         u32 func_id;
2759         s32 imm;
2760         u16 offset;
2761         unsigned long addr;
2762 };
2763
2764 struct bpf_kfunc_btf {
2765         struct btf *btf;
2766         struct module *module;
2767         u16 offset;
2768 };
2769
2770 struct bpf_kfunc_desc_tab {
2771         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2772          * verification. JITs do lookups by bpf_insn, where func_id may not be
2773          * available, therefore at the end of verification do_misc_fixups()
2774          * sorts this by imm and offset.
2775          */
2776         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2777         u32 nr_descs;
2778 };
2779
2780 struct bpf_kfunc_btf_tab {
2781         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2782         u32 nr_descs;
2783 };
2784
2785 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2786 {
2787         const struct bpf_kfunc_desc *d0 = a;
2788         const struct bpf_kfunc_desc *d1 = b;
2789
2790         /* func_id is not greater than BTF_MAX_TYPE */
2791         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2792 }
2793
2794 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2795 {
2796         const struct bpf_kfunc_btf *d0 = a;
2797         const struct bpf_kfunc_btf *d1 = b;
2798
2799         return d0->offset - d1->offset;
2800 }
2801
2802 static const struct bpf_kfunc_desc *
2803 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2804 {
2805         struct bpf_kfunc_desc desc = {
2806                 .func_id = func_id,
2807                 .offset = offset,
2808         };
2809         struct bpf_kfunc_desc_tab *tab;
2810
2811         tab = prog->aux->kfunc_tab;
2812         return bsearch(&desc, tab->descs, tab->nr_descs,
2813                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2814 }
2815
2816 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2817                        u16 btf_fd_idx, u8 **func_addr)
2818 {
2819         const struct bpf_kfunc_desc *desc;
2820
2821         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2822         if (!desc)
2823                 return -EFAULT;
2824
2825         *func_addr = (u8 *)desc->addr;
2826         return 0;
2827 }
2828
2829 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2830                                          s16 offset)
2831 {
2832         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2833         struct bpf_kfunc_btf_tab *tab;
2834         struct bpf_kfunc_btf *b;
2835         struct module *mod;
2836         struct btf *btf;
2837         int btf_fd;
2838
2839         tab = env->prog->aux->kfunc_btf_tab;
2840         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2841                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2842         if (!b) {
2843                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2844                         verbose(env, "too many different module BTFs\n");
2845                         return ERR_PTR(-E2BIG);
2846                 }
2847
2848                 if (bpfptr_is_null(env->fd_array)) {
2849                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2850                         return ERR_PTR(-EPROTO);
2851                 }
2852
2853                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2854                                             offset * sizeof(btf_fd),
2855                                             sizeof(btf_fd)))
2856                         return ERR_PTR(-EFAULT);
2857
2858                 btf = btf_get_by_fd(btf_fd);
2859                 if (IS_ERR(btf)) {
2860                         verbose(env, "invalid module BTF fd specified\n");
2861                         return btf;
2862                 }
2863
2864                 if (!btf_is_module(btf)) {
2865                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2866                         btf_put(btf);
2867                         return ERR_PTR(-EINVAL);
2868                 }
2869
2870                 mod = btf_try_get_module(btf);
2871                 if (!mod) {
2872                         btf_put(btf);
2873                         return ERR_PTR(-ENXIO);
2874                 }
2875
2876                 b = &tab->descs[tab->nr_descs++];
2877                 b->btf = btf;
2878                 b->module = mod;
2879                 b->offset = offset;
2880
2881                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2882                      kfunc_btf_cmp_by_off, NULL);
2883         }
2884         return b->btf;
2885 }
2886
2887 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2888 {
2889         if (!tab)
2890                 return;
2891
2892         while (tab->nr_descs--) {
2893                 module_put(tab->descs[tab->nr_descs].module);
2894                 btf_put(tab->descs[tab->nr_descs].btf);
2895         }
2896         kfree(tab);
2897 }
2898
2899 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2900 {
2901         if (offset) {
2902                 if (offset < 0) {
2903                         /* In the future, this can be allowed to increase limit
2904                          * of fd index into fd_array, interpreted as u16.
2905                          */
2906                         verbose(env, "negative offset disallowed for kernel module function call\n");
2907                         return ERR_PTR(-EINVAL);
2908                 }
2909
2910                 return __find_kfunc_desc_btf(env, offset);
2911         }
2912         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2913 }
2914
2915 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2916 {
2917         const struct btf_type *func, *func_proto;
2918         struct bpf_kfunc_btf_tab *btf_tab;
2919         struct bpf_kfunc_desc_tab *tab;
2920         struct bpf_prog_aux *prog_aux;
2921         struct bpf_kfunc_desc *desc;
2922         const char *func_name;
2923         struct btf *desc_btf;
2924         unsigned long call_imm;
2925         unsigned long addr;
2926         int err;
2927
2928         prog_aux = env->prog->aux;
2929         tab = prog_aux->kfunc_tab;
2930         btf_tab = prog_aux->kfunc_btf_tab;
2931         if (!tab) {
2932                 if (!btf_vmlinux) {
2933                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2934                         return -ENOTSUPP;
2935                 }
2936
2937                 if (!env->prog->jit_requested) {
2938                         verbose(env, "JIT is required for calling kernel function\n");
2939                         return -ENOTSUPP;
2940                 }
2941
2942                 if (!bpf_jit_supports_kfunc_call()) {
2943                         verbose(env, "JIT does not support calling kernel function\n");
2944                         return -ENOTSUPP;
2945                 }
2946
2947                 if (!env->prog->gpl_compatible) {
2948                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2949                         return -EINVAL;
2950                 }
2951
2952                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2953                 if (!tab)
2954                         return -ENOMEM;
2955                 prog_aux->kfunc_tab = tab;
2956         }
2957
2958         /* func_id == 0 is always invalid, but instead of returning an error, be
2959          * conservative and wait until the code elimination pass before returning
2960          * error, so that invalid calls that get pruned out can be in BPF programs
2961          * loaded from userspace.  It is also required that offset be untouched
2962          * for such calls.
2963          */
2964         if (!func_id && !offset)
2965                 return 0;
2966
2967         if (!btf_tab && offset) {
2968                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2969                 if (!btf_tab)
2970                         return -ENOMEM;
2971                 prog_aux->kfunc_btf_tab = btf_tab;
2972         }
2973
2974         desc_btf = find_kfunc_desc_btf(env, offset);
2975         if (IS_ERR(desc_btf)) {
2976                 verbose(env, "failed to find BTF for kernel function\n");
2977                 return PTR_ERR(desc_btf);
2978         }
2979
2980         if (find_kfunc_desc(env->prog, func_id, offset))
2981                 return 0;
2982
2983         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2984                 verbose(env, "too many different kernel function calls\n");
2985                 return -E2BIG;
2986         }
2987
2988         func = btf_type_by_id(desc_btf, func_id);
2989         if (!func || !btf_type_is_func(func)) {
2990                 verbose(env, "kernel btf_id %u is not a function\n",
2991                         func_id);
2992                 return -EINVAL;
2993         }
2994         func_proto = btf_type_by_id(desc_btf, func->type);
2995         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2996                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2997                         func_id);
2998                 return -EINVAL;
2999         }
3000
3001         func_name = btf_name_by_offset(desc_btf, func->name_off);
3002         addr = kallsyms_lookup_name(func_name);
3003         if (!addr) {
3004                 verbose(env, "cannot find address for kernel function %s\n",
3005                         func_name);
3006                 return -EINVAL;
3007         }
3008         specialize_kfunc(env, func_id, offset, &addr);
3009
3010         if (bpf_jit_supports_far_kfunc_call()) {
3011                 call_imm = func_id;
3012         } else {
3013                 call_imm = BPF_CALL_IMM(addr);
3014                 /* Check whether the relative offset overflows desc->imm */
3015                 if ((unsigned long)(s32)call_imm != call_imm) {
3016                         verbose(env, "address of kernel function %s is out of range\n",
3017                                 func_name);
3018                         return -EINVAL;
3019                 }
3020         }
3021
3022         if (bpf_dev_bound_kfunc_id(func_id)) {
3023                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
3024                 if (err)
3025                         return err;
3026         }
3027
3028         desc = &tab->descs[tab->nr_descs++];
3029         desc->func_id = func_id;
3030         desc->imm = call_imm;
3031         desc->offset = offset;
3032         desc->addr = addr;
3033         err = btf_distill_func_proto(&env->log, desc_btf,
3034                                      func_proto, func_name,
3035                                      &desc->func_model);
3036         if (!err)
3037                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3038                      kfunc_desc_cmp_by_id_off, NULL);
3039         return err;
3040 }
3041
3042 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
3043 {
3044         const struct bpf_kfunc_desc *d0 = a;
3045         const struct bpf_kfunc_desc *d1 = b;
3046
3047         if (d0->imm != d1->imm)
3048                 return d0->imm < d1->imm ? -1 : 1;
3049         if (d0->offset != d1->offset)
3050                 return d0->offset < d1->offset ? -1 : 1;
3051         return 0;
3052 }
3053
3054 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
3055 {
3056         struct bpf_kfunc_desc_tab *tab;
3057
3058         tab = prog->aux->kfunc_tab;
3059         if (!tab)
3060                 return;
3061
3062         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
3063              kfunc_desc_cmp_by_imm_off, NULL);
3064 }
3065
3066 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
3067 {
3068         return !!prog->aux->kfunc_tab;
3069 }
3070
3071 const struct btf_func_model *
3072 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3073                          const struct bpf_insn *insn)
3074 {
3075         const struct bpf_kfunc_desc desc = {
3076                 .imm = insn->imm,
3077                 .offset = insn->off,
3078         };
3079         const struct bpf_kfunc_desc *res;
3080         struct bpf_kfunc_desc_tab *tab;
3081
3082         tab = prog->aux->kfunc_tab;
3083         res = bsearch(&desc, tab->descs, tab->nr_descs,
3084                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
3085
3086         return res ? &res->func_model : NULL;
3087 }
3088
3089 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
3090 {
3091         struct bpf_subprog_info *subprog = env->subprog_info;
3092         int i, ret, insn_cnt = env->prog->len, ex_cb_insn;
3093         struct bpf_insn *insn = env->prog->insnsi;
3094
3095         /* Add entry function. */
3096         ret = add_subprog(env, 0);
3097         if (ret)
3098                 return ret;
3099
3100         for (i = 0; i < insn_cnt; i++, insn++) {
3101                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
3102                     !bpf_pseudo_kfunc_call(insn))
3103                         continue;
3104
3105                 if (!env->bpf_capable) {
3106                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
3107                         return -EPERM;
3108                 }
3109
3110                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
3111                         ret = add_subprog(env, i + insn->imm + 1);
3112                 else
3113                         ret = add_kfunc_call(env, insn->imm, insn->off);
3114
3115                 if (ret < 0)
3116                         return ret;
3117         }
3118
3119         ret = bpf_find_exception_callback_insn_off(env);
3120         if (ret < 0)
3121                 return ret;
3122         ex_cb_insn = ret;
3123
3124         /* If ex_cb_insn > 0, this means that the main program has a subprog
3125          * marked using BTF decl tag to serve as the exception callback.
3126          */
3127         if (ex_cb_insn) {
3128                 ret = add_subprog(env, ex_cb_insn);
3129                 if (ret < 0)
3130                         return ret;
3131                 for (i = 1; i < env->subprog_cnt; i++) {
3132                         if (env->subprog_info[i].start != ex_cb_insn)
3133                                 continue;
3134                         env->exception_callback_subprog = i;
3135                         break;
3136                 }
3137         }
3138
3139         /* Add a fake 'exit' subprog which could simplify subprog iteration
3140          * logic. 'subprog_cnt' should not be increased.
3141          */
3142         subprog[env->subprog_cnt].start = insn_cnt;
3143
3144         if (env->log.level & BPF_LOG_LEVEL2)
3145                 for (i = 0; i < env->subprog_cnt; i++)
3146                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
3147
3148         return 0;
3149 }
3150
3151 static int check_subprogs(struct bpf_verifier_env *env)
3152 {
3153         int i, subprog_start, subprog_end, off, cur_subprog = 0;
3154         struct bpf_subprog_info *subprog = env->subprog_info;
3155         struct bpf_insn *insn = env->prog->insnsi;
3156         int insn_cnt = env->prog->len;
3157
3158         /* now check that all jumps are within the same subprog */
3159         subprog_start = subprog[cur_subprog].start;
3160         subprog_end = subprog[cur_subprog + 1].start;
3161         for (i = 0; i < insn_cnt; i++) {
3162                 u8 code = insn[i].code;
3163
3164                 if (code == (BPF_JMP | BPF_CALL) &&
3165                     insn[i].src_reg == 0 &&
3166                     insn[i].imm == BPF_FUNC_tail_call)
3167                         subprog[cur_subprog].has_tail_call = true;
3168                 if (BPF_CLASS(code) == BPF_LD &&
3169                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
3170                         subprog[cur_subprog].has_ld_abs = true;
3171                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
3172                         goto next;
3173                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
3174                         goto next;
3175                 if (code == (BPF_JMP32 | BPF_JA))
3176                         off = i + insn[i].imm + 1;
3177                 else
3178                         off = i + insn[i].off + 1;
3179                 if (off < subprog_start || off >= subprog_end) {
3180                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
3181                         return -EINVAL;
3182                 }
3183 next:
3184                 if (i == subprog_end - 1) {
3185                         /* to avoid fall-through from one subprog into another
3186                          * the last insn of the subprog should be either exit
3187                          * or unconditional jump back or bpf_throw call
3188                          */
3189                         if (code != (BPF_JMP | BPF_EXIT) &&
3190                             code != (BPF_JMP32 | BPF_JA) &&
3191                             code != (BPF_JMP | BPF_JA)) {
3192                                 verbose(env, "last insn is not an exit or jmp\n");
3193                                 return -EINVAL;
3194                         }
3195                         subprog_start = subprog_end;
3196                         cur_subprog++;
3197                         if (cur_subprog < env->subprog_cnt)
3198                                 subprog_end = subprog[cur_subprog + 1].start;
3199                 }
3200         }
3201         return 0;
3202 }
3203
3204 /* Parentage chain of this register (or stack slot) should take care of all
3205  * issues like callee-saved registers, stack slot allocation time, etc.
3206  */
3207 static int mark_reg_read(struct bpf_verifier_env *env,
3208                          const struct bpf_reg_state *state,
3209                          struct bpf_reg_state *parent, u8 flag)
3210 {
3211         bool writes = parent == state->parent; /* Observe write marks */
3212         int cnt = 0;
3213
3214         while (parent) {
3215                 /* if read wasn't screened by an earlier write ... */
3216                 if (writes && state->live & REG_LIVE_WRITTEN)
3217                         break;
3218                 if (parent->live & REG_LIVE_DONE) {
3219                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
3220                                 reg_type_str(env, parent->type),
3221                                 parent->var_off.value, parent->off);
3222                         return -EFAULT;
3223                 }
3224                 /* The first condition is more likely to be true than the
3225                  * second, checked it first.
3226                  */
3227                 if ((parent->live & REG_LIVE_READ) == flag ||
3228                     parent->live & REG_LIVE_READ64)
3229                         /* The parentage chain never changes and
3230                          * this parent was already marked as LIVE_READ.
3231                          * There is no need to keep walking the chain again and
3232                          * keep re-marking all parents as LIVE_READ.
3233                          * This case happens when the same register is read
3234                          * multiple times without writes into it in-between.
3235                          * Also, if parent has the stronger REG_LIVE_READ64 set,
3236                          * then no need to set the weak REG_LIVE_READ32.
3237                          */
3238                         break;
3239                 /* ... then we depend on parent's value */
3240                 parent->live |= flag;
3241                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
3242                 if (flag == REG_LIVE_READ64)
3243                         parent->live &= ~REG_LIVE_READ32;
3244                 state = parent;
3245                 parent = state->parent;
3246                 writes = true;
3247                 cnt++;
3248         }
3249
3250         if (env->longest_mark_read_walk < cnt)
3251                 env->longest_mark_read_walk = cnt;
3252         return 0;
3253 }
3254
3255 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
3256 {
3257         struct bpf_func_state *state = func(env, reg);
3258         int spi, ret;
3259
3260         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
3261          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
3262          * check_kfunc_call.
3263          */
3264         if (reg->type == CONST_PTR_TO_DYNPTR)
3265                 return 0;
3266         spi = dynptr_get_spi(env, reg);
3267         if (spi < 0)
3268                 return spi;
3269         /* Caller ensures dynptr is valid and initialized, which means spi is in
3270          * bounds and spi is the first dynptr slot. Simply mark stack slot as
3271          * read.
3272          */
3273         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
3274                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
3275         if (ret)
3276                 return ret;
3277         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
3278                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
3279 }
3280
3281 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
3282                           int spi, int nr_slots)
3283 {
3284         struct bpf_func_state *state = func(env, reg);
3285         int err, i;
3286
3287         for (i = 0; i < nr_slots; i++) {
3288                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
3289
3290                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
3291                 if (err)
3292                         return err;
3293
3294                 mark_stack_slot_scratched(env, spi - i);
3295         }
3296
3297         return 0;
3298 }
3299
3300 /* This function is supposed to be used by the following 32-bit optimization
3301  * code only. It returns TRUE if the source or destination register operates
3302  * on 64-bit, otherwise return FALSE.
3303  */
3304 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
3305                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
3306 {
3307         u8 code, class, op;
3308
3309         code = insn->code;
3310         class = BPF_CLASS(code);
3311         op = BPF_OP(code);
3312         if (class == BPF_JMP) {
3313                 /* BPF_EXIT for "main" will reach here. Return TRUE
3314                  * conservatively.
3315                  */
3316                 if (op == BPF_EXIT)
3317                         return true;
3318                 if (op == BPF_CALL) {
3319                         /* BPF to BPF call will reach here because of marking
3320                          * caller saved clobber with DST_OP_NO_MARK for which we
3321                          * don't care the register def because they are anyway
3322                          * marked as NOT_INIT already.
3323                          */
3324                         if (insn->src_reg == BPF_PSEUDO_CALL)
3325                                 return false;
3326                         /* Helper call will reach here because of arg type
3327                          * check, conservatively return TRUE.
3328                          */
3329                         if (t == SRC_OP)
3330                                 return true;
3331
3332                         return false;
3333                 }
3334         }
3335
3336         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3337                 return false;
3338
3339         if (class == BPF_ALU64 || class == BPF_JMP ||
3340             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3341                 return true;
3342
3343         if (class == BPF_ALU || class == BPF_JMP32)
3344                 return false;
3345
3346         if (class == BPF_LDX) {
3347                 if (t != SRC_OP)
3348                         return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX;
3349                 /* LDX source must be ptr. */
3350                 return true;
3351         }
3352
3353         if (class == BPF_STX) {
3354                 /* BPF_STX (including atomic variants) has multiple source
3355                  * operands, one of which is a ptr. Check whether the caller is
3356                  * asking about it.
3357                  */
3358                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3359                         return true;
3360                 return BPF_SIZE(code) == BPF_DW;
3361         }
3362
3363         if (class == BPF_LD) {
3364                 u8 mode = BPF_MODE(code);
3365
3366                 /* LD_IMM64 */
3367                 if (mode == BPF_IMM)
3368                         return true;
3369
3370                 /* Both LD_IND and LD_ABS return 32-bit data. */
3371                 if (t != SRC_OP)
3372                         return  false;
3373
3374                 /* Implicit ctx ptr. */
3375                 if (regno == BPF_REG_6)
3376                         return true;
3377
3378                 /* Explicit source could be any width. */
3379                 return true;
3380         }
3381
3382         if (class == BPF_ST)
3383                 /* The only source register for BPF_ST is a ptr. */
3384                 return true;
3385
3386         /* Conservatively return true at default. */
3387         return true;
3388 }
3389
3390 /* Return the regno defined by the insn, or -1. */
3391 static int insn_def_regno(const struct bpf_insn *insn)
3392 {
3393         switch (BPF_CLASS(insn->code)) {
3394         case BPF_JMP:
3395         case BPF_JMP32:
3396         case BPF_ST:
3397                 return -1;
3398         case BPF_STX:
3399                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3400                     (insn->imm & BPF_FETCH)) {
3401                         if (insn->imm == BPF_CMPXCHG)
3402                                 return BPF_REG_0;
3403                         else
3404                                 return insn->src_reg;
3405                 } else {
3406                         return -1;
3407                 }
3408         default:
3409                 return insn->dst_reg;
3410         }
3411 }
3412
3413 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3414 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3415 {
3416         int dst_reg = insn_def_regno(insn);
3417
3418         if (dst_reg == -1)
3419                 return false;
3420
3421         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3422 }
3423
3424 static void mark_insn_zext(struct bpf_verifier_env *env,
3425                            struct bpf_reg_state *reg)
3426 {
3427         s32 def_idx = reg->subreg_def;
3428
3429         if (def_idx == DEF_NOT_SUBREG)
3430                 return;
3431
3432         env->insn_aux_data[def_idx - 1].zext_dst = true;
3433         /* The dst will be zero extended, so won't be sub-register anymore. */
3434         reg->subreg_def = DEF_NOT_SUBREG;
3435 }
3436
3437 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3438                          enum reg_arg_type t)
3439 {
3440         struct bpf_verifier_state *vstate = env->cur_state;
3441         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3442         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3443         struct bpf_reg_state *reg, *regs = state->regs;
3444         bool rw64;
3445
3446         if (regno >= MAX_BPF_REG) {
3447                 verbose(env, "R%d is invalid\n", regno);
3448                 return -EINVAL;
3449         }
3450
3451         mark_reg_scratched(env, regno);
3452
3453         reg = &regs[regno];
3454         rw64 = is_reg64(env, insn, regno, reg, t);
3455         if (t == SRC_OP) {
3456                 /* check whether register used as source operand can be read */
3457                 if (reg->type == NOT_INIT) {
3458                         verbose(env, "R%d !read_ok\n", regno);
3459                         return -EACCES;
3460                 }
3461                 /* We don't need to worry about FP liveness because it's read-only */
3462                 if (regno == BPF_REG_FP)
3463                         return 0;
3464
3465                 if (rw64)
3466                         mark_insn_zext(env, reg);
3467
3468                 return mark_reg_read(env, reg, reg->parent,
3469                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3470         } else {
3471                 /* check whether register used as dest operand can be written to */
3472                 if (regno == BPF_REG_FP) {
3473                         verbose(env, "frame pointer is read only\n");
3474                         return -EACCES;
3475                 }
3476                 reg->live |= REG_LIVE_WRITTEN;
3477                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3478                 if (t == DST_OP)
3479                         mark_reg_unknown(env, regs, regno);
3480         }
3481         return 0;
3482 }
3483
3484 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3485 {
3486         env->insn_aux_data[idx].jmp_point = true;
3487 }
3488
3489 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3490 {
3491         return env->insn_aux_data[insn_idx].jmp_point;
3492 }
3493
3494 /* for any branch, call, exit record the history of jmps in the given state */
3495 static int push_jmp_history(struct bpf_verifier_env *env,
3496                             struct bpf_verifier_state *cur)
3497 {
3498         u32 cnt = cur->jmp_history_cnt;
3499         struct bpf_idx_pair *p;
3500         size_t alloc_size;
3501
3502         if (!is_jmp_point(env, env->insn_idx))
3503                 return 0;
3504
3505         cnt++;
3506         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3507         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3508         if (!p)
3509                 return -ENOMEM;
3510         p[cnt - 1].idx = env->insn_idx;
3511         p[cnt - 1].prev_idx = env->prev_insn_idx;
3512         cur->jmp_history = p;
3513         cur->jmp_history_cnt = cnt;
3514         return 0;
3515 }
3516
3517 /* Backtrack one insn at a time. If idx is not at the top of recorded
3518  * history then previous instruction came from straight line execution.
3519  */
3520 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3521                              u32 *history)
3522 {
3523         u32 cnt = *history;
3524
3525         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3526                 i = st->jmp_history[cnt - 1].prev_idx;
3527                 (*history)--;
3528         } else {
3529                 i--;
3530         }
3531         return i;
3532 }
3533
3534 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3535 {
3536         const struct btf_type *func;
3537         struct btf *desc_btf;
3538
3539         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3540                 return NULL;
3541
3542         desc_btf = find_kfunc_desc_btf(data, insn->off);
3543         if (IS_ERR(desc_btf))
3544                 return "<error>";
3545
3546         func = btf_type_by_id(desc_btf, insn->imm);
3547         return btf_name_by_offset(desc_btf, func->name_off);
3548 }
3549
3550 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3551 {
3552         bt->frame = frame;
3553 }
3554
3555 static inline void bt_reset(struct backtrack_state *bt)
3556 {
3557         struct bpf_verifier_env *env = bt->env;
3558
3559         memset(bt, 0, sizeof(*bt));
3560         bt->env = env;
3561 }
3562
3563 static inline u32 bt_empty(struct backtrack_state *bt)
3564 {
3565         u64 mask = 0;
3566         int i;
3567
3568         for (i = 0; i <= bt->frame; i++)
3569                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3570
3571         return mask == 0;
3572 }
3573
3574 static inline int bt_subprog_enter(struct backtrack_state *bt)
3575 {
3576         if (bt->frame == MAX_CALL_FRAMES - 1) {
3577                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3578                 WARN_ONCE(1, "verifier backtracking bug");
3579                 return -EFAULT;
3580         }
3581         bt->frame++;
3582         return 0;
3583 }
3584
3585 static inline int bt_subprog_exit(struct backtrack_state *bt)
3586 {
3587         if (bt->frame == 0) {
3588                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3589                 WARN_ONCE(1, "verifier backtracking bug");
3590                 return -EFAULT;
3591         }
3592         bt->frame--;
3593         return 0;
3594 }
3595
3596 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3597 {
3598         bt->reg_masks[frame] |= 1 << reg;
3599 }
3600
3601 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3602 {
3603         bt->reg_masks[frame] &= ~(1 << reg);
3604 }
3605
3606 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3607 {
3608         bt_set_frame_reg(bt, bt->frame, reg);
3609 }
3610
3611 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3612 {
3613         bt_clear_frame_reg(bt, bt->frame, reg);
3614 }
3615
3616 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3617 {
3618         bt->stack_masks[frame] |= 1ull << slot;
3619 }
3620
3621 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3622 {
3623         bt->stack_masks[frame] &= ~(1ull << slot);
3624 }
3625
3626 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3627 {
3628         bt_set_frame_slot(bt, bt->frame, slot);
3629 }
3630
3631 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3632 {
3633         bt_clear_frame_slot(bt, bt->frame, slot);
3634 }
3635
3636 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3637 {
3638         return bt->reg_masks[frame];
3639 }
3640
3641 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3642 {
3643         return bt->reg_masks[bt->frame];
3644 }
3645
3646 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3647 {
3648         return bt->stack_masks[frame];
3649 }
3650
3651 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3652 {
3653         return bt->stack_masks[bt->frame];
3654 }
3655
3656 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3657 {
3658         return bt->reg_masks[bt->frame] & (1 << reg);
3659 }
3660
3661 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3662 {
3663         return bt->stack_masks[bt->frame] & (1ull << slot);
3664 }
3665
3666 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3667 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3668 {
3669         DECLARE_BITMAP(mask, 64);
3670         bool first = true;
3671         int i, n;
3672
3673         buf[0] = '\0';
3674
3675         bitmap_from_u64(mask, reg_mask);
3676         for_each_set_bit(i, mask, 32) {
3677                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3678                 first = false;
3679                 buf += n;
3680                 buf_sz -= n;
3681                 if (buf_sz < 0)
3682                         break;
3683         }
3684 }
3685 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3686 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3687 {
3688         DECLARE_BITMAP(mask, 64);
3689         bool first = true;
3690         int i, n;
3691
3692         buf[0] = '\0';
3693
3694         bitmap_from_u64(mask, stack_mask);
3695         for_each_set_bit(i, mask, 64) {
3696                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3697                 first = false;
3698                 buf += n;
3699                 buf_sz -= n;
3700                 if (buf_sz < 0)
3701                         break;
3702         }
3703 }
3704
3705 /* For given verifier state backtrack_insn() is called from the last insn to
3706  * the first insn. Its purpose is to compute a bitmask of registers and
3707  * stack slots that needs precision in the parent verifier state.
3708  *
3709  * @idx is an index of the instruction we are currently processing;
3710  * @subseq_idx is an index of the subsequent instruction that:
3711  *   - *would be* executed next, if jump history is viewed in forward order;
3712  *   - *was* processed previously during backtracking.
3713  */
3714 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3715                           struct backtrack_state *bt)
3716 {
3717         const struct bpf_insn_cbs cbs = {
3718                 .cb_call        = disasm_kfunc_name,
3719                 .cb_print       = verbose,
3720                 .private_data   = env,
3721         };
3722         struct bpf_insn *insn = env->prog->insnsi + idx;
3723         u8 class = BPF_CLASS(insn->code);
3724         u8 opcode = BPF_OP(insn->code);
3725         u8 mode = BPF_MODE(insn->code);
3726         u32 dreg = insn->dst_reg;
3727         u32 sreg = insn->src_reg;
3728         u32 spi, i;
3729
3730         if (insn->code == 0)
3731                 return 0;
3732         if (env->log.level & BPF_LOG_LEVEL2) {
3733                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3734                 verbose(env, "mark_precise: frame%d: regs=%s ",
3735                         bt->frame, env->tmp_str_buf);
3736                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3737                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3738                 verbose(env, "%d: ", idx);
3739                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3740         }
3741
3742         if (class == BPF_ALU || class == BPF_ALU64) {
3743                 if (!bt_is_reg_set(bt, dreg))
3744                         return 0;
3745                 if (opcode == BPF_MOV) {
3746                         if (BPF_SRC(insn->code) == BPF_X) {
3747                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3748                                  * dreg needs precision after this insn
3749                                  * sreg needs precision before this insn
3750                                  */
3751                                 bt_clear_reg(bt, dreg);
3752                                 bt_set_reg(bt, sreg);
3753                         } else {
3754                                 /* dreg = K
3755                                  * dreg needs precision after this insn.
3756                                  * Corresponding register is already marked
3757                                  * as precise=true in this verifier state.
3758                                  * No further markings in parent are necessary
3759                                  */
3760                                 bt_clear_reg(bt, dreg);
3761                         }
3762                 } else {
3763                         if (BPF_SRC(insn->code) == BPF_X) {
3764                                 /* dreg += sreg
3765                                  * both dreg and sreg need precision
3766                                  * before this insn
3767                                  */
3768                                 bt_set_reg(bt, sreg);
3769                         } /* else dreg += K
3770                            * dreg still needs precision before this insn
3771                            */
3772                 }
3773         } else if (class == BPF_LDX) {
3774                 if (!bt_is_reg_set(bt, dreg))
3775                         return 0;
3776                 bt_clear_reg(bt, dreg);
3777
3778                 /* scalars can only be spilled into stack w/o losing precision.
3779                  * Load from any other memory can be zero extended.
3780                  * The desire to keep that precision is already indicated
3781                  * by 'precise' mark in corresponding register of this state.
3782                  * No further tracking necessary.
3783                  */
3784                 if (insn->src_reg != BPF_REG_FP)
3785                         return 0;
3786
3787                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3788                  * that [fp - off] slot contains scalar that needs to be
3789                  * tracked with precision
3790                  */
3791                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3792                 if (spi >= 64) {
3793                         verbose(env, "BUG spi %d\n", spi);
3794                         WARN_ONCE(1, "verifier backtracking bug");
3795                         return -EFAULT;
3796                 }
3797                 bt_set_slot(bt, spi);
3798         } else if (class == BPF_STX || class == BPF_ST) {
3799                 if (bt_is_reg_set(bt, dreg))
3800                         /* stx & st shouldn't be using _scalar_ dst_reg
3801                          * to access memory. It means backtracking
3802                          * encountered a case of pointer subtraction.
3803                          */
3804                         return -ENOTSUPP;
3805                 /* scalars can only be spilled into stack */
3806                 if (insn->dst_reg != BPF_REG_FP)
3807                         return 0;
3808                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3809                 if (spi >= 64) {
3810                         verbose(env, "BUG spi %d\n", spi);
3811                         WARN_ONCE(1, "verifier backtracking bug");
3812                         return -EFAULT;
3813                 }
3814                 if (!bt_is_slot_set(bt, spi))
3815                         return 0;
3816                 bt_clear_slot(bt, spi);
3817                 if (class == BPF_STX)
3818                         bt_set_reg(bt, sreg);
3819         } else if (class == BPF_JMP || class == BPF_JMP32) {
3820                 if (bpf_pseudo_call(insn)) {
3821                         int subprog_insn_idx, subprog;
3822
3823                         subprog_insn_idx = idx + insn->imm + 1;
3824                         subprog = find_subprog(env, subprog_insn_idx);
3825                         if (subprog < 0)
3826                                 return -EFAULT;
3827
3828                         if (subprog_is_global(env, subprog)) {
3829                                 /* check that jump history doesn't have any
3830                                  * extra instructions from subprog; the next
3831                                  * instruction after call to global subprog
3832                                  * should be literally next instruction in
3833                                  * caller program
3834                                  */
3835                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3836                                 /* r1-r5 are invalidated after subprog call,
3837                                  * so for global func call it shouldn't be set
3838                                  * anymore
3839                                  */
3840                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3841                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3842                                         WARN_ONCE(1, "verifier backtracking bug");
3843                                         return -EFAULT;
3844                                 }
3845                                 /* global subprog always sets R0 */
3846                                 bt_clear_reg(bt, BPF_REG_0);
3847                                 return 0;
3848                         } else {
3849                                 /* static subprog call instruction, which
3850                                  * means that we are exiting current subprog,
3851                                  * so only r1-r5 could be still requested as
3852                                  * precise, r0 and r6-r10 or any stack slot in
3853                                  * the current frame should be zero by now
3854                                  */
3855                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3856                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3857                                         WARN_ONCE(1, "verifier backtracking bug");
3858                                         return -EFAULT;
3859                                 }
3860                                 /* we don't track register spills perfectly,
3861                                  * so fallback to force-precise instead of failing */
3862                                 if (bt_stack_mask(bt) != 0)
3863                                         return -ENOTSUPP;
3864                                 /* propagate r1-r5 to the caller */
3865                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3866                                         if (bt_is_reg_set(bt, i)) {
3867                                                 bt_clear_reg(bt, i);
3868                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3869                                         }
3870                                 }
3871                                 if (bt_subprog_exit(bt))
3872                                         return -EFAULT;
3873                                 return 0;
3874                         }
3875                 } else if ((bpf_helper_call(insn) &&
3876                             is_callback_calling_function(insn->imm) &&
3877                             !is_async_callback_calling_function(insn->imm)) ||
3878                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3879                         /* callback-calling helper or kfunc call, which means
3880                          * we are exiting from subprog, but unlike the subprog
3881                          * call handling above, we shouldn't propagate
3882                          * precision of r1-r5 (if any requested), as they are
3883                          * not actually arguments passed directly to callback
3884                          * subprogs
3885                          */
3886                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3887                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3888                                 WARN_ONCE(1, "verifier backtracking bug");
3889                                 return -EFAULT;
3890                         }
3891                         if (bt_stack_mask(bt) != 0)
3892                                 return -ENOTSUPP;
3893                         /* clear r1-r5 in callback subprog's mask */
3894                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3895                                 bt_clear_reg(bt, i);
3896                         if (bt_subprog_exit(bt))
3897                                 return -EFAULT;
3898                         return 0;
3899                 } else if (opcode == BPF_CALL) {
3900                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3901                          * catch this error later. Make backtracking conservative
3902                          * with ENOTSUPP.
3903                          */
3904                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3905                                 return -ENOTSUPP;
3906                         /* regular helper call sets R0 */
3907                         bt_clear_reg(bt, BPF_REG_0);
3908                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3909                                 /* if backtracing was looking for registers R1-R5
3910                                  * they should have been found already.
3911                                  */
3912                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3913                                 WARN_ONCE(1, "verifier backtracking bug");
3914                                 return -EFAULT;
3915                         }
3916                 } else if (opcode == BPF_EXIT) {
3917                         bool r0_precise;
3918
3919                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3920                                 /* if backtracing was looking for registers R1-R5
3921                                  * they should have been found already.
3922                                  */
3923                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3924                                 WARN_ONCE(1, "verifier backtracking bug");
3925                                 return -EFAULT;
3926                         }
3927
3928                         /* BPF_EXIT in subprog or callback always returns
3929                          * right after the call instruction, so by checking
3930                          * whether the instruction at subseq_idx-1 is subprog
3931                          * call or not we can distinguish actual exit from
3932                          * *subprog* from exit from *callback*. In the former
3933                          * case, we need to propagate r0 precision, if
3934                          * necessary. In the former we never do that.
3935                          */
3936                         r0_precise = subseq_idx - 1 >= 0 &&
3937                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3938                                      bt_is_reg_set(bt, BPF_REG_0);
3939
3940                         bt_clear_reg(bt, BPF_REG_0);
3941                         if (bt_subprog_enter(bt))
3942                                 return -EFAULT;
3943
3944                         if (r0_precise)
3945                                 bt_set_reg(bt, BPF_REG_0);
3946                         /* r6-r9 and stack slots will stay set in caller frame
3947                          * bitmasks until we return back from callee(s)
3948                          */
3949                         return 0;
3950                 } else if (BPF_SRC(insn->code) == BPF_X) {
3951                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3952                                 return 0;
3953                         /* dreg <cond> sreg
3954                          * Both dreg and sreg need precision before
3955                          * this insn. If only sreg was marked precise
3956                          * before it would be equally necessary to
3957                          * propagate it to dreg.
3958                          */
3959                         bt_set_reg(bt, dreg);
3960                         bt_set_reg(bt, sreg);
3961                          /* else dreg <cond> K
3962                           * Only dreg still needs precision before
3963                           * this insn, so for the K-based conditional
3964                           * there is nothing new to be marked.
3965                           */
3966                 }
3967         } else if (class == BPF_LD) {
3968                 if (!bt_is_reg_set(bt, dreg))
3969                         return 0;
3970                 bt_clear_reg(bt, dreg);
3971                 /* It's ld_imm64 or ld_abs or ld_ind.
3972                  * For ld_imm64 no further tracking of precision
3973                  * into parent is necessary
3974                  */
3975                 if (mode == BPF_IND || mode == BPF_ABS)
3976                         /* to be analyzed */
3977                         return -ENOTSUPP;
3978         }
3979         return 0;
3980 }
3981
3982 /* the scalar precision tracking algorithm:
3983  * . at the start all registers have precise=false.
3984  * . scalar ranges are tracked as normal through alu and jmp insns.
3985  * . once precise value of the scalar register is used in:
3986  *   .  ptr + scalar alu
3987  *   . if (scalar cond K|scalar)
3988  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3989  *   backtrack through the verifier states and mark all registers and
3990  *   stack slots with spilled constants that these scalar regisers
3991  *   should be precise.
3992  * . during state pruning two registers (or spilled stack slots)
3993  *   are equivalent if both are not precise.
3994  *
3995  * Note the verifier cannot simply walk register parentage chain,
3996  * since many different registers and stack slots could have been
3997  * used to compute single precise scalar.
3998  *
3999  * The approach of starting with precise=true for all registers and then
4000  * backtrack to mark a register as not precise when the verifier detects
4001  * that program doesn't care about specific value (e.g., when helper
4002  * takes register as ARG_ANYTHING parameter) is not safe.
4003  *
4004  * It's ok to walk single parentage chain of the verifier states.
4005  * It's possible that this backtracking will go all the way till 1st insn.
4006  * All other branches will be explored for needing precision later.
4007  *
4008  * The backtracking needs to deal with cases like:
4009  *   R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0)
4010  * r9 -= r8
4011  * r5 = r9
4012  * if r5 > 0x79f goto pc+7
4013  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
4014  * r5 += 1
4015  * ...
4016  * call bpf_perf_event_output#25
4017  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
4018  *
4019  * and this case:
4020  * r6 = 1
4021  * call foo // uses callee's r6 inside to compute r0
4022  * r0 += r6
4023  * if r0 == 0 goto
4024  *
4025  * to track above reg_mask/stack_mask needs to be independent for each frame.
4026  *
4027  * Also if parent's curframe > frame where backtracking started,
4028  * the verifier need to mark registers in both frames, otherwise callees
4029  * may incorrectly prune callers. This is similar to
4030  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
4031  *
4032  * For now backtracking falls back into conservative marking.
4033  */
4034 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
4035                                      struct bpf_verifier_state *st)
4036 {
4037         struct bpf_func_state *func;
4038         struct bpf_reg_state *reg;
4039         int i, j;
4040
4041         if (env->log.level & BPF_LOG_LEVEL2) {
4042                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
4043                         st->curframe);
4044         }
4045
4046         /* big hammer: mark all scalars precise in this path.
4047          * pop_stack may still get !precise scalars.
4048          * We also skip current state and go straight to first parent state,
4049          * because precision markings in current non-checkpointed state are
4050          * not needed. See why in the comment in __mark_chain_precision below.
4051          */
4052         for (st = st->parent; st; st = st->parent) {
4053                 for (i = 0; i <= st->curframe; i++) {
4054                         func = st->frame[i];
4055                         for (j = 0; j < BPF_REG_FP; j++) {
4056                                 reg = &func->regs[j];
4057                                 if (reg->type != SCALAR_VALUE || reg->precise)
4058                                         continue;
4059                                 reg->precise = true;
4060                                 if (env->log.level & BPF_LOG_LEVEL2) {
4061                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
4062                                                 i, j);
4063                                 }
4064                         }
4065                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4066                                 if (!is_spilled_reg(&func->stack[j]))
4067                                         continue;
4068                                 reg = &func->stack[j].spilled_ptr;
4069                                 if (reg->type != SCALAR_VALUE || reg->precise)
4070                                         continue;
4071                                 reg->precise = true;
4072                                 if (env->log.level & BPF_LOG_LEVEL2) {
4073                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
4074                                                 i, -(j + 1) * 8);
4075                                 }
4076                         }
4077                 }
4078         }
4079 }
4080
4081 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4082 {
4083         struct bpf_func_state *func;
4084         struct bpf_reg_state *reg;
4085         int i, j;
4086
4087         for (i = 0; i <= st->curframe; i++) {
4088                 func = st->frame[i];
4089                 for (j = 0; j < BPF_REG_FP; j++) {
4090                         reg = &func->regs[j];
4091                         if (reg->type != SCALAR_VALUE)
4092                                 continue;
4093                         reg->precise = false;
4094                 }
4095                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
4096                         if (!is_spilled_reg(&func->stack[j]))
4097                                 continue;
4098                         reg = &func->stack[j].spilled_ptr;
4099                         if (reg->type != SCALAR_VALUE)
4100                                 continue;
4101                         reg->precise = false;
4102                 }
4103         }
4104 }
4105
4106 static bool idset_contains(struct bpf_idset *s, u32 id)
4107 {
4108         u32 i;
4109
4110         for (i = 0; i < s->count; ++i)
4111                 if (s->ids[i] == id)
4112                         return true;
4113
4114         return false;
4115 }
4116
4117 static int idset_push(struct bpf_idset *s, u32 id)
4118 {
4119         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
4120                 return -EFAULT;
4121         s->ids[s->count++] = id;
4122         return 0;
4123 }
4124
4125 static void idset_reset(struct bpf_idset *s)
4126 {
4127         s->count = 0;
4128 }
4129
4130 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
4131  * Mark all registers with these IDs as precise.
4132  */
4133 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
4134 {
4135         struct bpf_idset *precise_ids = &env->idset_scratch;
4136         struct backtrack_state *bt = &env->bt;
4137         struct bpf_func_state *func;
4138         struct bpf_reg_state *reg;
4139         DECLARE_BITMAP(mask, 64);
4140         int i, fr;
4141
4142         idset_reset(precise_ids);
4143
4144         for (fr = bt->frame; fr >= 0; fr--) {
4145                 func = st->frame[fr];
4146
4147                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4148                 for_each_set_bit(i, mask, 32) {
4149                         reg = &func->regs[i];
4150                         if (!reg->id || reg->type != SCALAR_VALUE)
4151                                 continue;
4152                         if (idset_push(precise_ids, reg->id))
4153                                 return -EFAULT;
4154                 }
4155
4156                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4157                 for_each_set_bit(i, mask, 64) {
4158                         if (i >= func->allocated_stack / BPF_REG_SIZE)
4159                                 break;
4160                         if (!is_spilled_scalar_reg(&func->stack[i]))
4161                                 continue;
4162                         reg = &func->stack[i].spilled_ptr;
4163                         if (!reg->id)
4164                                 continue;
4165                         if (idset_push(precise_ids, reg->id))
4166                                 return -EFAULT;
4167                 }
4168         }
4169
4170         for (fr = 0; fr <= st->curframe; ++fr) {
4171                 func = st->frame[fr];
4172
4173                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
4174                         reg = &func->regs[i];
4175                         if (!reg->id)
4176                                 continue;
4177                         if (!idset_contains(precise_ids, reg->id))
4178                                 continue;
4179                         bt_set_frame_reg(bt, fr, i);
4180                 }
4181                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
4182                         if (!is_spilled_scalar_reg(&func->stack[i]))
4183                                 continue;
4184                         reg = &func->stack[i].spilled_ptr;
4185                         if (!reg->id)
4186                                 continue;
4187                         if (!idset_contains(precise_ids, reg->id))
4188                                 continue;
4189                         bt_set_frame_slot(bt, fr, i);
4190                 }
4191         }
4192
4193         return 0;
4194 }
4195
4196 /*
4197  * __mark_chain_precision() backtracks BPF program instruction sequence and
4198  * chain of verifier states making sure that register *regno* (if regno >= 0)
4199  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
4200  * SCALARS, as well as any other registers and slots that contribute to
4201  * a tracked state of given registers/stack slots, depending on specific BPF
4202  * assembly instructions (see backtrack_insns() for exact instruction handling
4203  * logic). This backtracking relies on recorded jmp_history and is able to
4204  * traverse entire chain of parent states. This process ends only when all the
4205  * necessary registers/slots and their transitive dependencies are marked as
4206  * precise.
4207  *
4208  * One important and subtle aspect is that precise marks *do not matter* in
4209  * the currently verified state (current state). It is important to understand
4210  * why this is the case.
4211  *
4212  * First, note that current state is the state that is not yet "checkpointed",
4213  * i.e., it is not yet put into env->explored_states, and it has no children
4214  * states as well. It's ephemeral, and can end up either a) being discarded if
4215  * compatible explored state is found at some point or BPF_EXIT instruction is
4216  * reached or b) checkpointed and put into env->explored_states, branching out
4217  * into one or more children states.
4218  *
4219  * In the former case, precise markings in current state are completely
4220  * ignored by state comparison code (see regsafe() for details). Only
4221  * checkpointed ("old") state precise markings are important, and if old
4222  * state's register/slot is precise, regsafe() assumes current state's
4223  * register/slot as precise and checks value ranges exactly and precisely. If
4224  * states turn out to be compatible, current state's necessary precise
4225  * markings and any required parent states' precise markings are enforced
4226  * after the fact with propagate_precision() logic, after the fact. But it's
4227  * important to realize that in this case, even after marking current state
4228  * registers/slots as precise, we immediately discard current state. So what
4229  * actually matters is any of the precise markings propagated into current
4230  * state's parent states, which are always checkpointed (due to b) case above).
4231  * As such, for scenario a) it doesn't matter if current state has precise
4232  * markings set or not.
4233  *
4234  * Now, for the scenario b), checkpointing and forking into child(ren)
4235  * state(s). Note that before current state gets to checkpointing step, any
4236  * processed instruction always assumes precise SCALAR register/slot
4237  * knowledge: if precise value or range is useful to prune jump branch, BPF
4238  * verifier takes this opportunity enthusiastically. Similarly, when
4239  * register's value is used to calculate offset or memory address, exact
4240  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
4241  * what we mentioned above about state comparison ignoring precise markings
4242  * during state comparison, BPF verifier ignores and also assumes precise
4243  * markings *at will* during instruction verification process. But as verifier
4244  * assumes precision, it also propagates any precision dependencies across
4245  * parent states, which are not yet finalized, so can be further restricted
4246  * based on new knowledge gained from restrictions enforced by their children
4247  * states. This is so that once those parent states are finalized, i.e., when
4248  * they have no more active children state, state comparison logic in
4249  * is_state_visited() would enforce strict and precise SCALAR ranges, if
4250  * required for correctness.
4251  *
4252  * To build a bit more intuition, note also that once a state is checkpointed,
4253  * the path we took to get to that state is not important. This is crucial
4254  * property for state pruning. When state is checkpointed and finalized at
4255  * some instruction index, it can be correctly and safely used to "short
4256  * circuit" any *compatible* state that reaches exactly the same instruction
4257  * index. I.e., if we jumped to that instruction from a completely different
4258  * code path than original finalized state was derived from, it doesn't
4259  * matter, current state can be discarded because from that instruction
4260  * forward having a compatible state will ensure we will safely reach the
4261  * exit. States describe preconditions for further exploration, but completely
4262  * forget the history of how we got here.
4263  *
4264  * This also means that even if we needed precise SCALAR range to get to
4265  * finalized state, but from that point forward *that same* SCALAR register is
4266  * never used in a precise context (i.e., it's precise value is not needed for
4267  * correctness), it's correct and safe to mark such register as "imprecise"
4268  * (i.e., precise marking set to false). This is what we rely on when we do
4269  * not set precise marking in current state. If no child state requires
4270  * precision for any given SCALAR register, it's safe to dictate that it can
4271  * be imprecise. If any child state does require this register to be precise,
4272  * we'll mark it precise later retroactively during precise markings
4273  * propagation from child state to parent states.
4274  *
4275  * Skipping precise marking setting in current state is a mild version of
4276  * relying on the above observation. But we can utilize this property even
4277  * more aggressively by proactively forgetting any precise marking in the
4278  * current state (which we inherited from the parent state), right before we
4279  * checkpoint it and branch off into new child state. This is done by
4280  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
4281  * finalized states which help in short circuiting more future states.
4282  */
4283 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
4284 {
4285         struct backtrack_state *bt = &env->bt;
4286         struct bpf_verifier_state *st = env->cur_state;
4287         int first_idx = st->first_insn_idx;
4288         int last_idx = env->insn_idx;
4289         int subseq_idx = -1;
4290         struct bpf_func_state *func;
4291         struct bpf_reg_state *reg;
4292         bool skip_first = true;
4293         int i, fr, err;
4294
4295         if (!env->bpf_capable)
4296                 return 0;
4297
4298         /* set frame number from which we are starting to backtrack */
4299         bt_init(bt, env->cur_state->curframe);
4300
4301         /* Do sanity checks against current state of register and/or stack
4302          * slot, but don't set precise flag in current state, as precision
4303          * tracking in the current state is unnecessary.
4304          */
4305         func = st->frame[bt->frame];
4306         if (regno >= 0) {
4307                 reg = &func->regs[regno];
4308                 if (reg->type != SCALAR_VALUE) {
4309                         WARN_ONCE(1, "backtracing misuse");
4310                         return -EFAULT;
4311                 }
4312                 bt_set_reg(bt, regno);
4313         }
4314
4315         if (bt_empty(bt))
4316                 return 0;
4317
4318         for (;;) {
4319                 DECLARE_BITMAP(mask, 64);
4320                 u32 history = st->jmp_history_cnt;
4321
4322                 if (env->log.level & BPF_LOG_LEVEL2) {
4323                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4324                                 bt->frame, last_idx, first_idx, subseq_idx);
4325                 }
4326
4327                 /* If some register with scalar ID is marked as precise,
4328                  * make sure that all registers sharing this ID are also precise.
4329                  * This is needed to estimate effect of find_equal_scalars().
4330                  * Do this at the last instruction of each state,
4331                  * bpf_reg_state::id fields are valid for these instructions.
4332                  *
4333                  * Allows to track precision in situation like below:
4334                  *
4335                  *     r2 = unknown value
4336                  *     ...
4337                  *   --- state #0 ---
4338                  *     ...
4339                  *     r1 = r2                 // r1 and r2 now share the same ID
4340                  *     ...
4341                  *   --- state #1 {r1.id = A, r2.id = A} ---
4342                  *     ...
4343                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4344                  *     ...
4345                  *   --- state #2 {r1.id = A, r2.id = A} ---
4346                  *     r3 = r10
4347                  *     r3 += r1                // need to mark both r1 and r2
4348                  */
4349                 if (mark_precise_scalar_ids(env, st))
4350                         return -EFAULT;
4351
4352                 if (last_idx < 0) {
4353                         /* we are at the entry into subprog, which
4354                          * is expected for global funcs, but only if
4355                          * requested precise registers are R1-R5
4356                          * (which are global func's input arguments)
4357                          */
4358                         if (st->curframe == 0 &&
4359                             st->frame[0]->subprogno > 0 &&
4360                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4361                             bt_stack_mask(bt) == 0 &&
4362                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4363                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4364                                 for_each_set_bit(i, mask, 32) {
4365                                         reg = &st->frame[0]->regs[i];
4366                                         bt_clear_reg(bt, i);
4367                                         if (reg->type == SCALAR_VALUE)
4368                                                 reg->precise = true;
4369                                 }
4370                                 return 0;
4371                         }
4372
4373                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4374                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4375                         WARN_ONCE(1, "verifier backtracking bug");
4376                         return -EFAULT;
4377                 }
4378
4379                 for (i = last_idx;;) {
4380                         if (skip_first) {
4381                                 err = 0;
4382                                 skip_first = false;
4383                         } else {
4384                                 err = backtrack_insn(env, i, subseq_idx, bt);
4385                         }
4386                         if (err == -ENOTSUPP) {
4387                                 mark_all_scalars_precise(env, env->cur_state);
4388                                 bt_reset(bt);
4389                                 return 0;
4390                         } else if (err) {
4391                                 return err;
4392                         }
4393                         if (bt_empty(bt))
4394                                 /* Found assignment(s) into tracked register in this state.
4395                                  * Since this state is already marked, just return.
4396                                  * Nothing to be tracked further in the parent state.
4397                                  */
4398                                 return 0;
4399                         if (i == first_idx)
4400                                 break;
4401                         subseq_idx = i;
4402                         i = get_prev_insn_idx(st, i, &history);
4403                         if (i >= env->prog->len) {
4404                                 /* This can happen if backtracking reached insn 0
4405                                  * and there are still reg_mask or stack_mask
4406                                  * to backtrack.
4407                                  * It means the backtracking missed the spot where
4408                                  * particular register was initialized with a constant.
4409                                  */
4410                                 verbose(env, "BUG backtracking idx %d\n", i);
4411                                 WARN_ONCE(1, "verifier backtracking bug");
4412                                 return -EFAULT;
4413                         }
4414                 }
4415                 st = st->parent;
4416                 if (!st)
4417                         break;
4418
4419                 for (fr = bt->frame; fr >= 0; fr--) {
4420                         func = st->frame[fr];
4421                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4422                         for_each_set_bit(i, mask, 32) {
4423                                 reg = &func->regs[i];
4424                                 if (reg->type != SCALAR_VALUE) {
4425                                         bt_clear_frame_reg(bt, fr, i);
4426                                         continue;
4427                                 }
4428                                 if (reg->precise)
4429                                         bt_clear_frame_reg(bt, fr, i);
4430                                 else
4431                                         reg->precise = true;
4432                         }
4433
4434                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4435                         for_each_set_bit(i, mask, 64) {
4436                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4437                                         /* the sequence of instructions:
4438                                          * 2: (bf) r3 = r10
4439                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4440                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4441                                          * doesn't contain jmps. It's backtracked
4442                                          * as a single block.
4443                                          * During backtracking insn 3 is not recognized as
4444                                          * stack access, so at the end of backtracking
4445                                          * stack slot fp-8 is still marked in stack_mask.
4446                                          * However the parent state may not have accessed
4447                                          * fp-8 and it's "unallocated" stack space.
4448                                          * In such case fallback to conservative.
4449                                          */
4450                                         mark_all_scalars_precise(env, env->cur_state);
4451                                         bt_reset(bt);
4452                                         return 0;
4453                                 }
4454
4455                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4456                                         bt_clear_frame_slot(bt, fr, i);
4457                                         continue;
4458                                 }
4459                                 reg = &func->stack[i].spilled_ptr;
4460                                 if (reg->precise)
4461                                         bt_clear_frame_slot(bt, fr, i);
4462                                 else
4463                                         reg->precise = true;
4464                         }
4465                         if (env->log.level & BPF_LOG_LEVEL2) {
4466                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4467                                              bt_frame_reg_mask(bt, fr));
4468                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4469                                         fr, env->tmp_str_buf);
4470                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4471                                                bt_frame_stack_mask(bt, fr));
4472                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4473                                 print_verifier_state(env, func, true);
4474                         }
4475                 }
4476
4477                 if (bt_empty(bt))
4478                         return 0;
4479
4480                 subseq_idx = first_idx;
4481                 last_idx = st->last_insn_idx;
4482                 first_idx = st->first_insn_idx;
4483         }
4484
4485         /* if we still have requested precise regs or slots, we missed
4486          * something (e.g., stack access through non-r10 register), so
4487          * fallback to marking all precise
4488          */
4489         if (!bt_empty(bt)) {
4490                 mark_all_scalars_precise(env, env->cur_state);
4491                 bt_reset(bt);
4492         }
4493
4494         return 0;
4495 }
4496
4497 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4498 {
4499         return __mark_chain_precision(env, regno);
4500 }
4501
4502 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4503  * desired reg and stack masks across all relevant frames
4504  */
4505 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4506 {
4507         return __mark_chain_precision(env, -1);
4508 }
4509
4510 static bool is_spillable_regtype(enum bpf_reg_type type)
4511 {
4512         switch (base_type(type)) {
4513         case PTR_TO_MAP_VALUE:
4514         case PTR_TO_STACK:
4515         case PTR_TO_CTX:
4516         case PTR_TO_PACKET:
4517         case PTR_TO_PACKET_META:
4518         case PTR_TO_PACKET_END:
4519         case PTR_TO_FLOW_KEYS:
4520         case CONST_PTR_TO_MAP:
4521         case PTR_TO_SOCKET:
4522         case PTR_TO_SOCK_COMMON:
4523         case PTR_TO_TCP_SOCK:
4524         case PTR_TO_XDP_SOCK:
4525         case PTR_TO_BTF_ID:
4526         case PTR_TO_BUF:
4527         case PTR_TO_MEM:
4528         case PTR_TO_FUNC:
4529         case PTR_TO_MAP_KEY:
4530                 return true;
4531         default:
4532                 return false;
4533         }
4534 }
4535
4536 /* Does this register contain a constant zero? */
4537 static bool register_is_null(struct bpf_reg_state *reg)
4538 {
4539         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4540 }
4541
4542 static bool register_is_const(struct bpf_reg_state *reg)
4543 {
4544         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4545 }
4546
4547 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4548 {
4549         return tnum_is_unknown(reg->var_off) &&
4550                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4551                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4552                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4553                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4554 }
4555
4556 static bool register_is_bounded(struct bpf_reg_state *reg)
4557 {
4558         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4559 }
4560
4561 static bool __is_pointer_value(bool allow_ptr_leaks,
4562                                const struct bpf_reg_state *reg)
4563 {
4564         if (allow_ptr_leaks)
4565                 return false;
4566
4567         return reg->type != SCALAR_VALUE;
4568 }
4569
4570 /* Copy src state preserving dst->parent and dst->live fields */
4571 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4572 {
4573         struct bpf_reg_state *parent = dst->parent;
4574         enum bpf_reg_liveness live = dst->live;
4575
4576         *dst = *src;
4577         dst->parent = parent;
4578         dst->live = live;
4579 }
4580
4581 static void save_register_state(struct bpf_func_state *state,
4582                                 int spi, struct bpf_reg_state *reg,
4583                                 int size)
4584 {
4585         int i;
4586
4587         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4588         if (size == BPF_REG_SIZE)
4589                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4590
4591         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4592                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4593
4594         /* size < 8 bytes spill */
4595         for (; i; i--)
4596                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4597 }
4598
4599 static bool is_bpf_st_mem(struct bpf_insn *insn)
4600 {
4601         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4602 }
4603
4604 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4605  * stack boundary and alignment are checked in check_mem_access()
4606  */
4607 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4608                                        /* stack frame we're writing to */
4609                                        struct bpf_func_state *state,
4610                                        int off, int size, int value_regno,
4611                                        int insn_idx)
4612 {
4613         struct bpf_func_state *cur; /* state of the current function */
4614         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4615         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4616         struct bpf_reg_state *reg = NULL;
4617         u32 dst_reg = insn->dst_reg;
4618
4619         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4620         if (err)
4621                 return err;
4622         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4623          * so it's aligned access and [off, off + size) are within stack limits
4624          */
4625         if (!env->allow_ptr_leaks &&
4626             state->stack[spi].slot_type[0] == STACK_SPILL &&
4627             size != BPF_REG_SIZE) {
4628                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4629                 return -EACCES;
4630         }
4631
4632         cur = env->cur_state->frame[env->cur_state->curframe];
4633         if (value_regno >= 0)
4634                 reg = &cur->regs[value_regno];
4635         if (!env->bypass_spec_v4) {
4636                 bool sanitize = reg && is_spillable_regtype(reg->type);
4637
4638                 for (i = 0; i < size; i++) {
4639                         u8 type = state->stack[spi].slot_type[i];
4640
4641                         if (type != STACK_MISC && type != STACK_ZERO) {
4642                                 sanitize = true;
4643                                 break;
4644                         }
4645                 }
4646
4647                 if (sanitize)
4648                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4649         }
4650
4651         err = destroy_if_dynptr_stack_slot(env, state, spi);
4652         if (err)
4653                 return err;
4654
4655         mark_stack_slot_scratched(env, spi);
4656         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4657             !register_is_null(reg) && env->bpf_capable) {
4658                 if (dst_reg != BPF_REG_FP) {
4659                         /* The backtracking logic can only recognize explicit
4660                          * stack slot address like [fp - 8]. Other spill of
4661                          * scalar via different register has to be conservative.
4662                          * Backtrack from here and mark all registers as precise
4663                          * that contributed into 'reg' being a constant.
4664                          */
4665                         err = mark_chain_precision(env, value_regno);
4666                         if (err)
4667                                 return err;
4668                 }
4669                 save_register_state(state, spi, reg, size);
4670                 /* Break the relation on a narrowing spill. */
4671                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4672                         state->stack[spi].spilled_ptr.id = 0;
4673         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4674                    insn->imm != 0 && env->bpf_capable) {
4675                 struct bpf_reg_state fake_reg = {};
4676
4677                 __mark_reg_known(&fake_reg, (u32)insn->imm);
4678                 fake_reg.type = SCALAR_VALUE;
4679                 save_register_state(state, spi, &fake_reg, size);
4680         } else if (reg && is_spillable_regtype(reg->type)) {
4681                 /* register containing pointer is being spilled into stack */
4682                 if (size != BPF_REG_SIZE) {
4683                         verbose_linfo(env, insn_idx, "; ");
4684                         verbose(env, "invalid size of register spill\n");
4685                         return -EACCES;
4686                 }
4687                 if (state != cur && reg->type == PTR_TO_STACK) {
4688                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4689                         return -EINVAL;
4690                 }
4691                 save_register_state(state, spi, reg, size);
4692         } else {
4693                 u8 type = STACK_MISC;
4694
4695                 /* regular write of data into stack destroys any spilled ptr */
4696                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4697                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4698                 if (is_stack_slot_special(&state->stack[spi]))
4699                         for (i = 0; i < BPF_REG_SIZE; i++)
4700                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4701
4702                 /* only mark the slot as written if all 8 bytes were written
4703                  * otherwise read propagation may incorrectly stop too soon
4704                  * when stack slots are partially written.
4705                  * This heuristic means that read propagation will be
4706                  * conservative, since it will add reg_live_read marks
4707                  * to stack slots all the way to first state when programs
4708                  * writes+reads less than 8 bytes
4709                  */
4710                 if (size == BPF_REG_SIZE)
4711                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4712
4713                 /* when we zero initialize stack slots mark them as such */
4714                 if ((reg && register_is_null(reg)) ||
4715                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4716                         /* backtracking doesn't work for STACK_ZERO yet. */
4717                         err = mark_chain_precision(env, value_regno);
4718                         if (err)
4719                                 return err;
4720                         type = STACK_ZERO;
4721                 }
4722
4723                 /* Mark slots affected by this stack write. */
4724                 for (i = 0; i < size; i++)
4725                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4726                                 type;
4727         }
4728         return 0;
4729 }
4730
4731 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4732  * known to contain a variable offset.
4733  * This function checks whether the write is permitted and conservatively
4734  * tracks the effects of the write, considering that each stack slot in the
4735  * dynamic range is potentially written to.
4736  *
4737  * 'off' includes 'regno->off'.
4738  * 'value_regno' can be -1, meaning that an unknown value is being written to
4739  * the stack.
4740  *
4741  * Spilled pointers in range are not marked as written because we don't know
4742  * what's going to be actually written. This means that read propagation for
4743  * future reads cannot be terminated by this write.
4744  *
4745  * For privileged programs, uninitialized stack slots are considered
4746  * initialized by this write (even though we don't know exactly what offsets
4747  * are going to be written to). The idea is that we don't want the verifier to
4748  * reject future reads that access slots written to through variable offsets.
4749  */
4750 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4751                                      /* func where register points to */
4752                                      struct bpf_func_state *state,
4753                                      int ptr_regno, int off, int size,
4754                                      int value_regno, int insn_idx)
4755 {
4756         struct bpf_func_state *cur; /* state of the current function */
4757         int min_off, max_off;
4758         int i, err;
4759         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4760         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4761         bool writing_zero = false;
4762         /* set if the fact that we're writing a zero is used to let any
4763          * stack slots remain STACK_ZERO
4764          */
4765         bool zero_used = false;
4766
4767         cur = env->cur_state->frame[env->cur_state->curframe];
4768         ptr_reg = &cur->regs[ptr_regno];
4769         min_off = ptr_reg->smin_value + off;
4770         max_off = ptr_reg->smax_value + off + size;
4771         if (value_regno >= 0)
4772                 value_reg = &cur->regs[value_regno];
4773         if ((value_reg && register_is_null(value_reg)) ||
4774             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4775                 writing_zero = true;
4776
4777         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4778         if (err)
4779                 return err;
4780
4781         for (i = min_off; i < max_off; i++) {
4782                 int spi;
4783
4784                 spi = __get_spi(i);
4785                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4786                 if (err)
4787                         return err;
4788         }
4789
4790         /* Variable offset writes destroy any spilled pointers in range. */
4791         for (i = min_off; i < max_off; i++) {
4792                 u8 new_type, *stype;
4793                 int slot, spi;
4794
4795                 slot = -i - 1;
4796                 spi = slot / BPF_REG_SIZE;
4797                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4798                 mark_stack_slot_scratched(env, spi);
4799
4800                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4801                         /* Reject the write if range we may write to has not
4802                          * been initialized beforehand. If we didn't reject
4803                          * here, the ptr status would be erased below (even
4804                          * though not all slots are actually overwritten),
4805                          * possibly opening the door to leaks.
4806                          *
4807                          * We do however catch STACK_INVALID case below, and
4808                          * only allow reading possibly uninitialized memory
4809                          * later for CAP_PERFMON, as the write may not happen to
4810                          * that slot.
4811                          */
4812                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4813                                 insn_idx, i);
4814                         return -EINVAL;
4815                 }
4816
4817                 /* Erase all spilled pointers. */
4818                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4819
4820                 /* Update the slot type. */
4821                 new_type = STACK_MISC;
4822                 if (writing_zero && *stype == STACK_ZERO) {
4823                         new_type = STACK_ZERO;
4824                         zero_used = true;
4825                 }
4826                 /* If the slot is STACK_INVALID, we check whether it's OK to
4827                  * pretend that it will be initialized by this write. The slot
4828                  * might not actually be written to, and so if we mark it as
4829                  * initialized future reads might leak uninitialized memory.
4830                  * For privileged programs, we will accept such reads to slots
4831                  * that may or may not be written because, if we're reject
4832                  * them, the error would be too confusing.
4833                  */
4834                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4835                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4836                                         insn_idx, i);
4837                         return -EINVAL;
4838                 }
4839                 *stype = new_type;
4840         }
4841         if (zero_used) {
4842                 /* backtracking doesn't work for STACK_ZERO yet. */
4843                 err = mark_chain_precision(env, value_regno);
4844                 if (err)
4845                         return err;
4846         }
4847         return 0;
4848 }
4849
4850 /* When register 'dst_regno' is assigned some values from stack[min_off,
4851  * max_off), we set the register's type according to the types of the
4852  * respective stack slots. If all the stack values are known to be zeros, then
4853  * so is the destination reg. Otherwise, the register is considered to be
4854  * SCALAR. This function does not deal with register filling; the caller must
4855  * ensure that all spilled registers in the stack range have been marked as
4856  * read.
4857  */
4858 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4859                                 /* func where src register points to */
4860                                 struct bpf_func_state *ptr_state,
4861                                 int min_off, int max_off, int dst_regno)
4862 {
4863         struct bpf_verifier_state *vstate = env->cur_state;
4864         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4865         int i, slot, spi;
4866         u8 *stype;
4867         int zeros = 0;
4868
4869         for (i = min_off; i < max_off; i++) {
4870                 slot = -i - 1;
4871                 spi = slot / BPF_REG_SIZE;
4872                 mark_stack_slot_scratched(env, spi);
4873                 stype = ptr_state->stack[spi].slot_type;
4874                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4875                         break;
4876                 zeros++;
4877         }
4878         if (zeros == max_off - min_off) {
4879                 /* any access_size read into register is zero extended,
4880                  * so the whole register == const_zero
4881                  */
4882                 __mark_reg_const_zero(&state->regs[dst_regno]);
4883                 /* backtracking doesn't support STACK_ZERO yet,
4884                  * so mark it precise here, so that later
4885                  * backtracking can stop here.
4886                  * Backtracking may not need this if this register
4887                  * doesn't participate in pointer adjustment.
4888                  * Forward propagation of precise flag is not
4889                  * necessary either. This mark is only to stop
4890                  * backtracking. Any register that contributed
4891                  * to const 0 was marked precise before spill.
4892                  */
4893                 state->regs[dst_regno].precise = true;
4894         } else {
4895                 /* have read misc data from the stack */
4896                 mark_reg_unknown(env, state->regs, dst_regno);
4897         }
4898         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4899 }
4900
4901 /* Read the stack at 'off' and put the results into the register indicated by
4902  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4903  * spilled reg.
4904  *
4905  * 'dst_regno' can be -1, meaning that the read value is not going to a
4906  * register.
4907  *
4908  * The access is assumed to be within the current stack bounds.
4909  */
4910 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4911                                       /* func where src register points to */
4912                                       struct bpf_func_state *reg_state,
4913                                       int off, int size, int dst_regno)
4914 {
4915         struct bpf_verifier_state *vstate = env->cur_state;
4916         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4917         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4918         struct bpf_reg_state *reg;
4919         u8 *stype, type;
4920
4921         stype = reg_state->stack[spi].slot_type;
4922         reg = &reg_state->stack[spi].spilled_ptr;
4923
4924         mark_stack_slot_scratched(env, spi);
4925
4926         if (is_spilled_reg(&reg_state->stack[spi])) {
4927                 u8 spill_size = 1;
4928
4929                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4930                         spill_size++;
4931
4932                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4933                         if (reg->type != SCALAR_VALUE) {
4934                                 verbose_linfo(env, env->insn_idx, "; ");
4935                                 verbose(env, "invalid size of register fill\n");
4936                                 return -EACCES;
4937                         }
4938
4939                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4940                         if (dst_regno < 0)
4941                                 return 0;
4942
4943                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4944                                 /* The earlier check_reg_arg() has decided the
4945                                  * subreg_def for this insn.  Save it first.
4946                                  */
4947                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4948
4949                                 copy_register_state(&state->regs[dst_regno], reg);
4950                                 state->regs[dst_regno].subreg_def = subreg_def;
4951                         } else {
4952                                 for (i = 0; i < size; i++) {
4953                                         type = stype[(slot - i) % BPF_REG_SIZE];
4954                                         if (type == STACK_SPILL)
4955                                                 continue;
4956                                         if (type == STACK_MISC)
4957                                                 continue;
4958                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4959                                                 continue;
4960                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4961                                                 off, i, size);
4962                                         return -EACCES;
4963                                 }
4964                                 mark_reg_unknown(env, state->regs, dst_regno);
4965                         }
4966                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4967                         return 0;
4968                 }
4969
4970                 if (dst_regno >= 0) {
4971                         /* restore register state from stack */
4972                         copy_register_state(&state->regs[dst_regno], reg);
4973                         /* mark reg as written since spilled pointer state likely
4974                          * has its liveness marks cleared by is_state_visited()
4975                          * which resets stack/reg liveness for state transitions
4976                          */
4977                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4978                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4979                         /* If dst_regno==-1, the caller is asking us whether
4980                          * it is acceptable to use this value as a SCALAR_VALUE
4981                          * (e.g. for XADD).
4982                          * We must not allow unprivileged callers to do that
4983                          * with spilled pointers.
4984                          */
4985                         verbose(env, "leaking pointer from stack off %d\n",
4986                                 off);
4987                         return -EACCES;
4988                 }
4989                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4990         } else {
4991                 for (i = 0; i < size; i++) {
4992                         type = stype[(slot - i) % BPF_REG_SIZE];
4993                         if (type == STACK_MISC)
4994                                 continue;
4995                         if (type == STACK_ZERO)
4996                                 continue;
4997                         if (type == STACK_INVALID && env->allow_uninit_stack)
4998                                 continue;
4999                         verbose(env, "invalid read from stack off %d+%d size %d\n",
5000                                 off, i, size);
5001                         return -EACCES;
5002                 }
5003                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
5004                 if (dst_regno >= 0)
5005                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
5006         }
5007         return 0;
5008 }
5009
5010 enum bpf_access_src {
5011         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
5012         ACCESS_HELPER = 2,  /* the access is performed by a helper */
5013 };
5014
5015 static int check_stack_range_initialized(struct bpf_verifier_env *env,
5016                                          int regno, int off, int access_size,
5017                                          bool zero_size_allowed,
5018                                          enum bpf_access_src type,
5019                                          struct bpf_call_arg_meta *meta);
5020
5021 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
5022 {
5023         return cur_regs(env) + regno;
5024 }
5025
5026 /* Read the stack at 'ptr_regno + off' and put the result into the register
5027  * 'dst_regno'.
5028  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
5029  * but not its variable offset.
5030  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
5031  *
5032  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
5033  * filling registers (i.e. reads of spilled register cannot be detected when
5034  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
5035  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
5036  * offset; for a fixed offset check_stack_read_fixed_off should be used
5037  * instead.
5038  */
5039 static int check_stack_read_var_off(struct bpf_verifier_env *env,
5040                                     int ptr_regno, int off, int size, int dst_regno)
5041 {
5042         /* The state of the source register. */
5043         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5044         struct bpf_func_state *ptr_state = func(env, reg);
5045         int err;
5046         int min_off, max_off;
5047
5048         /* Note that we pass a NULL meta, so raw access will not be permitted.
5049          */
5050         err = check_stack_range_initialized(env, ptr_regno, off, size,
5051                                             false, ACCESS_DIRECT, NULL);
5052         if (err)
5053                 return err;
5054
5055         min_off = reg->smin_value + off;
5056         max_off = reg->smax_value + off;
5057         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
5058         return 0;
5059 }
5060
5061 /* check_stack_read dispatches to check_stack_read_fixed_off or
5062  * check_stack_read_var_off.
5063  *
5064  * The caller must ensure that the offset falls within the allocated stack
5065  * bounds.
5066  *
5067  * 'dst_regno' is a register which will receive the value from the stack. It
5068  * can be -1, meaning that the read value is not going to a register.
5069  */
5070 static int check_stack_read(struct bpf_verifier_env *env,
5071                             int ptr_regno, int off, int size,
5072                             int dst_regno)
5073 {
5074         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5075         struct bpf_func_state *state = func(env, reg);
5076         int err;
5077         /* Some accesses are only permitted with a static offset. */
5078         bool var_off = !tnum_is_const(reg->var_off);
5079
5080         /* The offset is required to be static when reads don't go to a
5081          * register, in order to not leak pointers (see
5082          * check_stack_read_fixed_off).
5083          */
5084         if (dst_regno < 0 && var_off) {
5085                 char tn_buf[48];
5086
5087                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5088                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
5089                         tn_buf, off, size);
5090                 return -EACCES;
5091         }
5092         /* Variable offset is prohibited for unprivileged mode for simplicity
5093          * since it requires corresponding support in Spectre masking for stack
5094          * ALU. See also retrieve_ptr_limit(). The check in
5095          * check_stack_access_for_ptr_arithmetic() called by
5096          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
5097          * with variable offsets, therefore no check is required here. Further,
5098          * just checking it here would be insufficient as speculative stack
5099          * writes could still lead to unsafe speculative behaviour.
5100          */
5101         if (!var_off) {
5102                 off += reg->var_off.value;
5103                 err = check_stack_read_fixed_off(env, state, off, size,
5104                                                  dst_regno);
5105         } else {
5106                 /* Variable offset stack reads need more conservative handling
5107                  * than fixed offset ones. Note that dst_regno >= 0 on this
5108                  * branch.
5109                  */
5110                 err = check_stack_read_var_off(env, ptr_regno, off, size,
5111                                                dst_regno);
5112         }
5113         return err;
5114 }
5115
5116
5117 /* check_stack_write dispatches to check_stack_write_fixed_off or
5118  * check_stack_write_var_off.
5119  *
5120  * 'ptr_regno' is the register used as a pointer into the stack.
5121  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
5122  * 'value_regno' is the register whose value we're writing to the stack. It can
5123  * be -1, meaning that we're not writing from a register.
5124  *
5125  * The caller must ensure that the offset falls within the maximum stack size.
5126  */
5127 static int check_stack_write(struct bpf_verifier_env *env,
5128                              int ptr_regno, int off, int size,
5129                              int value_regno, int insn_idx)
5130 {
5131         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
5132         struct bpf_func_state *state = func(env, reg);
5133         int err;
5134
5135         if (tnum_is_const(reg->var_off)) {
5136                 off += reg->var_off.value;
5137                 err = check_stack_write_fixed_off(env, state, off, size,
5138                                                   value_regno, insn_idx);
5139         } else {
5140                 /* Variable offset stack reads need more conservative handling
5141                  * than fixed offset ones.
5142                  */
5143                 err = check_stack_write_var_off(env, state,
5144                                                 ptr_regno, off, size,
5145                                                 value_regno, insn_idx);
5146         }
5147         return err;
5148 }
5149
5150 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
5151                                  int off, int size, enum bpf_access_type type)
5152 {
5153         struct bpf_reg_state *regs = cur_regs(env);
5154         struct bpf_map *map = regs[regno].map_ptr;
5155         u32 cap = bpf_map_flags_to_cap(map);
5156
5157         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
5158                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
5159                         map->value_size, off, size);
5160                 return -EACCES;
5161         }
5162
5163         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
5164                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
5165                         map->value_size, off, size);
5166                 return -EACCES;
5167         }
5168
5169         return 0;
5170 }
5171
5172 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
5173 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
5174                               int off, int size, u32 mem_size,
5175                               bool zero_size_allowed)
5176 {
5177         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
5178         struct bpf_reg_state *reg;
5179
5180         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
5181                 return 0;
5182
5183         reg = &cur_regs(env)[regno];
5184         switch (reg->type) {
5185         case PTR_TO_MAP_KEY:
5186                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
5187                         mem_size, off, size);
5188                 break;
5189         case PTR_TO_MAP_VALUE:
5190                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
5191                         mem_size, off, size);
5192                 break;
5193         case PTR_TO_PACKET:
5194         case PTR_TO_PACKET_META:
5195         case PTR_TO_PACKET_END:
5196                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
5197                         off, size, regno, reg->id, off, mem_size);
5198                 break;
5199         case PTR_TO_MEM:
5200         default:
5201                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
5202                         mem_size, off, size);
5203         }
5204
5205         return -EACCES;
5206 }
5207
5208 /* check read/write into a memory region with possible variable offset */
5209 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
5210                                    int off, int size, u32 mem_size,
5211                                    bool zero_size_allowed)
5212 {
5213         struct bpf_verifier_state *vstate = env->cur_state;
5214         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5215         struct bpf_reg_state *reg = &state->regs[regno];
5216         int err;
5217
5218         /* We may have adjusted the register pointing to memory region, so we
5219          * need to try adding each of min_value and max_value to off
5220          * to make sure our theoretical access will be safe.
5221          *
5222          * The minimum value is only important with signed
5223          * comparisons where we can't assume the floor of a
5224          * value is 0.  If we are using signed variables for our
5225          * index'es we need to make sure that whatever we use
5226          * will have a set floor within our range.
5227          */
5228         if (reg->smin_value < 0 &&
5229             (reg->smin_value == S64_MIN ||
5230              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
5231               reg->smin_value + off < 0)) {
5232                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5233                         regno);
5234                 return -EACCES;
5235         }
5236         err = __check_mem_access(env, regno, reg->smin_value + off, size,
5237                                  mem_size, zero_size_allowed);
5238         if (err) {
5239                 verbose(env, "R%d min value is outside of the allowed memory range\n",
5240                         regno);
5241                 return err;
5242         }
5243
5244         /* If we haven't set a max value then we need to bail since we can't be
5245          * sure we won't do bad things.
5246          * If reg->umax_value + off could overflow, treat that as unbounded too.
5247          */
5248         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
5249                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
5250                         regno);
5251                 return -EACCES;
5252         }
5253         err = __check_mem_access(env, regno, reg->umax_value + off, size,
5254                                  mem_size, zero_size_allowed);
5255         if (err) {
5256                 verbose(env, "R%d max value is outside of the allowed memory range\n",
5257                         regno);
5258                 return err;
5259         }
5260
5261         return 0;
5262 }
5263
5264 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
5265                                const struct bpf_reg_state *reg, int regno,
5266                                bool fixed_off_ok)
5267 {
5268         /* Access to this pointer-typed register or passing it to a helper
5269          * is only allowed in its original, unmodified form.
5270          */
5271
5272         if (reg->off < 0) {
5273                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
5274                         reg_type_str(env, reg->type), regno, reg->off);
5275                 return -EACCES;
5276         }
5277
5278         if (!fixed_off_ok && reg->off) {
5279                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
5280                         reg_type_str(env, reg->type), regno, reg->off);
5281                 return -EACCES;
5282         }
5283
5284         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5285                 char tn_buf[48];
5286
5287                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5288                 verbose(env, "variable %s access var_off=%s disallowed\n",
5289                         reg_type_str(env, reg->type), tn_buf);
5290                 return -EACCES;
5291         }
5292
5293         return 0;
5294 }
5295
5296 int check_ptr_off_reg(struct bpf_verifier_env *env,
5297                       const struct bpf_reg_state *reg, int regno)
5298 {
5299         return __check_ptr_off_reg(env, reg, regno, false);
5300 }
5301
5302 static int map_kptr_match_type(struct bpf_verifier_env *env,
5303                                struct btf_field *kptr_field,
5304                                struct bpf_reg_state *reg, u32 regno)
5305 {
5306         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5307         int perm_flags;
5308         const char *reg_name = "";
5309
5310         if (btf_is_kernel(reg->btf)) {
5311                 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5312
5313                 /* Only unreferenced case accepts untrusted pointers */
5314                 if (kptr_field->type == BPF_KPTR_UNREF)
5315                         perm_flags |= PTR_UNTRUSTED;
5316         } else {
5317                 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5318                 if (kptr_field->type == BPF_KPTR_PERCPU)
5319                         perm_flags |= MEM_PERCPU;
5320         }
5321
5322         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5323                 goto bad_type;
5324
5325         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5326         reg_name = btf_type_name(reg->btf, reg->btf_id);
5327
5328         /* For ref_ptr case, release function check should ensure we get one
5329          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5330          * normal store of unreferenced kptr, we must ensure var_off is zero.
5331          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5332          * reg->off and reg->ref_obj_id are not needed here.
5333          */
5334         if (__check_ptr_off_reg(env, reg, regno, true))
5335                 return -EACCES;
5336
5337         /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5338          * we also need to take into account the reg->off.
5339          *
5340          * We want to support cases like:
5341          *
5342          * struct foo {
5343          *         struct bar br;
5344          *         struct baz bz;
5345          * };
5346          *
5347          * struct foo *v;
5348          * v = func();        // PTR_TO_BTF_ID
5349          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5350          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5351          *                    // first member type of struct after comparison fails
5352          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5353          *                    // to match type
5354          *
5355          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5356          * is zero. We must also ensure that btf_struct_ids_match does not walk
5357          * the struct to match type against first member of struct, i.e. reject
5358          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5359          * strict mode to true for type match.
5360          */
5361         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5362                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5363                                   kptr_field->type != BPF_KPTR_UNREF))
5364                 goto bad_type;
5365         return 0;
5366 bad_type:
5367         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5368                 reg_type_str(env, reg->type), reg_name);
5369         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5370         if (kptr_field->type == BPF_KPTR_UNREF)
5371                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5372                         targ_name);
5373         else
5374                 verbose(env, "\n");
5375         return -EINVAL;
5376 }
5377
5378 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5379  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5380  */
5381 static bool in_rcu_cs(struct bpf_verifier_env *env)
5382 {
5383         return env->cur_state->active_rcu_lock ||
5384                env->cur_state->active_lock.ptr ||
5385                !env->prog->aux->sleepable;
5386 }
5387
5388 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5389 BTF_SET_START(rcu_protected_types)
5390 BTF_ID(struct, prog_test_ref_kfunc)
5391 #ifdef CONFIG_CGROUPS
5392 BTF_ID(struct, cgroup)
5393 #endif
5394 BTF_ID(struct, bpf_cpumask)
5395 BTF_ID(struct, task_struct)
5396 BTF_SET_END(rcu_protected_types)
5397
5398 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5399 {
5400         if (!btf_is_kernel(btf))
5401                 return false;
5402         return btf_id_set_contains(&rcu_protected_types, btf_id);
5403 }
5404
5405 static bool rcu_safe_kptr(const struct btf_field *field)
5406 {
5407         const struct btf_field_kptr *kptr = &field->kptr;
5408
5409         return field->type == BPF_KPTR_PERCPU ||
5410                (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id));
5411 }
5412
5413 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field)
5414 {
5415         if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) {
5416                 if (kptr_field->type != BPF_KPTR_PERCPU)
5417                         return PTR_MAYBE_NULL | MEM_RCU;
5418                 return PTR_MAYBE_NULL | MEM_RCU | MEM_PERCPU;
5419         }
5420         return PTR_MAYBE_NULL | PTR_UNTRUSTED;
5421 }
5422
5423 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5424                                  int value_regno, int insn_idx,
5425                                  struct btf_field *kptr_field)
5426 {
5427         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5428         int class = BPF_CLASS(insn->code);
5429         struct bpf_reg_state *val_reg;
5430
5431         /* Things we already checked for in check_map_access and caller:
5432          *  - Reject cases where variable offset may touch kptr
5433          *  - size of access (must be BPF_DW)
5434          *  - tnum_is_const(reg->var_off)
5435          *  - kptr_field->offset == off + reg->var_off.value
5436          */
5437         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5438         if (BPF_MODE(insn->code) != BPF_MEM) {
5439                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5440                 return -EACCES;
5441         }
5442
5443         /* We only allow loading referenced kptr, since it will be marked as
5444          * untrusted, similar to unreferenced kptr.
5445          */
5446         if (class != BPF_LDX &&
5447             (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) {
5448                 verbose(env, "store to referenced kptr disallowed\n");
5449                 return -EACCES;
5450         }
5451
5452         if (class == BPF_LDX) {
5453                 val_reg = reg_state(env, value_regno);
5454                 /* We can simply mark the value_regno receiving the pointer
5455                  * value from map as PTR_TO_BTF_ID, with the correct type.
5456                  */
5457                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5458                                 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field));
5459                 /* For mark_ptr_or_null_reg */
5460                 val_reg->id = ++env->id_gen;
5461         } else if (class == BPF_STX) {
5462                 val_reg = reg_state(env, value_regno);
5463                 if (!register_is_null(val_reg) &&
5464                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5465                         return -EACCES;
5466         } else if (class == BPF_ST) {
5467                 if (insn->imm) {
5468                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5469                                 kptr_field->offset);
5470                         return -EACCES;
5471                 }
5472         } else {
5473                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5474                 return -EACCES;
5475         }
5476         return 0;
5477 }
5478
5479 /* check read/write into a map element with possible variable offset */
5480 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5481                             int off, int size, bool zero_size_allowed,
5482                             enum bpf_access_src src)
5483 {
5484         struct bpf_verifier_state *vstate = env->cur_state;
5485         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5486         struct bpf_reg_state *reg = &state->regs[regno];
5487         struct bpf_map *map = reg->map_ptr;
5488         struct btf_record *rec;
5489         int err, i;
5490
5491         err = check_mem_region_access(env, regno, off, size, map->value_size,
5492                                       zero_size_allowed);
5493         if (err)
5494                 return err;
5495
5496         if (IS_ERR_OR_NULL(map->record))
5497                 return 0;
5498         rec = map->record;
5499         for (i = 0; i < rec->cnt; i++) {
5500                 struct btf_field *field = &rec->fields[i];
5501                 u32 p = field->offset;
5502
5503                 /* If any part of a field  can be touched by load/store, reject
5504                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5505                  * it is sufficient to check x1 < y2 && y1 < x2.
5506                  */
5507                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5508                     p < reg->umax_value + off + size) {
5509                         switch (field->type) {
5510                         case BPF_KPTR_UNREF:
5511                         case BPF_KPTR_REF:
5512                         case BPF_KPTR_PERCPU:
5513                                 if (src != ACCESS_DIRECT) {
5514                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5515                                         return -EACCES;
5516                                 }
5517                                 if (!tnum_is_const(reg->var_off)) {
5518                                         verbose(env, "kptr access cannot have variable offset\n");
5519                                         return -EACCES;
5520                                 }
5521                                 if (p != off + reg->var_off.value) {
5522                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5523                                                 p, off + reg->var_off.value);
5524                                         return -EACCES;
5525                                 }
5526                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5527                                         verbose(env, "kptr access size must be BPF_DW\n");
5528                                         return -EACCES;
5529                                 }
5530                                 break;
5531                         default:
5532                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5533                                         btf_field_type_name(field->type));
5534                                 return -EACCES;
5535                         }
5536                 }
5537         }
5538         return 0;
5539 }
5540
5541 #define MAX_PACKET_OFF 0xffff
5542
5543 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5544                                        const struct bpf_call_arg_meta *meta,
5545                                        enum bpf_access_type t)
5546 {
5547         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5548
5549         switch (prog_type) {
5550         /* Program types only with direct read access go here! */
5551         case BPF_PROG_TYPE_LWT_IN:
5552         case BPF_PROG_TYPE_LWT_OUT:
5553         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5554         case BPF_PROG_TYPE_SK_REUSEPORT:
5555         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5556         case BPF_PROG_TYPE_CGROUP_SKB:
5557                 if (t == BPF_WRITE)
5558                         return false;
5559                 fallthrough;
5560
5561         /* Program types with direct read + write access go here! */
5562         case BPF_PROG_TYPE_SCHED_CLS:
5563         case BPF_PROG_TYPE_SCHED_ACT:
5564         case BPF_PROG_TYPE_XDP:
5565         case BPF_PROG_TYPE_LWT_XMIT:
5566         case BPF_PROG_TYPE_SK_SKB:
5567         case BPF_PROG_TYPE_SK_MSG:
5568                 if (meta)
5569                         return meta->pkt_access;
5570
5571                 env->seen_direct_write = true;
5572                 return true;
5573
5574         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5575                 if (t == BPF_WRITE)
5576                         env->seen_direct_write = true;
5577
5578                 return true;
5579
5580         default:
5581                 return false;
5582         }
5583 }
5584
5585 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5586                                int size, bool zero_size_allowed)
5587 {
5588         struct bpf_reg_state *regs = cur_regs(env);
5589         struct bpf_reg_state *reg = &regs[regno];
5590         int err;
5591
5592         /* We may have added a variable offset to the packet pointer; but any
5593          * reg->range we have comes after that.  We are only checking the fixed
5594          * offset.
5595          */
5596
5597         /* We don't allow negative numbers, because we aren't tracking enough
5598          * detail to prove they're safe.
5599          */
5600         if (reg->smin_value < 0) {
5601                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5602                         regno);
5603                 return -EACCES;
5604         }
5605
5606         err = reg->range < 0 ? -EINVAL :
5607               __check_mem_access(env, regno, off, size, reg->range,
5608                                  zero_size_allowed);
5609         if (err) {
5610                 verbose(env, "R%d offset is outside of the packet\n", regno);
5611                 return err;
5612         }
5613
5614         /* __check_mem_access has made sure "off + size - 1" is within u16.
5615          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5616          * otherwise find_good_pkt_pointers would have refused to set range info
5617          * that __check_mem_access would have rejected this pkt access.
5618          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5619          */
5620         env->prog->aux->max_pkt_offset =
5621                 max_t(u32, env->prog->aux->max_pkt_offset,
5622                       off + reg->umax_value + size - 1);
5623
5624         return err;
5625 }
5626
5627 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5628 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5629                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5630                             struct btf **btf, u32 *btf_id)
5631 {
5632         struct bpf_insn_access_aux info = {
5633                 .reg_type = *reg_type,
5634                 .log = &env->log,
5635         };
5636
5637         if (env->ops->is_valid_access &&
5638             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5639                 /* A non zero info.ctx_field_size indicates that this field is a
5640                  * candidate for later verifier transformation to load the whole
5641                  * field and then apply a mask when accessed with a narrower
5642                  * access than actual ctx access size. A zero info.ctx_field_size
5643                  * will only allow for whole field access and rejects any other
5644                  * type of narrower access.
5645                  */
5646                 *reg_type = info.reg_type;
5647
5648                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5649                         *btf = info.btf;
5650                         *btf_id = info.btf_id;
5651                 } else {
5652                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5653                 }
5654                 /* remember the offset of last byte accessed in ctx */
5655                 if (env->prog->aux->max_ctx_offset < off + size)
5656                         env->prog->aux->max_ctx_offset = off + size;
5657                 return 0;
5658         }
5659
5660         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5661         return -EACCES;
5662 }
5663
5664 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5665                                   int size)
5666 {
5667         if (size < 0 || off < 0 ||
5668             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5669                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5670                         off, size);
5671                 return -EACCES;
5672         }
5673         return 0;
5674 }
5675
5676 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5677                              u32 regno, int off, int size,
5678                              enum bpf_access_type t)
5679 {
5680         struct bpf_reg_state *regs = cur_regs(env);
5681         struct bpf_reg_state *reg = &regs[regno];
5682         struct bpf_insn_access_aux info = {};
5683         bool valid;
5684
5685         if (reg->smin_value < 0) {
5686                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5687                         regno);
5688                 return -EACCES;
5689         }
5690
5691         switch (reg->type) {
5692         case PTR_TO_SOCK_COMMON:
5693                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5694                 break;
5695         case PTR_TO_SOCKET:
5696                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5697                 break;
5698         case PTR_TO_TCP_SOCK:
5699                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5700                 break;
5701         case PTR_TO_XDP_SOCK:
5702                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5703                 break;
5704         default:
5705                 valid = false;
5706         }
5707
5708
5709         if (valid) {
5710                 env->insn_aux_data[insn_idx].ctx_field_size =
5711                         info.ctx_field_size;
5712                 return 0;
5713         }
5714
5715         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5716                 regno, reg_type_str(env, reg->type), off, size);
5717
5718         return -EACCES;
5719 }
5720
5721 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5722 {
5723         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5724 }
5725
5726 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5727 {
5728         const struct bpf_reg_state *reg = reg_state(env, regno);
5729
5730         return reg->type == PTR_TO_CTX;
5731 }
5732
5733 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5734 {
5735         const struct bpf_reg_state *reg = reg_state(env, regno);
5736
5737         return type_is_sk_pointer(reg->type);
5738 }
5739
5740 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5741 {
5742         const struct bpf_reg_state *reg = reg_state(env, regno);
5743
5744         return type_is_pkt_pointer(reg->type);
5745 }
5746
5747 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5748 {
5749         const struct bpf_reg_state *reg = reg_state(env, regno);
5750
5751         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5752         return reg->type == PTR_TO_FLOW_KEYS;
5753 }
5754
5755 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5756 #ifdef CONFIG_NET
5757         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5758         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5759         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5760 #endif
5761         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5762 };
5763
5764 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5765 {
5766         /* A referenced register is always trusted. */
5767         if (reg->ref_obj_id)
5768                 return true;
5769
5770         /* Types listed in the reg2btf_ids are always trusted */
5771         if (reg2btf_ids[base_type(reg->type)])
5772                 return true;
5773
5774         /* If a register is not referenced, it is trusted if it has the
5775          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5776          * other type modifiers may be safe, but we elect to take an opt-in
5777          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5778          * not.
5779          *
5780          * Eventually, we should make PTR_TRUSTED the single source of truth
5781          * for whether a register is trusted.
5782          */
5783         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5784                !bpf_type_has_unsafe_modifiers(reg->type);
5785 }
5786
5787 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5788 {
5789         return reg->type & MEM_RCU;
5790 }
5791
5792 static void clear_trusted_flags(enum bpf_type_flag *flag)
5793 {
5794         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5795 }
5796
5797 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5798                                    const struct bpf_reg_state *reg,
5799                                    int off, int size, bool strict)
5800 {
5801         struct tnum reg_off;
5802         int ip_align;
5803
5804         /* Byte size accesses are always allowed. */
5805         if (!strict || size == 1)
5806                 return 0;
5807
5808         /* For platforms that do not have a Kconfig enabling
5809          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5810          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5811          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5812          * to this code only in strict mode where we want to emulate
5813          * the NET_IP_ALIGN==2 checking.  Therefore use an
5814          * unconditional IP align value of '2'.
5815          */
5816         ip_align = 2;
5817
5818         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5819         if (!tnum_is_aligned(reg_off, size)) {
5820                 char tn_buf[48];
5821
5822                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5823                 verbose(env,
5824                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5825                         ip_align, tn_buf, reg->off, off, size);
5826                 return -EACCES;
5827         }
5828
5829         return 0;
5830 }
5831
5832 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5833                                        const struct bpf_reg_state *reg,
5834                                        const char *pointer_desc,
5835                                        int off, int size, bool strict)
5836 {
5837         struct tnum reg_off;
5838
5839         /* Byte size accesses are always allowed. */
5840         if (!strict || size == 1)
5841                 return 0;
5842
5843         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5844         if (!tnum_is_aligned(reg_off, size)) {
5845                 char tn_buf[48];
5846
5847                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5848                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5849                         pointer_desc, tn_buf, reg->off, off, size);
5850                 return -EACCES;
5851         }
5852
5853         return 0;
5854 }
5855
5856 static int check_ptr_alignment(struct bpf_verifier_env *env,
5857                                const struct bpf_reg_state *reg, int off,
5858                                int size, bool strict_alignment_once)
5859 {
5860         bool strict = env->strict_alignment || strict_alignment_once;
5861         const char *pointer_desc = "";
5862
5863         switch (reg->type) {
5864         case PTR_TO_PACKET:
5865         case PTR_TO_PACKET_META:
5866                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5867                  * right in front, treat it the very same way.
5868                  */
5869                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5870         case PTR_TO_FLOW_KEYS:
5871                 pointer_desc = "flow keys ";
5872                 break;
5873         case PTR_TO_MAP_KEY:
5874                 pointer_desc = "key ";
5875                 break;
5876         case PTR_TO_MAP_VALUE:
5877                 pointer_desc = "value ";
5878                 break;
5879         case PTR_TO_CTX:
5880                 pointer_desc = "context ";
5881                 break;
5882         case PTR_TO_STACK:
5883                 pointer_desc = "stack ";
5884                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5885                  * and check_stack_read_fixed_off() relies on stack accesses being
5886                  * aligned.
5887                  */
5888                 strict = true;
5889                 break;
5890         case PTR_TO_SOCKET:
5891                 pointer_desc = "sock ";
5892                 break;
5893         case PTR_TO_SOCK_COMMON:
5894                 pointer_desc = "sock_common ";
5895                 break;
5896         case PTR_TO_TCP_SOCK:
5897                 pointer_desc = "tcp_sock ";
5898                 break;
5899         case PTR_TO_XDP_SOCK:
5900                 pointer_desc = "xdp_sock ";
5901                 break;
5902         default:
5903                 break;
5904         }
5905         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5906                                            strict);
5907 }
5908
5909 static int update_stack_depth(struct bpf_verifier_env *env,
5910                               const struct bpf_func_state *func,
5911                               int off)
5912 {
5913         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5914
5915         if (stack >= -off)
5916                 return 0;
5917
5918         /* update known max for given subprogram */
5919         env->subprog_info[func->subprogno].stack_depth = -off;
5920         return 0;
5921 }
5922
5923 /* starting from main bpf function walk all instructions of the function
5924  * and recursively walk all callees that given function can call.
5925  * Ignore jump and exit insns.
5926  * Since recursion is prevented by check_cfg() this algorithm
5927  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5928  */
5929 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5930 {
5931         struct bpf_subprog_info *subprog = env->subprog_info;
5932         struct bpf_insn *insn = env->prog->insnsi;
5933         int depth = 0, frame = 0, i, subprog_end;
5934         bool tail_call_reachable = false;
5935         int ret_insn[MAX_CALL_FRAMES];
5936         int ret_prog[MAX_CALL_FRAMES];
5937         int j;
5938
5939         i = subprog[idx].start;
5940 process_func:
5941         /* protect against potential stack overflow that might happen when
5942          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5943          * depth for such case down to 256 so that the worst case scenario
5944          * would result in 8k stack size (32 which is tailcall limit * 256 =
5945          * 8k).
5946          *
5947          * To get the idea what might happen, see an example:
5948          * func1 -> sub rsp, 128
5949          *  subfunc1 -> sub rsp, 256
5950          *  tailcall1 -> add rsp, 256
5951          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5952          *   subfunc2 -> sub rsp, 64
5953          *   subfunc22 -> sub rsp, 128
5954          *   tailcall2 -> add rsp, 128
5955          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5956          *
5957          * tailcall will unwind the current stack frame but it will not get rid
5958          * of caller's stack as shown on the example above.
5959          */
5960         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5961                 verbose(env,
5962                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5963                         depth);
5964                 return -EACCES;
5965         }
5966         /* round up to 32-bytes, since this is granularity
5967          * of interpreter stack size
5968          */
5969         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5970         if (depth > MAX_BPF_STACK) {
5971                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5972                         frame + 1, depth);
5973                 return -EACCES;
5974         }
5975 continue_func:
5976         subprog_end = subprog[idx + 1].start;
5977         for (; i < subprog_end; i++) {
5978                 int next_insn, sidx;
5979
5980                 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) {
5981                         bool err = false;
5982
5983                         if (!is_bpf_throw_kfunc(insn + i))
5984                                 continue;
5985                         if (subprog[idx].is_cb)
5986                                 err = true;
5987                         for (int c = 0; c < frame && !err; c++) {
5988                                 if (subprog[ret_prog[c]].is_cb) {
5989                                         err = true;
5990                                         break;
5991                                 }
5992                         }
5993                         if (!err)
5994                                 continue;
5995                         verbose(env,
5996                                 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
5997                                 i, idx);
5998                         return -EINVAL;
5999                 }
6000
6001                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
6002                         continue;
6003                 /* remember insn and function to return to */
6004                 ret_insn[frame] = i + 1;
6005                 ret_prog[frame] = idx;
6006
6007                 /* find the callee */
6008                 next_insn = i + insn[i].imm + 1;
6009                 sidx = find_subprog(env, next_insn);
6010                 if (sidx < 0) {
6011                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6012                                   next_insn);
6013                         return -EFAULT;
6014                 }
6015                 if (subprog[sidx].is_async_cb) {
6016                         if (subprog[sidx].has_tail_call) {
6017                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
6018                                 return -EFAULT;
6019                         }
6020                         /* async callbacks don't increase bpf prog stack size unless called directly */
6021                         if (!bpf_pseudo_call(insn + i))
6022                                 continue;
6023                         if (subprog[sidx].is_exception_cb) {
6024                                 verbose(env, "insn %d cannot call exception cb directly\n", i);
6025                                 return -EINVAL;
6026                         }
6027                 }
6028                 i = next_insn;
6029                 idx = sidx;
6030
6031                 if (subprog[idx].has_tail_call)
6032                         tail_call_reachable = true;
6033
6034                 frame++;
6035                 if (frame >= MAX_CALL_FRAMES) {
6036                         verbose(env, "the call stack of %d frames is too deep !\n",
6037                                 frame);
6038                         return -E2BIG;
6039                 }
6040                 goto process_func;
6041         }
6042         /* if tail call got detected across bpf2bpf calls then mark each of the
6043          * currently present subprog frames as tail call reachable subprogs;
6044          * this info will be utilized by JIT so that we will be preserving the
6045          * tail call counter throughout bpf2bpf calls combined with tailcalls
6046          */
6047         if (tail_call_reachable)
6048                 for (j = 0; j < frame; j++) {
6049                         if (subprog[ret_prog[j]].is_exception_cb) {
6050                                 verbose(env, "cannot tail call within exception cb\n");
6051                                 return -EINVAL;
6052                         }
6053                         subprog[ret_prog[j]].tail_call_reachable = true;
6054                 }
6055         if (subprog[0].tail_call_reachable)
6056                 env->prog->aux->tail_call_reachable = true;
6057
6058         /* end of for() loop means the last insn of the 'subprog'
6059          * was reached. Doesn't matter whether it was JA or EXIT
6060          */
6061         if (frame == 0)
6062                 return 0;
6063         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
6064         frame--;
6065         i = ret_insn[frame];
6066         idx = ret_prog[frame];
6067         goto continue_func;
6068 }
6069
6070 static int check_max_stack_depth(struct bpf_verifier_env *env)
6071 {
6072         struct bpf_subprog_info *si = env->subprog_info;
6073         int ret;
6074
6075         for (int i = 0; i < env->subprog_cnt; i++) {
6076                 if (!i || si[i].is_async_cb) {
6077                         ret = check_max_stack_depth_subprog(env, i);
6078                         if (ret < 0)
6079                                 return ret;
6080                 }
6081                 continue;
6082         }
6083         return 0;
6084 }
6085
6086 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
6087 static int get_callee_stack_depth(struct bpf_verifier_env *env,
6088                                   const struct bpf_insn *insn, int idx)
6089 {
6090         int start = idx + insn->imm + 1, subprog;
6091
6092         subprog = find_subprog(env, start);
6093         if (subprog < 0) {
6094                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
6095                           start);
6096                 return -EFAULT;
6097         }
6098         return env->subprog_info[subprog].stack_depth;
6099 }
6100 #endif
6101
6102 static int __check_buffer_access(struct bpf_verifier_env *env,
6103                                  const char *buf_info,
6104                                  const struct bpf_reg_state *reg,
6105                                  int regno, int off, int size)
6106 {
6107         if (off < 0) {
6108                 verbose(env,
6109                         "R%d invalid %s buffer access: off=%d, size=%d\n",
6110                         regno, buf_info, off, size);
6111                 return -EACCES;
6112         }
6113         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6114                 char tn_buf[48];
6115
6116                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6117                 verbose(env,
6118                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
6119                         regno, off, tn_buf);
6120                 return -EACCES;
6121         }
6122
6123         return 0;
6124 }
6125
6126 static int check_tp_buffer_access(struct bpf_verifier_env *env,
6127                                   const struct bpf_reg_state *reg,
6128                                   int regno, int off, int size)
6129 {
6130         int err;
6131
6132         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
6133         if (err)
6134                 return err;
6135
6136         if (off + size > env->prog->aux->max_tp_access)
6137                 env->prog->aux->max_tp_access = off + size;
6138
6139         return 0;
6140 }
6141
6142 static int check_buffer_access(struct bpf_verifier_env *env,
6143                                const struct bpf_reg_state *reg,
6144                                int regno, int off, int size,
6145                                bool zero_size_allowed,
6146                                u32 *max_access)
6147 {
6148         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
6149         int err;
6150
6151         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
6152         if (err)
6153                 return err;
6154
6155         if (off + size > *max_access)
6156                 *max_access = off + size;
6157
6158         return 0;
6159 }
6160
6161 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
6162 static void zext_32_to_64(struct bpf_reg_state *reg)
6163 {
6164         reg->var_off = tnum_subreg(reg->var_off);
6165         __reg_assign_32_into_64(reg);
6166 }
6167
6168 /* truncate register to smaller size (in bytes)
6169  * must be called with size < BPF_REG_SIZE
6170  */
6171 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
6172 {
6173         u64 mask;
6174
6175         /* clear high bits in bit representation */
6176         reg->var_off = tnum_cast(reg->var_off, size);
6177
6178         /* fix arithmetic bounds */
6179         mask = ((u64)1 << (size * 8)) - 1;
6180         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
6181                 reg->umin_value &= mask;
6182                 reg->umax_value &= mask;
6183         } else {
6184                 reg->umin_value = 0;
6185                 reg->umax_value = mask;
6186         }
6187         reg->smin_value = reg->umin_value;
6188         reg->smax_value = reg->umax_value;
6189
6190         /* If size is smaller than 32bit register the 32bit register
6191          * values are also truncated so we push 64-bit bounds into
6192          * 32-bit bounds. Above were truncated < 32-bits already.
6193          */
6194         if (size >= 4)
6195                 return;
6196         __reg_combine_64_into_32(reg);
6197 }
6198
6199 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
6200 {
6201         if (size == 1) {
6202                 reg->smin_value = reg->s32_min_value = S8_MIN;
6203                 reg->smax_value = reg->s32_max_value = S8_MAX;
6204         } else if (size == 2) {
6205                 reg->smin_value = reg->s32_min_value = S16_MIN;
6206                 reg->smax_value = reg->s32_max_value = S16_MAX;
6207         } else {
6208                 /* size == 4 */
6209                 reg->smin_value = reg->s32_min_value = S32_MIN;
6210                 reg->smax_value = reg->s32_max_value = S32_MAX;
6211         }
6212         reg->umin_value = reg->u32_min_value = 0;
6213         reg->umax_value = U64_MAX;
6214         reg->u32_max_value = U32_MAX;
6215         reg->var_off = tnum_unknown;
6216 }
6217
6218 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
6219 {
6220         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
6221         u64 top_smax_value, top_smin_value;
6222         u64 num_bits = size * 8;
6223
6224         if (tnum_is_const(reg->var_off)) {
6225                 u64_cval = reg->var_off.value;
6226                 if (size == 1)
6227                         reg->var_off = tnum_const((s8)u64_cval);
6228                 else if (size == 2)
6229                         reg->var_off = tnum_const((s16)u64_cval);
6230                 else
6231                         /* size == 4 */
6232                         reg->var_off = tnum_const((s32)u64_cval);
6233
6234                 u64_cval = reg->var_off.value;
6235                 reg->smax_value = reg->smin_value = u64_cval;
6236                 reg->umax_value = reg->umin_value = u64_cval;
6237                 reg->s32_max_value = reg->s32_min_value = u64_cval;
6238                 reg->u32_max_value = reg->u32_min_value = u64_cval;
6239                 return;
6240         }
6241
6242         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
6243         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
6244
6245         if (top_smax_value != top_smin_value)
6246                 goto out;
6247
6248         /* find the s64_min and s64_min after sign extension */
6249         if (size == 1) {
6250                 init_s64_max = (s8)reg->smax_value;
6251                 init_s64_min = (s8)reg->smin_value;
6252         } else if (size == 2) {
6253                 init_s64_max = (s16)reg->smax_value;
6254                 init_s64_min = (s16)reg->smin_value;
6255         } else {
6256                 init_s64_max = (s32)reg->smax_value;
6257                 init_s64_min = (s32)reg->smin_value;
6258         }
6259
6260         s64_max = max(init_s64_max, init_s64_min);
6261         s64_min = min(init_s64_max, init_s64_min);
6262
6263         /* both of s64_max/s64_min positive or negative */
6264         if ((s64_max >= 0) == (s64_min >= 0)) {
6265                 reg->smin_value = reg->s32_min_value = s64_min;
6266                 reg->smax_value = reg->s32_max_value = s64_max;
6267                 reg->umin_value = reg->u32_min_value = s64_min;
6268                 reg->umax_value = reg->u32_max_value = s64_max;
6269                 reg->var_off = tnum_range(s64_min, s64_max);
6270                 return;
6271         }
6272
6273 out:
6274         set_sext64_default_val(reg, size);
6275 }
6276
6277 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
6278 {
6279         if (size == 1) {
6280                 reg->s32_min_value = S8_MIN;
6281                 reg->s32_max_value = S8_MAX;
6282         } else {
6283                 /* size == 2 */
6284                 reg->s32_min_value = S16_MIN;
6285                 reg->s32_max_value = S16_MAX;
6286         }
6287         reg->u32_min_value = 0;
6288         reg->u32_max_value = U32_MAX;
6289 }
6290
6291 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
6292 {
6293         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
6294         u32 top_smax_value, top_smin_value;
6295         u32 num_bits = size * 8;
6296
6297         if (tnum_is_const(reg->var_off)) {
6298                 u32_val = reg->var_off.value;
6299                 if (size == 1)
6300                         reg->var_off = tnum_const((s8)u32_val);
6301                 else
6302                         reg->var_off = tnum_const((s16)u32_val);
6303
6304                 u32_val = reg->var_off.value;
6305                 reg->s32_min_value = reg->s32_max_value = u32_val;
6306                 reg->u32_min_value = reg->u32_max_value = u32_val;
6307                 return;
6308         }
6309
6310         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
6311         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
6312
6313         if (top_smax_value != top_smin_value)
6314                 goto out;
6315
6316         /* find the s32_min and s32_min after sign extension */
6317         if (size == 1) {
6318                 init_s32_max = (s8)reg->s32_max_value;
6319                 init_s32_min = (s8)reg->s32_min_value;
6320         } else {
6321                 /* size == 2 */
6322                 init_s32_max = (s16)reg->s32_max_value;
6323                 init_s32_min = (s16)reg->s32_min_value;
6324         }
6325         s32_max = max(init_s32_max, init_s32_min);
6326         s32_min = min(init_s32_max, init_s32_min);
6327
6328         if ((s32_min >= 0) == (s32_max >= 0)) {
6329                 reg->s32_min_value = s32_min;
6330                 reg->s32_max_value = s32_max;
6331                 reg->u32_min_value = (u32)s32_min;
6332                 reg->u32_max_value = (u32)s32_max;
6333                 return;
6334         }
6335
6336 out:
6337         set_sext32_default_val(reg, size);
6338 }
6339
6340 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6341 {
6342         /* A map is considered read-only if the following condition are true:
6343          *
6344          * 1) BPF program side cannot change any of the map content. The
6345          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6346          *    and was set at map creation time.
6347          * 2) The map value(s) have been initialized from user space by a
6348          *    loader and then "frozen", such that no new map update/delete
6349          *    operations from syscall side are possible for the rest of
6350          *    the map's lifetime from that point onwards.
6351          * 3) Any parallel/pending map update/delete operations from syscall
6352          *    side have been completed. Only after that point, it's safe to
6353          *    assume that map value(s) are immutable.
6354          */
6355         return (map->map_flags & BPF_F_RDONLY_PROG) &&
6356                READ_ONCE(map->frozen) &&
6357                !bpf_map_write_active(map);
6358 }
6359
6360 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6361                                bool is_ldsx)
6362 {
6363         void *ptr;
6364         u64 addr;
6365         int err;
6366
6367         err = map->ops->map_direct_value_addr(map, &addr, off);
6368         if (err)
6369                 return err;
6370         ptr = (void *)(long)addr + off;
6371
6372         switch (size) {
6373         case sizeof(u8):
6374                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6375                 break;
6376         case sizeof(u16):
6377                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6378                 break;
6379         case sizeof(u32):
6380                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6381                 break;
6382         case sizeof(u64):
6383                 *val = *(u64 *)ptr;
6384                 break;
6385         default:
6386                 return -EINVAL;
6387         }
6388         return 0;
6389 }
6390
6391 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6392 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6393 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6394
6395 /*
6396  * Allow list few fields as RCU trusted or full trusted.
6397  * This logic doesn't allow mix tagging and will be removed once GCC supports
6398  * btf_type_tag.
6399  */
6400
6401 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6402 BTF_TYPE_SAFE_RCU(struct task_struct) {
6403         const cpumask_t *cpus_ptr;
6404         struct css_set __rcu *cgroups;
6405         struct task_struct __rcu *real_parent;
6406         struct task_struct *group_leader;
6407 };
6408
6409 BTF_TYPE_SAFE_RCU(struct cgroup) {
6410         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6411         struct kernfs_node *kn;
6412 };
6413
6414 BTF_TYPE_SAFE_RCU(struct css_set) {
6415         struct cgroup *dfl_cgrp;
6416 };
6417
6418 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6419 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6420         struct file __rcu *exe_file;
6421 };
6422
6423 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6424  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6425  */
6426 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6427         struct sock *sk;
6428 };
6429
6430 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6431         struct sock *sk;
6432 };
6433
6434 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6435 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6436         struct seq_file *seq;
6437 };
6438
6439 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6440         struct bpf_iter_meta *meta;
6441         struct task_struct *task;
6442 };
6443
6444 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6445         struct file *file;
6446 };
6447
6448 BTF_TYPE_SAFE_TRUSTED(struct file) {
6449         struct inode *f_inode;
6450 };
6451
6452 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6453         /* no negative dentry-s in places where bpf can see it */
6454         struct inode *d_inode;
6455 };
6456
6457 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6458         struct sock *sk;
6459 };
6460
6461 static bool type_is_rcu(struct bpf_verifier_env *env,
6462                         struct bpf_reg_state *reg,
6463                         const char *field_name, u32 btf_id)
6464 {
6465         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6466         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6467         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6468
6469         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6470 }
6471
6472 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6473                                 struct bpf_reg_state *reg,
6474                                 const char *field_name, u32 btf_id)
6475 {
6476         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6477         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6478         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6479
6480         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6481 }
6482
6483 static bool type_is_trusted(struct bpf_verifier_env *env,
6484                             struct bpf_reg_state *reg,
6485                             const char *field_name, u32 btf_id)
6486 {
6487         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6488         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6489         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6490         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6491         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6492         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6493
6494         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6495 }
6496
6497 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6498                                    struct bpf_reg_state *regs,
6499                                    int regno, int off, int size,
6500                                    enum bpf_access_type atype,
6501                                    int value_regno)
6502 {
6503         struct bpf_reg_state *reg = regs + regno;
6504         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6505         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6506         const char *field_name = NULL;
6507         enum bpf_type_flag flag = 0;
6508         u32 btf_id = 0;
6509         int ret;
6510
6511         if (!env->allow_ptr_leaks) {
6512                 verbose(env,
6513                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6514                         tname);
6515                 return -EPERM;
6516         }
6517         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6518                 verbose(env,
6519                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6520                         tname);
6521                 return -EINVAL;
6522         }
6523         if (off < 0) {
6524                 verbose(env,
6525                         "R%d is ptr_%s invalid negative access: off=%d\n",
6526                         regno, tname, off);
6527                 return -EACCES;
6528         }
6529         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6530                 char tn_buf[48];
6531
6532                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6533                 verbose(env,
6534                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6535                         regno, tname, off, tn_buf);
6536                 return -EACCES;
6537         }
6538
6539         if (reg->type & MEM_USER) {
6540                 verbose(env,
6541                         "R%d is ptr_%s access user memory: off=%d\n",
6542                         regno, tname, off);
6543                 return -EACCES;
6544         }
6545
6546         if (reg->type & MEM_PERCPU) {
6547                 verbose(env,
6548                         "R%d is ptr_%s access percpu memory: off=%d\n",
6549                         regno, tname, off);
6550                 return -EACCES;
6551         }
6552
6553         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6554                 if (!btf_is_kernel(reg->btf)) {
6555                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6556                         return -EFAULT;
6557                 }
6558                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6559         } else {
6560                 /* Writes are permitted with default btf_struct_access for
6561                  * program allocated objects (which always have ref_obj_id > 0),
6562                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6563                  */
6564                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6565                         verbose(env, "only read is supported\n");
6566                         return -EACCES;
6567                 }
6568
6569                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6570                     !(reg->type & MEM_RCU) && !reg->ref_obj_id) {
6571                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6572                         return -EFAULT;
6573                 }
6574
6575                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6576         }
6577
6578         if (ret < 0)
6579                 return ret;
6580
6581         if (ret != PTR_TO_BTF_ID) {
6582                 /* just mark; */
6583
6584         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6585                 /* If this is an untrusted pointer, all pointers formed by walking it
6586                  * also inherit the untrusted flag.
6587                  */
6588                 flag = PTR_UNTRUSTED;
6589
6590         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6591                 /* By default any pointer obtained from walking a trusted pointer is no
6592                  * longer trusted, unless the field being accessed has explicitly been
6593                  * marked as inheriting its parent's state of trust (either full or RCU).
6594                  * For example:
6595                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6596                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6597                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6598                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6599                  *
6600                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6601                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6602                  */
6603                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6604                         flag |= PTR_TRUSTED;
6605                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6606                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6607                                 /* ignore __rcu tag and mark it MEM_RCU */
6608                                 flag |= MEM_RCU;
6609                         } else if (flag & MEM_RCU ||
6610                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6611                                 /* __rcu tagged pointers can be NULL */
6612                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6613
6614                                 /* We always trust them */
6615                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6616                                     flag & PTR_UNTRUSTED)
6617                                         flag &= ~PTR_UNTRUSTED;
6618                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6619                                 /* keep as-is */
6620                         } else {
6621                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6622                                 clear_trusted_flags(&flag);
6623                         }
6624                 } else {
6625                         /*
6626                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6627                          * aggressively mark as untrusted otherwise such
6628                          * pointers will be plain PTR_TO_BTF_ID without flags
6629                          * and will be allowed to be passed into helpers for
6630                          * compat reasons.
6631                          */
6632                         flag = PTR_UNTRUSTED;
6633                 }
6634         } else {
6635                 /* Old compat. Deprecated */
6636                 clear_trusted_flags(&flag);
6637         }
6638
6639         if (atype == BPF_READ && value_regno >= 0)
6640                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6641
6642         return 0;
6643 }
6644
6645 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6646                                    struct bpf_reg_state *regs,
6647                                    int regno, int off, int size,
6648                                    enum bpf_access_type atype,
6649                                    int value_regno)
6650 {
6651         struct bpf_reg_state *reg = regs + regno;
6652         struct bpf_map *map = reg->map_ptr;
6653         struct bpf_reg_state map_reg;
6654         enum bpf_type_flag flag = 0;
6655         const struct btf_type *t;
6656         const char *tname;
6657         u32 btf_id;
6658         int ret;
6659
6660         if (!btf_vmlinux) {
6661                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6662                 return -ENOTSUPP;
6663         }
6664
6665         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6666                 verbose(env, "map_ptr access not supported for map type %d\n",
6667                         map->map_type);
6668                 return -ENOTSUPP;
6669         }
6670
6671         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6672         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6673
6674         if (!env->allow_ptr_leaks) {
6675                 verbose(env,
6676                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6677                         tname);
6678                 return -EPERM;
6679         }
6680
6681         if (off < 0) {
6682                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6683                         regno, tname, off);
6684                 return -EACCES;
6685         }
6686
6687         if (atype != BPF_READ) {
6688                 verbose(env, "only read from %s is supported\n", tname);
6689                 return -EACCES;
6690         }
6691
6692         /* Simulate access to a PTR_TO_BTF_ID */
6693         memset(&map_reg, 0, sizeof(map_reg));
6694         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6695         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6696         if (ret < 0)
6697                 return ret;
6698
6699         if (value_regno >= 0)
6700                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6701
6702         return 0;
6703 }
6704
6705 /* Check that the stack access at the given offset is within bounds. The
6706  * maximum valid offset is -1.
6707  *
6708  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6709  * -state->allocated_stack for reads.
6710  */
6711 static int check_stack_slot_within_bounds(int off,
6712                                           struct bpf_func_state *state,
6713                                           enum bpf_access_type t)
6714 {
6715         int min_valid_off;
6716
6717         if (t == BPF_WRITE)
6718                 min_valid_off = -MAX_BPF_STACK;
6719         else
6720                 min_valid_off = -state->allocated_stack;
6721
6722         if (off < min_valid_off || off > -1)
6723                 return -EACCES;
6724         return 0;
6725 }
6726
6727 /* Check that the stack access at 'regno + off' falls within the maximum stack
6728  * bounds.
6729  *
6730  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6731  */
6732 static int check_stack_access_within_bounds(
6733                 struct bpf_verifier_env *env,
6734                 int regno, int off, int access_size,
6735                 enum bpf_access_src src, enum bpf_access_type type)
6736 {
6737         struct bpf_reg_state *regs = cur_regs(env);
6738         struct bpf_reg_state *reg = regs + regno;
6739         struct bpf_func_state *state = func(env, reg);
6740         int min_off, max_off;
6741         int err;
6742         char *err_extra;
6743
6744         if (src == ACCESS_HELPER)
6745                 /* We don't know if helpers are reading or writing (or both). */
6746                 err_extra = " indirect access to";
6747         else if (type == BPF_READ)
6748                 err_extra = " read from";
6749         else
6750                 err_extra = " write to";
6751
6752         if (tnum_is_const(reg->var_off)) {
6753                 min_off = reg->var_off.value + off;
6754                 if (access_size > 0)
6755                         max_off = min_off + access_size - 1;
6756                 else
6757                         max_off = min_off;
6758         } else {
6759                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6760                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6761                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6762                                 err_extra, regno);
6763                         return -EACCES;
6764                 }
6765                 min_off = reg->smin_value + off;
6766                 if (access_size > 0)
6767                         max_off = reg->smax_value + off + access_size - 1;
6768                 else
6769                         max_off = min_off;
6770         }
6771
6772         err = check_stack_slot_within_bounds(min_off, state, type);
6773         if (!err)
6774                 err = check_stack_slot_within_bounds(max_off, state, type);
6775
6776         if (err) {
6777                 if (tnum_is_const(reg->var_off)) {
6778                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6779                                 err_extra, regno, off, access_size);
6780                 } else {
6781                         char tn_buf[48];
6782
6783                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6784                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6785                                 err_extra, regno, tn_buf, access_size);
6786                 }
6787         }
6788         return err;
6789 }
6790
6791 /* check whether memory at (regno + off) is accessible for t = (read | write)
6792  * if t==write, value_regno is a register which value is stored into memory
6793  * if t==read, value_regno is a register which will receive the value from memory
6794  * if t==write && value_regno==-1, some unknown value is stored into memory
6795  * if t==read && value_regno==-1, don't care what we read from memory
6796  */
6797 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6798                             int off, int bpf_size, enum bpf_access_type t,
6799                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6800 {
6801         struct bpf_reg_state *regs = cur_regs(env);
6802         struct bpf_reg_state *reg = regs + regno;
6803         struct bpf_func_state *state;
6804         int size, err = 0;
6805
6806         size = bpf_size_to_bytes(bpf_size);
6807         if (size < 0)
6808                 return size;
6809
6810         /* alignment checks will add in reg->off themselves */
6811         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6812         if (err)
6813                 return err;
6814
6815         /* for access checks, reg->off is just part of off */
6816         off += reg->off;
6817
6818         if (reg->type == PTR_TO_MAP_KEY) {
6819                 if (t == BPF_WRITE) {
6820                         verbose(env, "write to change key R%d not allowed\n", regno);
6821                         return -EACCES;
6822                 }
6823
6824                 err = check_mem_region_access(env, regno, off, size,
6825                                               reg->map_ptr->key_size, false);
6826                 if (err)
6827                         return err;
6828                 if (value_regno >= 0)
6829                         mark_reg_unknown(env, regs, value_regno);
6830         } else if (reg->type == PTR_TO_MAP_VALUE) {
6831                 struct btf_field *kptr_field = NULL;
6832
6833                 if (t == BPF_WRITE && value_regno >= 0 &&
6834                     is_pointer_value(env, value_regno)) {
6835                         verbose(env, "R%d leaks addr into map\n", value_regno);
6836                         return -EACCES;
6837                 }
6838                 err = check_map_access_type(env, regno, off, size, t);
6839                 if (err)
6840                         return err;
6841                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6842                 if (err)
6843                         return err;
6844                 if (tnum_is_const(reg->var_off))
6845                         kptr_field = btf_record_find(reg->map_ptr->record,
6846                                                      off + reg->var_off.value, BPF_KPTR);
6847                 if (kptr_field) {
6848                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6849                 } else if (t == BPF_READ && value_regno >= 0) {
6850                         struct bpf_map *map = reg->map_ptr;
6851
6852                         /* if map is read-only, track its contents as scalars */
6853                         if (tnum_is_const(reg->var_off) &&
6854                             bpf_map_is_rdonly(map) &&
6855                             map->ops->map_direct_value_addr) {
6856                                 int map_off = off + reg->var_off.value;
6857                                 u64 val = 0;
6858
6859                                 err = bpf_map_direct_read(map, map_off, size,
6860                                                           &val, is_ldsx);
6861                                 if (err)
6862                                         return err;
6863
6864                                 regs[value_regno].type = SCALAR_VALUE;
6865                                 __mark_reg_known(&regs[value_regno], val);
6866                         } else {
6867                                 mark_reg_unknown(env, regs, value_regno);
6868                         }
6869                 }
6870         } else if (base_type(reg->type) == PTR_TO_MEM) {
6871                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6872
6873                 if (type_may_be_null(reg->type)) {
6874                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6875                                 reg_type_str(env, reg->type));
6876                         return -EACCES;
6877                 }
6878
6879                 if (t == BPF_WRITE && rdonly_mem) {
6880                         verbose(env, "R%d cannot write into %s\n",
6881                                 regno, reg_type_str(env, reg->type));
6882                         return -EACCES;
6883                 }
6884
6885                 if (t == BPF_WRITE && value_regno >= 0 &&
6886                     is_pointer_value(env, value_regno)) {
6887                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6888                         return -EACCES;
6889                 }
6890
6891                 err = check_mem_region_access(env, regno, off, size,
6892                                               reg->mem_size, false);
6893                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6894                         mark_reg_unknown(env, regs, value_regno);
6895         } else if (reg->type == PTR_TO_CTX) {
6896                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6897                 struct btf *btf = NULL;
6898                 u32 btf_id = 0;
6899
6900                 if (t == BPF_WRITE && value_regno >= 0 &&
6901                     is_pointer_value(env, value_regno)) {
6902                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6903                         return -EACCES;
6904                 }
6905
6906                 err = check_ptr_off_reg(env, reg, regno);
6907                 if (err < 0)
6908                         return err;
6909
6910                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6911                                        &btf_id);
6912                 if (err)
6913                         verbose_linfo(env, insn_idx, "; ");
6914                 if (!err && t == BPF_READ && value_regno >= 0) {
6915                         /* ctx access returns either a scalar, or a
6916                          * PTR_TO_PACKET[_META,_END]. In the latter
6917                          * case, we know the offset is zero.
6918                          */
6919                         if (reg_type == SCALAR_VALUE) {
6920                                 mark_reg_unknown(env, regs, value_regno);
6921                         } else {
6922                                 mark_reg_known_zero(env, regs,
6923                                                     value_regno);
6924                                 if (type_may_be_null(reg_type))
6925                                         regs[value_regno].id = ++env->id_gen;
6926                                 /* A load of ctx field could have different
6927                                  * actual load size with the one encoded in the
6928                                  * insn. When the dst is PTR, it is for sure not
6929                                  * a sub-register.
6930                                  */
6931                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6932                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6933                                         regs[value_regno].btf = btf;
6934                                         regs[value_regno].btf_id = btf_id;
6935                                 }
6936                         }
6937                         regs[value_regno].type = reg_type;
6938                 }
6939
6940         } else if (reg->type == PTR_TO_STACK) {
6941                 /* Basic bounds checks. */
6942                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6943                 if (err)
6944                         return err;
6945
6946                 state = func(env, reg);
6947                 err = update_stack_depth(env, state, off);
6948                 if (err)
6949                         return err;
6950
6951                 if (t == BPF_READ)
6952                         err = check_stack_read(env, regno, off, size,
6953                                                value_regno);
6954                 else
6955                         err = check_stack_write(env, regno, off, size,
6956                                                 value_regno, insn_idx);
6957         } else if (reg_is_pkt_pointer(reg)) {
6958                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6959                         verbose(env, "cannot write into packet\n");
6960                         return -EACCES;
6961                 }
6962                 if (t == BPF_WRITE && value_regno >= 0 &&
6963                     is_pointer_value(env, value_regno)) {
6964                         verbose(env, "R%d leaks addr into packet\n",
6965                                 value_regno);
6966                         return -EACCES;
6967                 }
6968                 err = check_packet_access(env, regno, off, size, false);
6969                 if (!err && t == BPF_READ && value_regno >= 0)
6970                         mark_reg_unknown(env, regs, value_regno);
6971         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6972                 if (t == BPF_WRITE && value_regno >= 0 &&
6973                     is_pointer_value(env, value_regno)) {
6974                         verbose(env, "R%d leaks addr into flow keys\n",
6975                                 value_regno);
6976                         return -EACCES;
6977                 }
6978
6979                 err = check_flow_keys_access(env, off, size);
6980                 if (!err && t == BPF_READ && value_regno >= 0)
6981                         mark_reg_unknown(env, regs, value_regno);
6982         } else if (type_is_sk_pointer(reg->type)) {
6983                 if (t == BPF_WRITE) {
6984                         verbose(env, "R%d cannot write into %s\n",
6985                                 regno, reg_type_str(env, reg->type));
6986                         return -EACCES;
6987                 }
6988                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6989                 if (!err && value_regno >= 0)
6990                         mark_reg_unknown(env, regs, value_regno);
6991         } else if (reg->type == PTR_TO_TP_BUFFER) {
6992                 err = check_tp_buffer_access(env, reg, regno, off, size);
6993                 if (!err && t == BPF_READ && value_regno >= 0)
6994                         mark_reg_unknown(env, regs, value_regno);
6995         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6996                    !type_may_be_null(reg->type)) {
6997                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6998                                               value_regno);
6999         } else if (reg->type == CONST_PTR_TO_MAP) {
7000                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
7001                                               value_regno);
7002         } else if (base_type(reg->type) == PTR_TO_BUF) {
7003                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
7004                 u32 *max_access;
7005
7006                 if (rdonly_mem) {
7007                         if (t == BPF_WRITE) {
7008                                 verbose(env, "R%d cannot write into %s\n",
7009                                         regno, reg_type_str(env, reg->type));
7010                                 return -EACCES;
7011                         }
7012                         max_access = &env->prog->aux->max_rdonly_access;
7013                 } else {
7014                         max_access = &env->prog->aux->max_rdwr_access;
7015                 }
7016
7017                 err = check_buffer_access(env, reg, regno, off, size, false,
7018                                           max_access);
7019
7020                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
7021                         mark_reg_unknown(env, regs, value_regno);
7022         } else {
7023                 verbose(env, "R%d invalid mem access '%s'\n", regno,
7024                         reg_type_str(env, reg->type));
7025                 return -EACCES;
7026         }
7027
7028         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
7029             regs[value_regno].type == SCALAR_VALUE) {
7030                 if (!is_ldsx)
7031                         /* b/h/w load zero-extends, mark upper bits as known 0 */
7032                         coerce_reg_to_size(&regs[value_regno], size);
7033                 else
7034                         coerce_reg_to_size_sx(&regs[value_regno], size);
7035         }
7036         return err;
7037 }
7038
7039 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
7040 {
7041         int load_reg;
7042         int err;
7043
7044         switch (insn->imm) {
7045         case BPF_ADD:
7046         case BPF_ADD | BPF_FETCH:
7047         case BPF_AND:
7048         case BPF_AND | BPF_FETCH:
7049         case BPF_OR:
7050         case BPF_OR | BPF_FETCH:
7051         case BPF_XOR:
7052         case BPF_XOR | BPF_FETCH:
7053         case BPF_XCHG:
7054         case BPF_CMPXCHG:
7055                 break;
7056         default:
7057                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
7058                 return -EINVAL;
7059         }
7060
7061         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
7062                 verbose(env, "invalid atomic operand size\n");
7063                 return -EINVAL;
7064         }
7065
7066         /* check src1 operand */
7067         err = check_reg_arg(env, insn->src_reg, SRC_OP);
7068         if (err)
7069                 return err;
7070
7071         /* check src2 operand */
7072         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
7073         if (err)
7074                 return err;
7075
7076         if (insn->imm == BPF_CMPXCHG) {
7077                 /* Check comparison of R0 with memory location */
7078                 const u32 aux_reg = BPF_REG_0;
7079
7080                 err = check_reg_arg(env, aux_reg, SRC_OP);
7081                 if (err)
7082                         return err;
7083
7084                 if (is_pointer_value(env, aux_reg)) {
7085                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
7086                         return -EACCES;
7087                 }
7088         }
7089
7090         if (is_pointer_value(env, insn->src_reg)) {
7091                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
7092                 return -EACCES;
7093         }
7094
7095         if (is_ctx_reg(env, insn->dst_reg) ||
7096             is_pkt_reg(env, insn->dst_reg) ||
7097             is_flow_key_reg(env, insn->dst_reg) ||
7098             is_sk_reg(env, insn->dst_reg)) {
7099                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
7100                         insn->dst_reg,
7101                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
7102                 return -EACCES;
7103         }
7104
7105         if (insn->imm & BPF_FETCH) {
7106                 if (insn->imm == BPF_CMPXCHG)
7107                         load_reg = BPF_REG_0;
7108                 else
7109                         load_reg = insn->src_reg;
7110
7111                 /* check and record load of old value */
7112                 err = check_reg_arg(env, load_reg, DST_OP);
7113                 if (err)
7114                         return err;
7115         } else {
7116                 /* This instruction accesses a memory location but doesn't
7117                  * actually load it into a register.
7118                  */
7119                 load_reg = -1;
7120         }
7121
7122         /* Check whether we can read the memory, with second call for fetch
7123          * case to simulate the register fill.
7124          */
7125         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7126                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
7127         if (!err && load_reg >= 0)
7128                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7129                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
7130                                        true, false);
7131         if (err)
7132                 return err;
7133
7134         /* Check whether we can write into the same memory. */
7135         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
7136                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
7137         if (err)
7138                 return err;
7139
7140         return 0;
7141 }
7142
7143 /* When register 'regno' is used to read the stack (either directly or through
7144  * a helper function) make sure that it's within stack boundary and, depending
7145  * on the access type, that all elements of the stack are initialized.
7146  *
7147  * 'off' includes 'regno->off', but not its dynamic part (if any).
7148  *
7149  * All registers that have been spilled on the stack in the slots within the
7150  * read offsets are marked as read.
7151  */
7152 static int check_stack_range_initialized(
7153                 struct bpf_verifier_env *env, int regno, int off,
7154                 int access_size, bool zero_size_allowed,
7155                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
7156 {
7157         struct bpf_reg_state *reg = reg_state(env, regno);
7158         struct bpf_func_state *state = func(env, reg);
7159         int err, min_off, max_off, i, j, slot, spi;
7160         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
7161         enum bpf_access_type bounds_check_type;
7162         /* Some accesses can write anything into the stack, others are
7163          * read-only.
7164          */
7165         bool clobber = false;
7166
7167         if (access_size == 0 && !zero_size_allowed) {
7168                 verbose(env, "invalid zero-sized read\n");
7169                 return -EACCES;
7170         }
7171
7172         if (type == ACCESS_HELPER) {
7173                 /* The bounds checks for writes are more permissive than for
7174                  * reads. However, if raw_mode is not set, we'll do extra
7175                  * checks below.
7176                  */
7177                 bounds_check_type = BPF_WRITE;
7178                 clobber = true;
7179         } else {
7180                 bounds_check_type = BPF_READ;
7181         }
7182         err = check_stack_access_within_bounds(env, regno, off, access_size,
7183                                                type, bounds_check_type);
7184         if (err)
7185                 return err;
7186
7187
7188         if (tnum_is_const(reg->var_off)) {
7189                 min_off = max_off = reg->var_off.value + off;
7190         } else {
7191                 /* Variable offset is prohibited for unprivileged mode for
7192                  * simplicity since it requires corresponding support in
7193                  * Spectre masking for stack ALU.
7194                  * See also retrieve_ptr_limit().
7195                  */
7196                 if (!env->bypass_spec_v1) {
7197                         char tn_buf[48];
7198
7199                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7200                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
7201                                 regno, err_extra, tn_buf);
7202                         return -EACCES;
7203                 }
7204                 /* Only initialized buffer on stack is allowed to be accessed
7205                  * with variable offset. With uninitialized buffer it's hard to
7206                  * guarantee that whole memory is marked as initialized on
7207                  * helper return since specific bounds are unknown what may
7208                  * cause uninitialized stack leaking.
7209                  */
7210                 if (meta && meta->raw_mode)
7211                         meta = NULL;
7212
7213                 min_off = reg->smin_value + off;
7214                 max_off = reg->smax_value + off;
7215         }
7216
7217         if (meta && meta->raw_mode) {
7218                 /* Ensure we won't be overwriting dynptrs when simulating byte
7219                  * by byte access in check_helper_call using meta.access_size.
7220                  * This would be a problem if we have a helper in the future
7221                  * which takes:
7222                  *
7223                  *      helper(uninit_mem, len, dynptr)
7224                  *
7225                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
7226                  * may end up writing to dynptr itself when touching memory from
7227                  * arg 1. This can be relaxed on a case by case basis for known
7228                  * safe cases, but reject due to the possibilitiy of aliasing by
7229                  * default.
7230                  */
7231                 for (i = min_off; i < max_off + access_size; i++) {
7232                         int stack_off = -i - 1;
7233
7234                         spi = __get_spi(i);
7235                         /* raw_mode may write past allocated_stack */
7236                         if (state->allocated_stack <= stack_off)
7237                                 continue;
7238                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
7239                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
7240                                 return -EACCES;
7241                         }
7242                 }
7243                 meta->access_size = access_size;
7244                 meta->regno = regno;
7245                 return 0;
7246         }
7247
7248         for (i = min_off; i < max_off + access_size; i++) {
7249                 u8 *stype;
7250
7251                 slot = -i - 1;
7252                 spi = slot / BPF_REG_SIZE;
7253                 if (state->allocated_stack <= slot)
7254                         goto err;
7255                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
7256                 if (*stype == STACK_MISC)
7257                         goto mark;
7258                 if ((*stype == STACK_ZERO) ||
7259                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
7260                         if (clobber) {
7261                                 /* helper can write anything into the stack */
7262                                 *stype = STACK_MISC;
7263                         }
7264                         goto mark;
7265                 }
7266
7267                 if (is_spilled_reg(&state->stack[spi]) &&
7268                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
7269                      env->allow_ptr_leaks)) {
7270                         if (clobber) {
7271                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
7272                                 for (j = 0; j < BPF_REG_SIZE; j++)
7273                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
7274                         }
7275                         goto mark;
7276                 }
7277
7278 err:
7279                 if (tnum_is_const(reg->var_off)) {
7280                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
7281                                 err_extra, regno, min_off, i - min_off, access_size);
7282                 } else {
7283                         char tn_buf[48];
7284
7285                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
7286                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
7287                                 err_extra, regno, tn_buf, i - min_off, access_size);
7288                 }
7289                 return -EACCES;
7290 mark:
7291                 /* reading any byte out of 8-byte 'spill_slot' will cause
7292                  * the whole slot to be marked as 'read'
7293                  */
7294                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
7295                               state->stack[spi].spilled_ptr.parent,
7296                               REG_LIVE_READ64);
7297                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
7298                  * be sure that whether stack slot is written to or not. Hence,
7299                  * we must still conservatively propagate reads upwards even if
7300                  * helper may write to the entire memory range.
7301                  */
7302         }
7303         return update_stack_depth(env, state, min_off);
7304 }
7305
7306 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
7307                                    int access_size, bool zero_size_allowed,
7308                                    struct bpf_call_arg_meta *meta)
7309 {
7310         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7311         u32 *max_access;
7312
7313         switch (base_type(reg->type)) {
7314         case PTR_TO_PACKET:
7315         case PTR_TO_PACKET_META:
7316                 return check_packet_access(env, regno, reg->off, access_size,
7317                                            zero_size_allowed);
7318         case PTR_TO_MAP_KEY:
7319                 if (meta && meta->raw_mode) {
7320                         verbose(env, "R%d cannot write into %s\n", regno,
7321                                 reg_type_str(env, reg->type));
7322                         return -EACCES;
7323                 }
7324                 return check_mem_region_access(env, regno, reg->off, access_size,
7325                                                reg->map_ptr->key_size, false);
7326         case PTR_TO_MAP_VALUE:
7327                 if (check_map_access_type(env, regno, reg->off, access_size,
7328                                           meta && meta->raw_mode ? BPF_WRITE :
7329                                           BPF_READ))
7330                         return -EACCES;
7331                 return check_map_access(env, regno, reg->off, access_size,
7332                                         zero_size_allowed, ACCESS_HELPER);
7333         case PTR_TO_MEM:
7334                 if (type_is_rdonly_mem(reg->type)) {
7335                         if (meta && meta->raw_mode) {
7336                                 verbose(env, "R%d cannot write into %s\n", regno,
7337                                         reg_type_str(env, reg->type));
7338                                 return -EACCES;
7339                         }
7340                 }
7341                 return check_mem_region_access(env, regno, reg->off,
7342                                                access_size, reg->mem_size,
7343                                                zero_size_allowed);
7344         case PTR_TO_BUF:
7345                 if (type_is_rdonly_mem(reg->type)) {
7346                         if (meta && meta->raw_mode) {
7347                                 verbose(env, "R%d cannot write into %s\n", regno,
7348                                         reg_type_str(env, reg->type));
7349                                 return -EACCES;
7350                         }
7351
7352                         max_access = &env->prog->aux->max_rdonly_access;
7353                 } else {
7354                         max_access = &env->prog->aux->max_rdwr_access;
7355                 }
7356                 return check_buffer_access(env, reg, regno, reg->off,
7357                                            access_size, zero_size_allowed,
7358                                            max_access);
7359         case PTR_TO_STACK:
7360                 return check_stack_range_initialized(
7361                                 env,
7362                                 regno, reg->off, access_size,
7363                                 zero_size_allowed, ACCESS_HELPER, meta);
7364         case PTR_TO_BTF_ID:
7365                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7366                                                access_size, BPF_READ, -1);
7367         case PTR_TO_CTX:
7368                 /* in case the function doesn't know how to access the context,
7369                  * (because we are in a program of type SYSCALL for example), we
7370                  * can not statically check its size.
7371                  * Dynamically check it now.
7372                  */
7373                 if (!env->ops->convert_ctx_access) {
7374                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7375                         int offset = access_size - 1;
7376
7377                         /* Allow zero-byte read from PTR_TO_CTX */
7378                         if (access_size == 0)
7379                                 return zero_size_allowed ? 0 : -EACCES;
7380
7381                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7382                                                 atype, -1, false, false);
7383                 }
7384
7385                 fallthrough;
7386         default: /* scalar_value or invalid ptr */
7387                 /* Allow zero-byte read from NULL, regardless of pointer type */
7388                 if (zero_size_allowed && access_size == 0 &&
7389                     register_is_null(reg))
7390                         return 0;
7391
7392                 verbose(env, "R%d type=%s ", regno,
7393                         reg_type_str(env, reg->type));
7394                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7395                 return -EACCES;
7396         }
7397 }
7398
7399 static int check_mem_size_reg(struct bpf_verifier_env *env,
7400                               struct bpf_reg_state *reg, u32 regno,
7401                               bool zero_size_allowed,
7402                               struct bpf_call_arg_meta *meta)
7403 {
7404         int err;
7405
7406         /* This is used to refine r0 return value bounds for helpers
7407          * that enforce this value as an upper bound on return values.
7408          * See do_refine_retval_range() for helpers that can refine
7409          * the return value. C type of helper is u32 so we pull register
7410          * bound from umax_value however, if negative verifier errors
7411          * out. Only upper bounds can be learned because retval is an
7412          * int type and negative retvals are allowed.
7413          */
7414         meta->msize_max_value = reg->umax_value;
7415
7416         /* The register is SCALAR_VALUE; the access check
7417          * happens using its boundaries.
7418          */
7419         if (!tnum_is_const(reg->var_off))
7420                 /* For unprivileged variable accesses, disable raw
7421                  * mode so that the program is required to
7422                  * initialize all the memory that the helper could
7423                  * just partially fill up.
7424                  */
7425                 meta = NULL;
7426
7427         if (reg->smin_value < 0) {
7428                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7429                         regno);
7430                 return -EACCES;
7431         }
7432
7433         if (reg->umin_value == 0) {
7434                 err = check_helper_mem_access(env, regno - 1, 0,
7435                                               zero_size_allowed,
7436                                               meta);
7437                 if (err)
7438                         return err;
7439         }
7440
7441         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7442                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7443                         regno);
7444                 return -EACCES;
7445         }
7446         err = check_helper_mem_access(env, regno - 1,
7447                                       reg->umax_value,
7448                                       zero_size_allowed, meta);
7449         if (!err)
7450                 err = mark_chain_precision(env, regno);
7451         return err;
7452 }
7453
7454 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7455                    u32 regno, u32 mem_size)
7456 {
7457         bool may_be_null = type_may_be_null(reg->type);
7458         struct bpf_reg_state saved_reg;
7459         struct bpf_call_arg_meta meta;
7460         int err;
7461
7462         if (register_is_null(reg))
7463                 return 0;
7464
7465         memset(&meta, 0, sizeof(meta));
7466         /* Assuming that the register contains a value check if the memory
7467          * access is safe. Temporarily save and restore the register's state as
7468          * the conversion shouldn't be visible to a caller.
7469          */
7470         if (may_be_null) {
7471                 saved_reg = *reg;
7472                 mark_ptr_not_null_reg(reg);
7473         }
7474
7475         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7476         /* Check access for BPF_WRITE */
7477         meta.raw_mode = true;
7478         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7479
7480         if (may_be_null)
7481                 *reg = saved_reg;
7482
7483         return err;
7484 }
7485
7486 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7487                                     u32 regno)
7488 {
7489         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7490         bool may_be_null = type_may_be_null(mem_reg->type);
7491         struct bpf_reg_state saved_reg;
7492         struct bpf_call_arg_meta meta;
7493         int err;
7494
7495         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7496
7497         memset(&meta, 0, sizeof(meta));
7498
7499         if (may_be_null) {
7500                 saved_reg = *mem_reg;
7501                 mark_ptr_not_null_reg(mem_reg);
7502         }
7503
7504         err = check_mem_size_reg(env, reg, regno, true, &meta);
7505         /* Check access for BPF_WRITE */
7506         meta.raw_mode = true;
7507         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7508
7509         if (may_be_null)
7510                 *mem_reg = saved_reg;
7511         return err;
7512 }
7513
7514 /* Implementation details:
7515  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7516  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7517  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7518  * Two separate bpf_obj_new will also have different reg->id.
7519  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7520  * clears reg->id after value_or_null->value transition, since the verifier only
7521  * cares about the range of access to valid map value pointer and doesn't care
7522  * about actual address of the map element.
7523  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7524  * reg->id > 0 after value_or_null->value transition. By doing so
7525  * two bpf_map_lookups will be considered two different pointers that
7526  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7527  * returned from bpf_obj_new.
7528  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7529  * dead-locks.
7530  * Since only one bpf_spin_lock is allowed the checks are simpler than
7531  * reg_is_refcounted() logic. The verifier needs to remember only
7532  * one spin_lock instead of array of acquired_refs.
7533  * cur_state->active_lock remembers which map value element or allocated
7534  * object got locked and clears it after bpf_spin_unlock.
7535  */
7536 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7537                              bool is_lock)
7538 {
7539         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7540         struct bpf_verifier_state *cur = env->cur_state;
7541         bool is_const = tnum_is_const(reg->var_off);
7542         u64 val = reg->var_off.value;
7543         struct bpf_map *map = NULL;
7544         struct btf *btf = NULL;
7545         struct btf_record *rec;
7546
7547         if (!is_const) {
7548                 verbose(env,
7549                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7550                         regno);
7551                 return -EINVAL;
7552         }
7553         if (reg->type == PTR_TO_MAP_VALUE) {
7554                 map = reg->map_ptr;
7555                 if (!map->btf) {
7556                         verbose(env,
7557                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7558                                 map->name);
7559                         return -EINVAL;
7560                 }
7561         } else {
7562                 btf = reg->btf;
7563         }
7564
7565         rec = reg_btf_record(reg);
7566         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7567                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7568                         map ? map->name : "kptr");
7569                 return -EINVAL;
7570         }
7571         if (rec->spin_lock_off != val + reg->off) {
7572                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7573                         val + reg->off, rec->spin_lock_off);
7574                 return -EINVAL;
7575         }
7576         if (is_lock) {
7577                 if (cur->active_lock.ptr) {
7578                         verbose(env,
7579                                 "Locking two bpf_spin_locks are not allowed\n");
7580                         return -EINVAL;
7581                 }
7582                 if (map)
7583                         cur->active_lock.ptr = map;
7584                 else
7585                         cur->active_lock.ptr = btf;
7586                 cur->active_lock.id = reg->id;
7587         } else {
7588                 void *ptr;
7589
7590                 if (map)
7591                         ptr = map;
7592                 else
7593                         ptr = btf;
7594
7595                 if (!cur->active_lock.ptr) {
7596                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7597                         return -EINVAL;
7598                 }
7599                 if (cur->active_lock.ptr != ptr ||
7600                     cur->active_lock.id != reg->id) {
7601                         verbose(env, "bpf_spin_unlock of different lock\n");
7602                         return -EINVAL;
7603                 }
7604
7605                 invalidate_non_owning_refs(env);
7606
7607                 cur->active_lock.ptr = NULL;
7608                 cur->active_lock.id = 0;
7609         }
7610         return 0;
7611 }
7612
7613 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7614                               struct bpf_call_arg_meta *meta)
7615 {
7616         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7617         bool is_const = tnum_is_const(reg->var_off);
7618         struct bpf_map *map = reg->map_ptr;
7619         u64 val = reg->var_off.value;
7620
7621         if (!is_const) {
7622                 verbose(env,
7623                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7624                         regno);
7625                 return -EINVAL;
7626         }
7627         if (!map->btf) {
7628                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7629                         map->name);
7630                 return -EINVAL;
7631         }
7632         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7633                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7634                 return -EINVAL;
7635         }
7636         if (map->record->timer_off != val + reg->off) {
7637                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7638                         val + reg->off, map->record->timer_off);
7639                 return -EINVAL;
7640         }
7641         if (meta->map_ptr) {
7642                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7643                 return -EFAULT;
7644         }
7645         meta->map_uid = reg->map_uid;
7646         meta->map_ptr = map;
7647         return 0;
7648 }
7649
7650 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7651                              struct bpf_call_arg_meta *meta)
7652 {
7653         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7654         struct bpf_map *map_ptr = reg->map_ptr;
7655         struct btf_field *kptr_field;
7656         u32 kptr_off;
7657
7658         if (!tnum_is_const(reg->var_off)) {
7659                 verbose(env,
7660                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7661                         regno);
7662                 return -EINVAL;
7663         }
7664         if (!map_ptr->btf) {
7665                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7666                         map_ptr->name);
7667                 return -EINVAL;
7668         }
7669         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7670                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7671                 return -EINVAL;
7672         }
7673
7674         meta->map_ptr = map_ptr;
7675         kptr_off = reg->off + reg->var_off.value;
7676         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7677         if (!kptr_field) {
7678                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7679                 return -EACCES;
7680         }
7681         if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) {
7682                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7683                 return -EACCES;
7684         }
7685         meta->kptr_field = kptr_field;
7686         return 0;
7687 }
7688
7689 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7690  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7691  *
7692  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7693  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7694  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7695  *
7696  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7697  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7698  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7699  * mutate the view of the dynptr and also possibly destroy it. In the latter
7700  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7701  * memory that dynptr points to.
7702  *
7703  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7704  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7705  * readonly dynptr view yet, hence only the first case is tracked and checked.
7706  *
7707  * This is consistent with how C applies the const modifier to a struct object,
7708  * where the pointer itself inside bpf_dynptr becomes const but not what it
7709  * points to.
7710  *
7711  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7712  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7713  */
7714 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7715                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7716 {
7717         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7718         int err;
7719
7720         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7721          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7722          */
7723         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7724                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7725                 return -EFAULT;
7726         }
7727
7728         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7729          *               constructing a mutable bpf_dynptr object.
7730          *
7731          *               Currently, this is only possible with PTR_TO_STACK
7732          *               pointing to a region of at least 16 bytes which doesn't
7733          *               contain an existing bpf_dynptr.
7734          *
7735          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7736          *               mutated or destroyed. However, the memory it points to
7737          *               may be mutated.
7738          *
7739          *  None       - Points to a initialized dynptr that can be mutated and
7740          *               destroyed, including mutation of the memory it points
7741          *               to.
7742          */
7743         if (arg_type & MEM_UNINIT) {
7744                 int i;
7745
7746                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7747                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7748                         return -EINVAL;
7749                 }
7750
7751                 /* we write BPF_DW bits (8 bytes) at a time */
7752                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7753                         err = check_mem_access(env, insn_idx, regno,
7754                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7755                         if (err)
7756                                 return err;
7757                 }
7758
7759                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7760         } else /* MEM_RDONLY and None case from above */ {
7761                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7762                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7763                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7764                         return -EINVAL;
7765                 }
7766
7767                 if (!is_dynptr_reg_valid_init(env, reg)) {
7768                         verbose(env,
7769                                 "Expected an initialized dynptr as arg #%d\n",
7770                                 regno);
7771                         return -EINVAL;
7772                 }
7773
7774                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7775                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7776                         verbose(env,
7777                                 "Expected a dynptr of type %s as arg #%d\n",
7778                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7779                         return -EINVAL;
7780                 }
7781
7782                 err = mark_dynptr_read(env, reg);
7783         }
7784         return err;
7785 }
7786
7787 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7788 {
7789         struct bpf_func_state *state = func(env, reg);
7790
7791         return state->stack[spi].spilled_ptr.ref_obj_id;
7792 }
7793
7794 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7795 {
7796         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7797 }
7798
7799 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7800 {
7801         return meta->kfunc_flags & KF_ITER_NEW;
7802 }
7803
7804 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7805 {
7806         return meta->kfunc_flags & KF_ITER_NEXT;
7807 }
7808
7809 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7810 {
7811         return meta->kfunc_flags & KF_ITER_DESTROY;
7812 }
7813
7814 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7815 {
7816         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7817          * kfunc is iter state pointer
7818          */
7819         return arg == 0 && is_iter_kfunc(meta);
7820 }
7821
7822 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7823                             struct bpf_kfunc_call_arg_meta *meta)
7824 {
7825         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7826         const struct btf_type *t;
7827         const struct btf_param *arg;
7828         int spi, err, i, nr_slots;
7829         u32 btf_id;
7830
7831         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7832         arg = &btf_params(meta->func_proto)[0];
7833         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7834         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7835         nr_slots = t->size / BPF_REG_SIZE;
7836
7837         if (is_iter_new_kfunc(meta)) {
7838                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7839                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7840                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7841                                 iter_type_str(meta->btf, btf_id), regno);
7842                         return -EINVAL;
7843                 }
7844
7845                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7846                         err = check_mem_access(env, insn_idx, regno,
7847                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7848                         if (err)
7849                                 return err;
7850                 }
7851
7852                 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots);
7853                 if (err)
7854                         return err;
7855         } else {
7856                 /* iter_next() or iter_destroy() expect initialized iter state*/
7857                 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots);
7858                 switch (err) {
7859                 case 0:
7860                         break;
7861                 case -EINVAL:
7862                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7863                                 iter_type_str(meta->btf, btf_id), regno);
7864                         return err;
7865                 case -EPROTO:
7866                         verbose(env, "expected an RCU CS when using %s\n", meta->func_name);
7867                         return err;
7868                 default:
7869                         return err;
7870                 }
7871
7872                 spi = iter_get_spi(env, reg, nr_slots);
7873                 if (spi < 0)
7874                         return spi;
7875
7876                 err = mark_iter_read(env, reg, spi, nr_slots);
7877                 if (err)
7878                         return err;
7879
7880                 /* remember meta->iter info for process_iter_next_call() */
7881                 meta->iter.spi = spi;
7882                 meta->iter.frameno = reg->frameno;
7883                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7884
7885                 if (is_iter_destroy_kfunc(meta)) {
7886                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7887                         if (err)
7888                                 return err;
7889                 }
7890         }
7891
7892         return 0;
7893 }
7894
7895 /* Look for a previous loop entry at insn_idx: nearest parent state
7896  * stopped at insn_idx with callsites matching those in cur->frame.
7897  */
7898 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env,
7899                                                   struct bpf_verifier_state *cur,
7900                                                   int insn_idx)
7901 {
7902         struct bpf_verifier_state_list *sl;
7903         struct bpf_verifier_state *st;
7904
7905         /* Explored states are pushed in stack order, most recent states come first */
7906         sl = *explored_state(env, insn_idx);
7907         for (; sl; sl = sl->next) {
7908                 /* If st->branches != 0 state is a part of current DFS verification path,
7909                  * hence cur & st for a loop.
7910                  */
7911                 st = &sl->state;
7912                 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) &&
7913                     st->dfs_depth < cur->dfs_depth)
7914                         return st;
7915         }
7916
7917         return NULL;
7918 }
7919
7920 static void reset_idmap_scratch(struct bpf_verifier_env *env);
7921 static bool regs_exact(const struct bpf_reg_state *rold,
7922                        const struct bpf_reg_state *rcur,
7923                        struct bpf_idmap *idmap);
7924
7925 static void maybe_widen_reg(struct bpf_verifier_env *env,
7926                             struct bpf_reg_state *rold, struct bpf_reg_state *rcur,
7927                             struct bpf_idmap *idmap)
7928 {
7929         if (rold->type != SCALAR_VALUE)
7930                 return;
7931         if (rold->type != rcur->type)
7932                 return;
7933         if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap))
7934                 return;
7935         __mark_reg_unknown(env, rcur);
7936 }
7937
7938 static int widen_imprecise_scalars(struct bpf_verifier_env *env,
7939                                    struct bpf_verifier_state *old,
7940                                    struct bpf_verifier_state *cur)
7941 {
7942         struct bpf_func_state *fold, *fcur;
7943         int i, fr;
7944
7945         reset_idmap_scratch(env);
7946         for (fr = old->curframe; fr >= 0; fr--) {
7947                 fold = old->frame[fr];
7948                 fcur = cur->frame[fr];
7949
7950                 for (i = 0; i < MAX_BPF_REG; i++)
7951                         maybe_widen_reg(env,
7952                                         &fold->regs[i],
7953                                         &fcur->regs[i],
7954                                         &env->idmap_scratch);
7955
7956                 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) {
7957                         if (!is_spilled_reg(&fold->stack[i]) ||
7958                             !is_spilled_reg(&fcur->stack[i]))
7959                                 continue;
7960
7961                         maybe_widen_reg(env,
7962                                         &fold->stack[i].spilled_ptr,
7963                                         &fcur->stack[i].spilled_ptr,
7964                                         &env->idmap_scratch);
7965                 }
7966         }
7967         return 0;
7968 }
7969
7970 /* process_iter_next_call() is called when verifier gets to iterator's next
7971  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7972  * to it as just "iter_next()" in comments below.
7973  *
7974  * BPF verifier relies on a crucial contract for any iter_next()
7975  * implementation: it should *eventually* return NULL, and once that happens
7976  * it should keep returning NULL. That is, once iterator exhausts elements to
7977  * iterate, it should never reset or spuriously return new elements.
7978  *
7979  * With the assumption of such contract, process_iter_next_call() simulates
7980  * a fork in the verifier state to validate loop logic correctness and safety
7981  * without having to simulate infinite amount of iterations.
7982  *
7983  * In current state, we first assume that iter_next() returned NULL and
7984  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7985  * conditions we should not form an infinite loop and should eventually reach
7986  * exit.
7987  *
7988  * Besides that, we also fork current state and enqueue it for later
7989  * verification. In a forked state we keep iterator state as ACTIVE
7990  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7991  * also bump iteration depth to prevent erroneous infinite loop detection
7992  * later on (see iter_active_depths_differ() comment for details). In this
7993  * state we assume that we'll eventually loop back to another iter_next()
7994  * calls (it could be in exactly same location or in some other instruction,
7995  * it doesn't matter, we don't make any unnecessary assumptions about this,
7996  * everything revolves around iterator state in a stack slot, not which
7997  * instruction is calling iter_next()). When that happens, we either will come
7998  * to iter_next() with equivalent state and can conclude that next iteration
7999  * will proceed in exactly the same way as we just verified, so it's safe to
8000  * assume that loop converges. If not, we'll go on another iteration
8001  * simulation with a different input state, until all possible starting states
8002  * are validated or we reach maximum number of instructions limit.
8003  *
8004  * This way, we will either exhaustively discover all possible input states
8005  * that iterator loop can start with and eventually will converge, or we'll
8006  * effectively regress into bounded loop simulation logic and either reach
8007  * maximum number of instructions if loop is not provably convergent, or there
8008  * is some statically known limit on number of iterations (e.g., if there is
8009  * an explicit `if n > 100 then break;` statement somewhere in the loop).
8010  *
8011  * Iteration convergence logic in is_state_visited() relies on exact
8012  * states comparison, which ignores read and precision marks.
8013  * This is necessary because read and precision marks are not finalized
8014  * while in the loop. Exact comparison might preclude convergence for
8015  * simple programs like below:
8016  *
8017  *     i = 0;
8018  *     while(iter_next(&it))
8019  *       i++;
8020  *
8021  * At each iteration step i++ would produce a new distinct state and
8022  * eventually instruction processing limit would be reached.
8023  *
8024  * To avoid such behavior speculatively forget (widen) range for
8025  * imprecise scalar registers, if those registers were not precise at the
8026  * end of the previous iteration and do not match exactly.
8027  *
8028  * This is a conservative heuristic that allows to verify wide range of programs,
8029  * however it precludes verification of programs that conjure an
8030  * imprecise value on the first loop iteration and use it as precise on a second.
8031  * For example, the following safe program would fail to verify:
8032  *
8033  *     struct bpf_num_iter it;
8034  *     int arr[10];
8035  *     int i = 0, a = 0;
8036  *     bpf_iter_num_new(&it, 0, 10);
8037  *     while (bpf_iter_num_next(&it)) {
8038  *       if (a == 0) {
8039  *         a = 1;
8040  *         i = 7; // Because i changed verifier would forget
8041  *                // it's range on second loop entry.
8042  *       } else {
8043  *         arr[i] = 42; // This would fail to verify.
8044  *       }
8045  *     }
8046  *     bpf_iter_num_destroy(&it);
8047  */
8048 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
8049                                   struct bpf_kfunc_call_arg_meta *meta)
8050 {
8051         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st;
8052         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
8053         struct bpf_reg_state *cur_iter, *queued_iter;
8054         int iter_frameno = meta->iter.frameno;
8055         int iter_spi = meta->iter.spi;
8056
8057         BTF_TYPE_EMIT(struct bpf_iter);
8058
8059         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8060
8061         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
8062             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
8063                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
8064                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
8065                 return -EFAULT;
8066         }
8067
8068         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
8069                 /* Because iter_next() call is a checkpoint is_state_visitied()
8070                  * should guarantee parent state with same call sites and insn_idx.
8071                  */
8072                 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx ||
8073                     !same_callsites(cur_st->parent, cur_st)) {
8074                         verbose(env, "bug: bad parent state for iter next call");
8075                         return -EFAULT;
8076                 }
8077                 /* Note cur_st->parent in the call below, it is necessary to skip
8078                  * checkpoint created for cur_st by is_state_visited()
8079                  * right at this instruction.
8080                  */
8081                 prev_st = find_prev_entry(env, cur_st->parent, insn_idx);
8082                 /* branch out active iter state */
8083                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
8084                 if (!queued_st)
8085                         return -ENOMEM;
8086
8087                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
8088                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
8089                 queued_iter->iter.depth++;
8090                 if (prev_st)
8091                         widen_imprecise_scalars(env, prev_st, queued_st);
8092
8093                 queued_fr = queued_st->frame[queued_st->curframe];
8094                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
8095         }
8096
8097         /* switch to DRAINED state, but keep the depth unchanged */
8098         /* mark current iter state as drained and assume returned NULL */
8099         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
8100         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
8101
8102         return 0;
8103 }
8104
8105 static bool arg_type_is_mem_size(enum bpf_arg_type type)
8106 {
8107         return type == ARG_CONST_SIZE ||
8108                type == ARG_CONST_SIZE_OR_ZERO;
8109 }
8110
8111 static bool arg_type_is_release(enum bpf_arg_type type)
8112 {
8113         return type & OBJ_RELEASE;
8114 }
8115
8116 static bool arg_type_is_dynptr(enum bpf_arg_type type)
8117 {
8118         return base_type(type) == ARG_PTR_TO_DYNPTR;
8119 }
8120
8121 static int int_ptr_type_to_size(enum bpf_arg_type type)
8122 {
8123         if (type == ARG_PTR_TO_INT)
8124                 return sizeof(u32);
8125         else if (type == ARG_PTR_TO_LONG)
8126                 return sizeof(u64);
8127
8128         return -EINVAL;
8129 }
8130
8131 static int resolve_map_arg_type(struct bpf_verifier_env *env,
8132                                  const struct bpf_call_arg_meta *meta,
8133                                  enum bpf_arg_type *arg_type)
8134 {
8135         if (!meta->map_ptr) {
8136                 /* kernel subsystem misconfigured verifier */
8137                 verbose(env, "invalid map_ptr to access map->type\n");
8138                 return -EACCES;
8139         }
8140
8141         switch (meta->map_ptr->map_type) {
8142         case BPF_MAP_TYPE_SOCKMAP:
8143         case BPF_MAP_TYPE_SOCKHASH:
8144                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
8145                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
8146                 } else {
8147                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
8148                         return -EINVAL;
8149                 }
8150                 break;
8151         case BPF_MAP_TYPE_BLOOM_FILTER:
8152                 if (meta->func_id == BPF_FUNC_map_peek_elem)
8153                         *arg_type = ARG_PTR_TO_MAP_VALUE;
8154                 break;
8155         default:
8156                 break;
8157         }
8158         return 0;
8159 }
8160
8161 struct bpf_reg_types {
8162         const enum bpf_reg_type types[10];
8163         u32 *btf_id;
8164 };
8165
8166 static const struct bpf_reg_types sock_types = {
8167         .types = {
8168                 PTR_TO_SOCK_COMMON,
8169                 PTR_TO_SOCKET,
8170                 PTR_TO_TCP_SOCK,
8171                 PTR_TO_XDP_SOCK,
8172         },
8173 };
8174
8175 #ifdef CONFIG_NET
8176 static const struct bpf_reg_types btf_id_sock_common_types = {
8177         .types = {
8178                 PTR_TO_SOCK_COMMON,
8179                 PTR_TO_SOCKET,
8180                 PTR_TO_TCP_SOCK,
8181                 PTR_TO_XDP_SOCK,
8182                 PTR_TO_BTF_ID,
8183                 PTR_TO_BTF_ID | PTR_TRUSTED,
8184         },
8185         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
8186 };
8187 #endif
8188
8189 static const struct bpf_reg_types mem_types = {
8190         .types = {
8191                 PTR_TO_STACK,
8192                 PTR_TO_PACKET,
8193                 PTR_TO_PACKET_META,
8194                 PTR_TO_MAP_KEY,
8195                 PTR_TO_MAP_VALUE,
8196                 PTR_TO_MEM,
8197                 PTR_TO_MEM | MEM_RINGBUF,
8198                 PTR_TO_BUF,
8199                 PTR_TO_BTF_ID | PTR_TRUSTED,
8200         },
8201 };
8202
8203 static const struct bpf_reg_types int_ptr_types = {
8204         .types = {
8205                 PTR_TO_STACK,
8206                 PTR_TO_PACKET,
8207                 PTR_TO_PACKET_META,
8208                 PTR_TO_MAP_KEY,
8209                 PTR_TO_MAP_VALUE,
8210         },
8211 };
8212
8213 static const struct bpf_reg_types spin_lock_types = {
8214         .types = {
8215                 PTR_TO_MAP_VALUE,
8216                 PTR_TO_BTF_ID | MEM_ALLOC,
8217         }
8218 };
8219
8220 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
8221 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
8222 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
8223 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
8224 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
8225 static const struct bpf_reg_types btf_ptr_types = {
8226         .types = {
8227                 PTR_TO_BTF_ID,
8228                 PTR_TO_BTF_ID | PTR_TRUSTED,
8229                 PTR_TO_BTF_ID | MEM_RCU,
8230         },
8231 };
8232 static const struct bpf_reg_types percpu_btf_ptr_types = {
8233         .types = {
8234                 PTR_TO_BTF_ID | MEM_PERCPU,
8235                 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU,
8236                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
8237         }
8238 };
8239 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
8240 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
8241 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
8242 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
8243 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
8244 static const struct bpf_reg_types dynptr_types = {
8245         .types = {
8246                 PTR_TO_STACK,
8247                 CONST_PTR_TO_DYNPTR,
8248         }
8249 };
8250
8251 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
8252         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
8253         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
8254         [ARG_CONST_SIZE]                = &scalar_types,
8255         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
8256         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
8257         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
8258         [ARG_PTR_TO_CTX]                = &context_types,
8259         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
8260 #ifdef CONFIG_NET
8261         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
8262 #endif
8263         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
8264         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
8265         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
8266         [ARG_PTR_TO_MEM]                = &mem_types,
8267         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
8268         [ARG_PTR_TO_INT]                = &int_ptr_types,
8269         [ARG_PTR_TO_LONG]               = &int_ptr_types,
8270         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
8271         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
8272         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
8273         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
8274         [ARG_PTR_TO_TIMER]              = &timer_types,
8275         [ARG_PTR_TO_KPTR]               = &kptr_types,
8276         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
8277 };
8278
8279 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
8280                           enum bpf_arg_type arg_type,
8281                           const u32 *arg_btf_id,
8282                           struct bpf_call_arg_meta *meta)
8283 {
8284         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8285         enum bpf_reg_type expected, type = reg->type;
8286         const struct bpf_reg_types *compatible;
8287         int i, j;
8288
8289         compatible = compatible_reg_types[base_type(arg_type)];
8290         if (!compatible) {
8291                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
8292                 return -EFAULT;
8293         }
8294
8295         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
8296          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
8297          *
8298          * Same for MAYBE_NULL:
8299          *
8300          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
8301          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
8302          *
8303          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
8304          *
8305          * Therefore we fold these flags depending on the arg_type before comparison.
8306          */
8307         if (arg_type & MEM_RDONLY)
8308                 type &= ~MEM_RDONLY;
8309         if (arg_type & PTR_MAYBE_NULL)
8310                 type &= ~PTR_MAYBE_NULL;
8311         if (base_type(arg_type) == ARG_PTR_TO_MEM)
8312                 type &= ~DYNPTR_TYPE_FLAG_MASK;
8313
8314         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) {
8315                 type &= ~MEM_ALLOC;
8316                 type &= ~MEM_PERCPU;
8317         }
8318
8319         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
8320                 expected = compatible->types[i];
8321                 if (expected == NOT_INIT)
8322                         break;
8323
8324                 if (type == expected)
8325                         goto found;
8326         }
8327
8328         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
8329         for (j = 0; j + 1 < i; j++)
8330                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
8331         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
8332         return -EACCES;
8333
8334 found:
8335         if (base_type(reg->type) != PTR_TO_BTF_ID)
8336                 return 0;
8337
8338         if (compatible == &mem_types) {
8339                 if (!(arg_type & MEM_RDONLY)) {
8340                         verbose(env,
8341                                 "%s() may write into memory pointed by R%d type=%s\n",
8342                                 func_id_name(meta->func_id),
8343                                 regno, reg_type_str(env, reg->type));
8344                         return -EACCES;
8345                 }
8346                 return 0;
8347         }
8348
8349         switch ((int)reg->type) {
8350         case PTR_TO_BTF_ID:
8351         case PTR_TO_BTF_ID | PTR_TRUSTED:
8352         case PTR_TO_BTF_ID | MEM_RCU:
8353         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
8354         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
8355         {
8356                 /* For bpf_sk_release, it needs to match against first member
8357                  * 'struct sock_common', hence make an exception for it. This
8358                  * allows bpf_sk_release to work for multiple socket types.
8359                  */
8360                 bool strict_type_match = arg_type_is_release(arg_type) &&
8361                                          meta->func_id != BPF_FUNC_sk_release;
8362
8363                 if (type_may_be_null(reg->type) &&
8364                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
8365                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
8366                         return -EACCES;
8367                 }
8368
8369                 if (!arg_btf_id) {
8370                         if (!compatible->btf_id) {
8371                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
8372                                 return -EFAULT;
8373                         }
8374                         arg_btf_id = compatible->btf_id;
8375                 }
8376
8377                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8378                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8379                                 return -EACCES;
8380                 } else {
8381                         if (arg_btf_id == BPF_PTR_POISON) {
8382                                 verbose(env, "verifier internal error:");
8383                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
8384                                         regno);
8385                                 return -EACCES;
8386                         }
8387
8388                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
8389                                                   btf_vmlinux, *arg_btf_id,
8390                                                   strict_type_match)) {
8391                                 verbose(env, "R%d is of type %s but %s is expected\n",
8392                                         regno, btf_type_name(reg->btf, reg->btf_id),
8393                                         btf_type_name(btf_vmlinux, *arg_btf_id));
8394                                 return -EACCES;
8395                         }
8396                 }
8397                 break;
8398         }
8399         case PTR_TO_BTF_ID | MEM_ALLOC:
8400         case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC:
8401                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
8402                     meta->func_id != BPF_FUNC_kptr_xchg) {
8403                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
8404                         return -EFAULT;
8405                 }
8406                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
8407                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
8408                                 return -EACCES;
8409                 }
8410                 break;
8411         case PTR_TO_BTF_ID | MEM_PERCPU:
8412         case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU:
8413         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
8414                 /* Handled by helper specific checks */
8415                 break;
8416         default:
8417                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
8418                 return -EFAULT;
8419         }
8420         return 0;
8421 }
8422
8423 static struct btf_field *
8424 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
8425 {
8426         struct btf_field *field;
8427         struct btf_record *rec;
8428
8429         rec = reg_btf_record(reg);
8430         if (!rec)
8431                 return NULL;
8432
8433         field = btf_record_find(rec, off, fields);
8434         if (!field)
8435                 return NULL;
8436
8437         return field;
8438 }
8439
8440 int check_func_arg_reg_off(struct bpf_verifier_env *env,
8441                            const struct bpf_reg_state *reg, int regno,
8442                            enum bpf_arg_type arg_type)
8443 {
8444         u32 type = reg->type;
8445
8446         /* When referenced register is passed to release function, its fixed
8447          * offset must be 0.
8448          *
8449          * We will check arg_type_is_release reg has ref_obj_id when storing
8450          * meta->release_regno.
8451          */
8452         if (arg_type_is_release(arg_type)) {
8453                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
8454                  * may not directly point to the object being released, but to
8455                  * dynptr pointing to such object, which might be at some offset
8456                  * on the stack. In that case, we simply to fallback to the
8457                  * default handling.
8458                  */
8459                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
8460                         return 0;
8461
8462                 /* Doing check_ptr_off_reg check for the offset will catch this
8463                  * because fixed_off_ok is false, but checking here allows us
8464                  * to give the user a better error message.
8465                  */
8466                 if (reg->off) {
8467                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8468                                 regno);
8469                         return -EINVAL;
8470                 }
8471                 return __check_ptr_off_reg(env, reg, regno, false);
8472         }
8473
8474         switch (type) {
8475         /* Pointer types where both fixed and variable offset is explicitly allowed: */
8476         case PTR_TO_STACK:
8477         case PTR_TO_PACKET:
8478         case PTR_TO_PACKET_META:
8479         case PTR_TO_MAP_KEY:
8480         case PTR_TO_MAP_VALUE:
8481         case PTR_TO_MEM:
8482         case PTR_TO_MEM | MEM_RDONLY:
8483         case PTR_TO_MEM | MEM_RINGBUF:
8484         case PTR_TO_BUF:
8485         case PTR_TO_BUF | MEM_RDONLY:
8486         case SCALAR_VALUE:
8487                 return 0;
8488         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8489          * fixed offset.
8490          */
8491         case PTR_TO_BTF_ID:
8492         case PTR_TO_BTF_ID | MEM_ALLOC:
8493         case PTR_TO_BTF_ID | PTR_TRUSTED:
8494         case PTR_TO_BTF_ID | MEM_RCU:
8495         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8496         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8497                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8498                  * its fixed offset must be 0. In the other cases, fixed offset
8499                  * can be non-zero. This was already checked above. So pass
8500                  * fixed_off_ok as true to allow fixed offset for all other
8501                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8502                  * still need to do checks instead of returning.
8503                  */
8504                 return __check_ptr_off_reg(env, reg, regno, true);
8505         default:
8506                 return __check_ptr_off_reg(env, reg, regno, false);
8507         }
8508 }
8509
8510 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8511                                                 const struct bpf_func_proto *fn,
8512                                                 struct bpf_reg_state *regs)
8513 {
8514         struct bpf_reg_state *state = NULL;
8515         int i;
8516
8517         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8518                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8519                         if (state) {
8520                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8521                                 return NULL;
8522                         }
8523                         state = &regs[BPF_REG_1 + i];
8524                 }
8525
8526         if (!state)
8527                 verbose(env, "verifier internal error: no dynptr arg found\n");
8528
8529         return state;
8530 }
8531
8532 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8533 {
8534         struct bpf_func_state *state = func(env, reg);
8535         int spi;
8536
8537         if (reg->type == CONST_PTR_TO_DYNPTR)
8538                 return reg->id;
8539         spi = dynptr_get_spi(env, reg);
8540         if (spi < 0)
8541                 return spi;
8542         return state->stack[spi].spilled_ptr.id;
8543 }
8544
8545 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8546 {
8547         struct bpf_func_state *state = func(env, reg);
8548         int spi;
8549
8550         if (reg->type == CONST_PTR_TO_DYNPTR)
8551                 return reg->ref_obj_id;
8552         spi = dynptr_get_spi(env, reg);
8553         if (spi < 0)
8554                 return spi;
8555         return state->stack[spi].spilled_ptr.ref_obj_id;
8556 }
8557
8558 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8559                                             struct bpf_reg_state *reg)
8560 {
8561         struct bpf_func_state *state = func(env, reg);
8562         int spi;
8563
8564         if (reg->type == CONST_PTR_TO_DYNPTR)
8565                 return reg->dynptr.type;
8566
8567         spi = __get_spi(reg->off);
8568         if (spi < 0) {
8569                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8570                 return BPF_DYNPTR_TYPE_INVALID;
8571         }
8572
8573         return state->stack[spi].spilled_ptr.dynptr.type;
8574 }
8575
8576 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8577                           struct bpf_call_arg_meta *meta,
8578                           const struct bpf_func_proto *fn,
8579                           int insn_idx)
8580 {
8581         u32 regno = BPF_REG_1 + arg;
8582         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8583         enum bpf_arg_type arg_type = fn->arg_type[arg];
8584         enum bpf_reg_type type = reg->type;
8585         u32 *arg_btf_id = NULL;
8586         int err = 0;
8587
8588         if (arg_type == ARG_DONTCARE)
8589                 return 0;
8590
8591         err = check_reg_arg(env, regno, SRC_OP);
8592         if (err)
8593                 return err;
8594
8595         if (arg_type == ARG_ANYTHING) {
8596                 if (is_pointer_value(env, regno)) {
8597                         verbose(env, "R%d leaks addr into helper function\n",
8598                                 regno);
8599                         return -EACCES;
8600                 }
8601                 return 0;
8602         }
8603
8604         if (type_is_pkt_pointer(type) &&
8605             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8606                 verbose(env, "helper access to the packet is not allowed\n");
8607                 return -EACCES;
8608         }
8609
8610         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8611                 err = resolve_map_arg_type(env, meta, &arg_type);
8612                 if (err)
8613                         return err;
8614         }
8615
8616         if (register_is_null(reg) && type_may_be_null(arg_type))
8617                 /* A NULL register has a SCALAR_VALUE type, so skip
8618                  * type checking.
8619                  */
8620                 goto skip_type_check;
8621
8622         /* arg_btf_id and arg_size are in a union. */
8623         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8624             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8625                 arg_btf_id = fn->arg_btf_id[arg];
8626
8627         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8628         if (err)
8629                 return err;
8630
8631         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8632         if (err)
8633                 return err;
8634
8635 skip_type_check:
8636         if (arg_type_is_release(arg_type)) {
8637                 if (arg_type_is_dynptr(arg_type)) {
8638                         struct bpf_func_state *state = func(env, reg);
8639                         int spi;
8640
8641                         /* Only dynptr created on stack can be released, thus
8642                          * the get_spi and stack state checks for spilled_ptr
8643                          * should only be done before process_dynptr_func for
8644                          * PTR_TO_STACK.
8645                          */
8646                         if (reg->type == PTR_TO_STACK) {
8647                                 spi = dynptr_get_spi(env, reg);
8648                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8649                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8650                                         return -EINVAL;
8651                                 }
8652                         } else {
8653                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8654                                 return -EINVAL;
8655                         }
8656                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8657                         verbose(env, "R%d must be referenced when passed to release function\n",
8658                                 regno);
8659                         return -EINVAL;
8660                 }
8661                 if (meta->release_regno) {
8662                         verbose(env, "verifier internal error: more than one release argument\n");
8663                         return -EFAULT;
8664                 }
8665                 meta->release_regno = regno;
8666         }
8667
8668         if (reg->ref_obj_id) {
8669                 if (meta->ref_obj_id) {
8670                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8671                                 regno, reg->ref_obj_id,
8672                                 meta->ref_obj_id);
8673                         return -EFAULT;
8674                 }
8675                 meta->ref_obj_id = reg->ref_obj_id;
8676         }
8677
8678         switch (base_type(arg_type)) {
8679         case ARG_CONST_MAP_PTR:
8680                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8681                 if (meta->map_ptr) {
8682                         /* Use map_uid (which is unique id of inner map) to reject:
8683                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8684                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8685                          * if (inner_map1 && inner_map2) {
8686                          *     timer = bpf_map_lookup_elem(inner_map1);
8687                          *     if (timer)
8688                          *         // mismatch would have been allowed
8689                          *         bpf_timer_init(timer, inner_map2);
8690                          * }
8691                          *
8692                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8693                          */
8694                         if (meta->map_ptr != reg->map_ptr ||
8695                             meta->map_uid != reg->map_uid) {
8696                                 verbose(env,
8697                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8698                                         meta->map_uid, reg->map_uid);
8699                                 return -EINVAL;
8700                         }
8701                 }
8702                 meta->map_ptr = reg->map_ptr;
8703                 meta->map_uid = reg->map_uid;
8704                 break;
8705         case ARG_PTR_TO_MAP_KEY:
8706                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8707                  * check that [key, key + map->key_size) are within
8708                  * stack limits and initialized
8709                  */
8710                 if (!meta->map_ptr) {
8711                         /* in function declaration map_ptr must come before
8712                          * map_key, so that it's verified and known before
8713                          * we have to check map_key here. Otherwise it means
8714                          * that kernel subsystem misconfigured verifier
8715                          */
8716                         verbose(env, "invalid map_ptr to access map->key\n");
8717                         return -EACCES;
8718                 }
8719                 err = check_helper_mem_access(env, regno,
8720                                               meta->map_ptr->key_size, false,
8721                                               NULL);
8722                 break;
8723         case ARG_PTR_TO_MAP_VALUE:
8724                 if (type_may_be_null(arg_type) && register_is_null(reg))
8725                         return 0;
8726
8727                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8728                  * check [value, value + map->value_size) validity
8729                  */
8730                 if (!meta->map_ptr) {
8731                         /* kernel subsystem misconfigured verifier */
8732                         verbose(env, "invalid map_ptr to access map->value\n");
8733                         return -EACCES;
8734                 }
8735                 meta->raw_mode = arg_type & MEM_UNINIT;
8736                 err = check_helper_mem_access(env, regno,
8737                                               meta->map_ptr->value_size, false,
8738                                               meta);
8739                 break;
8740         case ARG_PTR_TO_PERCPU_BTF_ID:
8741                 if (!reg->btf_id) {
8742                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8743                         return -EACCES;
8744                 }
8745                 meta->ret_btf = reg->btf;
8746                 meta->ret_btf_id = reg->btf_id;
8747                 break;
8748         case ARG_PTR_TO_SPIN_LOCK:
8749                 if (in_rbtree_lock_required_cb(env)) {
8750                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8751                         return -EACCES;
8752                 }
8753                 if (meta->func_id == BPF_FUNC_spin_lock) {
8754                         err = process_spin_lock(env, regno, true);
8755                         if (err)
8756                                 return err;
8757                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8758                         err = process_spin_lock(env, regno, false);
8759                         if (err)
8760                                 return err;
8761                 } else {
8762                         verbose(env, "verifier internal error\n");
8763                         return -EFAULT;
8764                 }
8765                 break;
8766         case ARG_PTR_TO_TIMER:
8767                 err = process_timer_func(env, regno, meta);
8768                 if (err)
8769                         return err;
8770                 break;
8771         case ARG_PTR_TO_FUNC:
8772                 meta->subprogno = reg->subprogno;
8773                 break;
8774         case ARG_PTR_TO_MEM:
8775                 /* The access to this pointer is only checked when we hit the
8776                  * next is_mem_size argument below.
8777                  */
8778                 meta->raw_mode = arg_type & MEM_UNINIT;
8779                 if (arg_type & MEM_FIXED_SIZE) {
8780                         err = check_helper_mem_access(env, regno,
8781                                                       fn->arg_size[arg], false,
8782                                                       meta);
8783                 }
8784                 break;
8785         case ARG_CONST_SIZE:
8786                 err = check_mem_size_reg(env, reg, regno, false, meta);
8787                 break;
8788         case ARG_CONST_SIZE_OR_ZERO:
8789                 err = check_mem_size_reg(env, reg, regno, true, meta);
8790                 break;
8791         case ARG_PTR_TO_DYNPTR:
8792                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8793                 if (err)
8794                         return err;
8795                 break;
8796         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8797                 if (!tnum_is_const(reg->var_off)) {
8798                         verbose(env, "R%d is not a known constant'\n",
8799                                 regno);
8800                         return -EACCES;
8801                 }
8802                 meta->mem_size = reg->var_off.value;
8803                 err = mark_chain_precision(env, regno);
8804                 if (err)
8805                         return err;
8806                 break;
8807         case ARG_PTR_TO_INT:
8808         case ARG_PTR_TO_LONG:
8809         {
8810                 int size = int_ptr_type_to_size(arg_type);
8811
8812                 err = check_helper_mem_access(env, regno, size, false, meta);
8813                 if (err)
8814                         return err;
8815                 err = check_ptr_alignment(env, reg, 0, size, true);
8816                 break;
8817         }
8818         case ARG_PTR_TO_CONST_STR:
8819         {
8820                 struct bpf_map *map = reg->map_ptr;
8821                 int map_off;
8822                 u64 map_addr;
8823                 char *str_ptr;
8824
8825                 if (!bpf_map_is_rdonly(map)) {
8826                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8827                         return -EACCES;
8828                 }
8829
8830                 if (!tnum_is_const(reg->var_off)) {
8831                         verbose(env, "R%d is not a constant address'\n", regno);
8832                         return -EACCES;
8833                 }
8834
8835                 if (!map->ops->map_direct_value_addr) {
8836                         verbose(env, "no direct value access support for this map type\n");
8837                         return -EACCES;
8838                 }
8839
8840                 err = check_map_access(env, regno, reg->off,
8841                                        map->value_size - reg->off, false,
8842                                        ACCESS_HELPER);
8843                 if (err)
8844                         return err;
8845
8846                 map_off = reg->off + reg->var_off.value;
8847                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8848                 if (err) {
8849                         verbose(env, "direct value access on string failed\n");
8850                         return err;
8851                 }
8852
8853                 str_ptr = (char *)(long)(map_addr);
8854                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8855                         verbose(env, "string is not zero-terminated\n");
8856                         return -EINVAL;
8857                 }
8858                 break;
8859         }
8860         case ARG_PTR_TO_KPTR:
8861                 err = process_kptr_func(env, regno, meta);
8862                 if (err)
8863                         return err;
8864                 break;
8865         }
8866
8867         return err;
8868 }
8869
8870 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8871 {
8872         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8873         enum bpf_prog_type type = resolve_prog_type(env->prog);
8874
8875         if (func_id != BPF_FUNC_map_update_elem)
8876                 return false;
8877
8878         /* It's not possible to get access to a locked struct sock in these
8879          * contexts, so updating is safe.
8880          */
8881         switch (type) {
8882         case BPF_PROG_TYPE_TRACING:
8883                 if (eatype == BPF_TRACE_ITER)
8884                         return true;
8885                 break;
8886         case BPF_PROG_TYPE_SOCKET_FILTER:
8887         case BPF_PROG_TYPE_SCHED_CLS:
8888         case BPF_PROG_TYPE_SCHED_ACT:
8889         case BPF_PROG_TYPE_XDP:
8890         case BPF_PROG_TYPE_SK_REUSEPORT:
8891         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8892         case BPF_PROG_TYPE_SK_LOOKUP:
8893                 return true;
8894         default:
8895                 break;
8896         }
8897
8898         verbose(env, "cannot update sockmap in this context\n");
8899         return false;
8900 }
8901
8902 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8903 {
8904         return env->prog->jit_requested &&
8905                bpf_jit_supports_subprog_tailcalls();
8906 }
8907
8908 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8909                                         struct bpf_map *map, int func_id)
8910 {
8911         if (!map)
8912                 return 0;
8913
8914         /* We need a two way check, first is from map perspective ... */
8915         switch (map->map_type) {
8916         case BPF_MAP_TYPE_PROG_ARRAY:
8917                 if (func_id != BPF_FUNC_tail_call)
8918                         goto error;
8919                 break;
8920         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8921                 if (func_id != BPF_FUNC_perf_event_read &&
8922                     func_id != BPF_FUNC_perf_event_output &&
8923                     func_id != BPF_FUNC_skb_output &&
8924                     func_id != BPF_FUNC_perf_event_read_value &&
8925                     func_id != BPF_FUNC_xdp_output)
8926                         goto error;
8927                 break;
8928         case BPF_MAP_TYPE_RINGBUF:
8929                 if (func_id != BPF_FUNC_ringbuf_output &&
8930                     func_id != BPF_FUNC_ringbuf_reserve &&
8931                     func_id != BPF_FUNC_ringbuf_query &&
8932                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8933                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8934                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8935                         goto error;
8936                 break;
8937         case BPF_MAP_TYPE_USER_RINGBUF:
8938                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8939                         goto error;
8940                 break;
8941         case BPF_MAP_TYPE_STACK_TRACE:
8942                 if (func_id != BPF_FUNC_get_stackid)
8943                         goto error;
8944                 break;
8945         case BPF_MAP_TYPE_CGROUP_ARRAY:
8946                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8947                     func_id != BPF_FUNC_current_task_under_cgroup)
8948                         goto error;
8949                 break;
8950         case BPF_MAP_TYPE_CGROUP_STORAGE:
8951         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8952                 if (func_id != BPF_FUNC_get_local_storage)
8953                         goto error;
8954                 break;
8955         case BPF_MAP_TYPE_DEVMAP:
8956         case BPF_MAP_TYPE_DEVMAP_HASH:
8957                 if (func_id != BPF_FUNC_redirect_map &&
8958                     func_id != BPF_FUNC_map_lookup_elem)
8959                         goto error;
8960                 break;
8961         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8962          * appear.
8963          */
8964         case BPF_MAP_TYPE_CPUMAP:
8965                 if (func_id != BPF_FUNC_redirect_map)
8966                         goto error;
8967                 break;
8968         case BPF_MAP_TYPE_XSKMAP:
8969                 if (func_id != BPF_FUNC_redirect_map &&
8970                     func_id != BPF_FUNC_map_lookup_elem)
8971                         goto error;
8972                 break;
8973         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8974         case BPF_MAP_TYPE_HASH_OF_MAPS:
8975                 if (func_id != BPF_FUNC_map_lookup_elem)
8976                         goto error;
8977                 break;
8978         case BPF_MAP_TYPE_SOCKMAP:
8979                 if (func_id != BPF_FUNC_sk_redirect_map &&
8980                     func_id != BPF_FUNC_sock_map_update &&
8981                     func_id != BPF_FUNC_map_delete_elem &&
8982                     func_id != BPF_FUNC_msg_redirect_map &&
8983                     func_id != BPF_FUNC_sk_select_reuseport &&
8984                     func_id != BPF_FUNC_map_lookup_elem &&
8985                     !may_update_sockmap(env, func_id))
8986                         goto error;
8987                 break;
8988         case BPF_MAP_TYPE_SOCKHASH:
8989                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8990                     func_id != BPF_FUNC_sock_hash_update &&
8991                     func_id != BPF_FUNC_map_delete_elem &&
8992                     func_id != BPF_FUNC_msg_redirect_hash &&
8993                     func_id != BPF_FUNC_sk_select_reuseport &&
8994                     func_id != BPF_FUNC_map_lookup_elem &&
8995                     !may_update_sockmap(env, func_id))
8996                         goto error;
8997                 break;
8998         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8999                 if (func_id != BPF_FUNC_sk_select_reuseport)
9000                         goto error;
9001                 break;
9002         case BPF_MAP_TYPE_QUEUE:
9003         case BPF_MAP_TYPE_STACK:
9004                 if (func_id != BPF_FUNC_map_peek_elem &&
9005                     func_id != BPF_FUNC_map_pop_elem &&
9006                     func_id != BPF_FUNC_map_push_elem)
9007                         goto error;
9008                 break;
9009         case BPF_MAP_TYPE_SK_STORAGE:
9010                 if (func_id != BPF_FUNC_sk_storage_get &&
9011                     func_id != BPF_FUNC_sk_storage_delete &&
9012                     func_id != BPF_FUNC_kptr_xchg)
9013                         goto error;
9014                 break;
9015         case BPF_MAP_TYPE_INODE_STORAGE:
9016                 if (func_id != BPF_FUNC_inode_storage_get &&
9017                     func_id != BPF_FUNC_inode_storage_delete &&
9018                     func_id != BPF_FUNC_kptr_xchg)
9019                         goto error;
9020                 break;
9021         case BPF_MAP_TYPE_TASK_STORAGE:
9022                 if (func_id != BPF_FUNC_task_storage_get &&
9023                     func_id != BPF_FUNC_task_storage_delete &&
9024                     func_id != BPF_FUNC_kptr_xchg)
9025                         goto error;
9026                 break;
9027         case BPF_MAP_TYPE_CGRP_STORAGE:
9028                 if (func_id != BPF_FUNC_cgrp_storage_get &&
9029                     func_id != BPF_FUNC_cgrp_storage_delete &&
9030                     func_id != BPF_FUNC_kptr_xchg)
9031                         goto error;
9032                 break;
9033         case BPF_MAP_TYPE_BLOOM_FILTER:
9034                 if (func_id != BPF_FUNC_map_peek_elem &&
9035                     func_id != BPF_FUNC_map_push_elem)
9036                         goto error;
9037                 break;
9038         default:
9039                 break;
9040         }
9041
9042         /* ... and second from the function itself. */
9043         switch (func_id) {
9044         case BPF_FUNC_tail_call:
9045                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
9046                         goto error;
9047                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
9048                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
9049                         return -EINVAL;
9050                 }
9051                 break;
9052         case BPF_FUNC_perf_event_read:
9053         case BPF_FUNC_perf_event_output:
9054         case BPF_FUNC_perf_event_read_value:
9055         case BPF_FUNC_skb_output:
9056         case BPF_FUNC_xdp_output:
9057                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
9058                         goto error;
9059                 break;
9060         case BPF_FUNC_ringbuf_output:
9061         case BPF_FUNC_ringbuf_reserve:
9062         case BPF_FUNC_ringbuf_query:
9063         case BPF_FUNC_ringbuf_reserve_dynptr:
9064         case BPF_FUNC_ringbuf_submit_dynptr:
9065         case BPF_FUNC_ringbuf_discard_dynptr:
9066                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
9067                         goto error;
9068                 break;
9069         case BPF_FUNC_user_ringbuf_drain:
9070                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
9071                         goto error;
9072                 break;
9073         case BPF_FUNC_get_stackid:
9074                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
9075                         goto error;
9076                 break;
9077         case BPF_FUNC_current_task_under_cgroup:
9078         case BPF_FUNC_skb_under_cgroup:
9079                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
9080                         goto error;
9081                 break;
9082         case BPF_FUNC_redirect_map:
9083                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
9084                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
9085                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
9086                     map->map_type != BPF_MAP_TYPE_XSKMAP)
9087                         goto error;
9088                 break;
9089         case BPF_FUNC_sk_redirect_map:
9090         case BPF_FUNC_msg_redirect_map:
9091         case BPF_FUNC_sock_map_update:
9092                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
9093                         goto error;
9094                 break;
9095         case BPF_FUNC_sk_redirect_hash:
9096         case BPF_FUNC_msg_redirect_hash:
9097         case BPF_FUNC_sock_hash_update:
9098                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
9099                         goto error;
9100                 break;
9101         case BPF_FUNC_get_local_storage:
9102                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
9103                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
9104                         goto error;
9105                 break;
9106         case BPF_FUNC_sk_select_reuseport:
9107                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
9108                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
9109                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
9110                         goto error;
9111                 break;
9112         case BPF_FUNC_map_pop_elem:
9113                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9114                     map->map_type != BPF_MAP_TYPE_STACK)
9115                         goto error;
9116                 break;
9117         case BPF_FUNC_map_peek_elem:
9118         case BPF_FUNC_map_push_elem:
9119                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
9120                     map->map_type != BPF_MAP_TYPE_STACK &&
9121                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
9122                         goto error;
9123                 break;
9124         case BPF_FUNC_map_lookup_percpu_elem:
9125                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
9126                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
9127                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
9128                         goto error;
9129                 break;
9130         case BPF_FUNC_sk_storage_get:
9131         case BPF_FUNC_sk_storage_delete:
9132                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
9133                         goto error;
9134                 break;
9135         case BPF_FUNC_inode_storage_get:
9136         case BPF_FUNC_inode_storage_delete:
9137                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
9138                         goto error;
9139                 break;
9140         case BPF_FUNC_task_storage_get:
9141         case BPF_FUNC_task_storage_delete:
9142                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
9143                         goto error;
9144                 break;
9145         case BPF_FUNC_cgrp_storage_get:
9146         case BPF_FUNC_cgrp_storage_delete:
9147                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
9148                         goto error;
9149                 break;
9150         default:
9151                 break;
9152         }
9153
9154         return 0;
9155 error:
9156         verbose(env, "cannot pass map_type %d into func %s#%d\n",
9157                 map->map_type, func_id_name(func_id), func_id);
9158         return -EINVAL;
9159 }
9160
9161 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
9162 {
9163         int count = 0;
9164
9165         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
9166                 count++;
9167         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
9168                 count++;
9169         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
9170                 count++;
9171         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
9172                 count++;
9173         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
9174                 count++;
9175
9176         /* We only support one arg being in raw mode at the moment,
9177          * which is sufficient for the helper functions we have
9178          * right now.
9179          */
9180         return count <= 1;
9181 }
9182
9183 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
9184 {
9185         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
9186         bool has_size = fn->arg_size[arg] != 0;
9187         bool is_next_size = false;
9188
9189         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
9190                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
9191
9192         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
9193                 return is_next_size;
9194
9195         return has_size == is_next_size || is_next_size == is_fixed;
9196 }
9197
9198 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
9199 {
9200         /* bpf_xxx(..., buf, len) call will access 'len'
9201          * bytes from memory 'buf'. Both arg types need
9202          * to be paired, so make sure there's no buggy
9203          * helper function specification.
9204          */
9205         if (arg_type_is_mem_size(fn->arg1_type) ||
9206             check_args_pair_invalid(fn, 0) ||
9207             check_args_pair_invalid(fn, 1) ||
9208             check_args_pair_invalid(fn, 2) ||
9209             check_args_pair_invalid(fn, 3) ||
9210             check_args_pair_invalid(fn, 4))
9211                 return false;
9212
9213         return true;
9214 }
9215
9216 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
9217 {
9218         int i;
9219
9220         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
9221                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
9222                         return !!fn->arg_btf_id[i];
9223                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
9224                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
9225                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
9226                     /* arg_btf_id and arg_size are in a union. */
9227                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
9228                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
9229                         return false;
9230         }
9231
9232         return true;
9233 }
9234
9235 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
9236 {
9237         return check_raw_mode_ok(fn) &&
9238                check_arg_pair_ok(fn) &&
9239                check_btf_id_ok(fn) ? 0 : -EINVAL;
9240 }
9241
9242 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
9243  * are now invalid, so turn them into unknown SCALAR_VALUE.
9244  *
9245  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
9246  * since these slices point to packet data.
9247  */
9248 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
9249 {
9250         struct bpf_func_state *state;
9251         struct bpf_reg_state *reg;
9252
9253         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9254                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
9255                         mark_reg_invalid(env, reg);
9256         }));
9257 }
9258
9259 enum {
9260         AT_PKT_END = -1,
9261         BEYOND_PKT_END = -2,
9262 };
9263
9264 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
9265 {
9266         struct bpf_func_state *state = vstate->frame[vstate->curframe];
9267         struct bpf_reg_state *reg = &state->regs[regn];
9268
9269         if (reg->type != PTR_TO_PACKET)
9270                 /* PTR_TO_PACKET_META is not supported yet */
9271                 return;
9272
9273         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
9274          * How far beyond pkt_end it goes is unknown.
9275          * if (!range_open) it's the case of pkt >= pkt_end
9276          * if (range_open) it's the case of pkt > pkt_end
9277          * hence this pointer is at least 1 byte bigger than pkt_end
9278          */
9279         if (range_open)
9280                 reg->range = BEYOND_PKT_END;
9281         else
9282                 reg->range = AT_PKT_END;
9283 }
9284
9285 /* The pointer with the specified id has released its reference to kernel
9286  * resources. Identify all copies of the same pointer and clear the reference.
9287  */
9288 static int release_reference(struct bpf_verifier_env *env,
9289                              int ref_obj_id)
9290 {
9291         struct bpf_func_state *state;
9292         struct bpf_reg_state *reg;
9293         int err;
9294
9295         err = release_reference_state(cur_func(env), ref_obj_id);
9296         if (err)
9297                 return err;
9298
9299         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
9300                 if (reg->ref_obj_id == ref_obj_id)
9301                         mark_reg_invalid(env, reg);
9302         }));
9303
9304         return 0;
9305 }
9306
9307 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
9308 {
9309         struct bpf_func_state *unused;
9310         struct bpf_reg_state *reg;
9311
9312         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
9313                 if (type_is_non_owning_ref(reg->type))
9314                         mark_reg_invalid(env, reg);
9315         }));
9316 }
9317
9318 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
9319                                     struct bpf_reg_state *regs)
9320 {
9321         int i;
9322
9323         /* after the call registers r0 - r5 were scratched */
9324         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9325                 mark_reg_not_init(env, regs, caller_saved[i]);
9326                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9327         }
9328 }
9329
9330 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
9331                                    struct bpf_func_state *caller,
9332                                    struct bpf_func_state *callee,
9333                                    int insn_idx);
9334
9335 static int set_callee_state(struct bpf_verifier_env *env,
9336                             struct bpf_func_state *caller,
9337                             struct bpf_func_state *callee, int insn_idx);
9338
9339 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9340                              int *insn_idx, int subprog,
9341                              set_callee_state_fn set_callee_state_cb)
9342 {
9343         struct bpf_verifier_state *state = env->cur_state;
9344         struct bpf_func_state *caller, *callee;
9345         int err;
9346
9347         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
9348                 verbose(env, "the call stack of %d frames is too deep\n",
9349                         state->curframe + 2);
9350                 return -E2BIG;
9351         }
9352
9353         caller = state->frame[state->curframe];
9354         if (state->frame[state->curframe + 1]) {
9355                 verbose(env, "verifier bug. Frame %d already allocated\n",
9356                         state->curframe + 1);
9357                 return -EFAULT;
9358         }
9359
9360         err = btf_check_subprog_call(env, subprog, caller->regs);
9361         if (err == -EFAULT)
9362                 return err;
9363         if (subprog_is_global(env, subprog)) {
9364                 if (err) {
9365                         verbose(env, "Caller passes invalid args into func#%d\n",
9366                                 subprog);
9367                         return err;
9368                 } else {
9369                         if (env->log.level & BPF_LOG_LEVEL)
9370                                 verbose(env,
9371                                         "Func#%d is global and valid. Skipping.\n",
9372                                         subprog);
9373                         clear_caller_saved_regs(env, caller->regs);
9374
9375                         /* All global functions return a 64-bit SCALAR_VALUE */
9376                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
9377                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9378
9379                         /* continue with next insn after call */
9380                         return 0;
9381                 }
9382         }
9383
9384         /* set_callee_state is used for direct subprog calls, but we are
9385          * interested in validating only BPF helpers that can call subprogs as
9386          * callbacks
9387          */
9388         if (set_callee_state_cb != set_callee_state) {
9389                 env->subprog_info[subprog].is_cb = true;
9390                 if (bpf_pseudo_kfunc_call(insn) &&
9391                     !is_callback_calling_kfunc(insn->imm)) {
9392                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
9393                                 func_id_name(insn->imm), insn->imm);
9394                         return -EFAULT;
9395                 } else if (!bpf_pseudo_kfunc_call(insn) &&
9396                            !is_callback_calling_function(insn->imm)) { /* helper */
9397                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
9398                                 func_id_name(insn->imm), insn->imm);
9399                         return -EFAULT;
9400                 }
9401         }
9402
9403         if (insn->code == (BPF_JMP | BPF_CALL) &&
9404             insn->src_reg == 0 &&
9405             insn->imm == BPF_FUNC_timer_set_callback) {
9406                 struct bpf_verifier_state *async_cb;
9407
9408                 /* there is no real recursion here. timer callbacks are async */
9409                 env->subprog_info[subprog].is_async_cb = true;
9410                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
9411                                          *insn_idx, subprog);
9412                 if (!async_cb)
9413                         return -EFAULT;
9414                 callee = async_cb->frame[0];
9415                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
9416
9417                 /* Convert bpf_timer_set_callback() args into timer callback args */
9418                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
9419                 if (err)
9420                         return err;
9421
9422                 clear_caller_saved_regs(env, caller->regs);
9423                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
9424                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9425                 /* continue with next insn after call */
9426                 return 0;
9427         }
9428
9429         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
9430         if (!callee)
9431                 return -ENOMEM;
9432         state->frame[state->curframe + 1] = callee;
9433
9434         /* callee cannot access r0, r6 - r9 for reading and has to write
9435          * into its own stack before reading from it.
9436          * callee can read/write into caller's stack
9437          */
9438         init_func_state(env, callee,
9439                         /* remember the callsite, it will be used by bpf_exit */
9440                         *insn_idx /* callsite */,
9441                         state->curframe + 1 /* frameno within this callchain */,
9442                         subprog /* subprog number within this prog */);
9443
9444         /* Transfer references to the callee */
9445         err = copy_reference_state(callee, caller);
9446         if (err)
9447                 goto err_out;
9448
9449         err = set_callee_state_cb(env, caller, callee, *insn_idx);
9450         if (err)
9451                 goto err_out;
9452
9453         clear_caller_saved_regs(env, caller->regs);
9454
9455         /* only increment it after check_reg_arg() finished */
9456         state->curframe++;
9457
9458         /* and go analyze first insn of the callee */
9459         *insn_idx = env->subprog_info[subprog].start - 1;
9460
9461         if (env->log.level & BPF_LOG_LEVEL) {
9462                 verbose(env, "caller:\n");
9463                 print_verifier_state(env, caller, true);
9464                 verbose(env, "callee:\n");
9465                 print_verifier_state(env, callee, true);
9466         }
9467         return 0;
9468
9469 err_out:
9470         free_func_state(callee);
9471         state->frame[state->curframe + 1] = NULL;
9472         return err;
9473 }
9474
9475 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9476                                    struct bpf_func_state *caller,
9477                                    struct bpf_func_state *callee)
9478 {
9479         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9480          *      void *callback_ctx, u64 flags);
9481          * callback_fn(struct bpf_map *map, void *key, void *value,
9482          *      void *callback_ctx);
9483          */
9484         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9485
9486         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9487         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9488         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9489
9490         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9491         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9492         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9493
9494         /* pointer to stack or null */
9495         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9496
9497         /* unused */
9498         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9499         return 0;
9500 }
9501
9502 static int set_callee_state(struct bpf_verifier_env *env,
9503                             struct bpf_func_state *caller,
9504                             struct bpf_func_state *callee, int insn_idx)
9505 {
9506         int i;
9507
9508         /* copy r1 - r5 args that callee can access.  The copy includes parent
9509          * pointers, which connects us up to the liveness chain
9510          */
9511         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9512                 callee->regs[i] = caller->regs[i];
9513         return 0;
9514 }
9515
9516 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9517                            int *insn_idx)
9518 {
9519         int subprog, target_insn;
9520
9521         target_insn = *insn_idx + insn->imm + 1;
9522         subprog = find_subprog(env, target_insn);
9523         if (subprog < 0) {
9524                 verbose(env, "verifier bug. No program starts at insn %d\n",
9525                         target_insn);
9526                 return -EFAULT;
9527         }
9528
9529         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9530 }
9531
9532 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9533                                        struct bpf_func_state *caller,
9534                                        struct bpf_func_state *callee,
9535                                        int insn_idx)
9536 {
9537         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9538         struct bpf_map *map;
9539         int err;
9540
9541         if (bpf_map_ptr_poisoned(insn_aux)) {
9542                 verbose(env, "tail_call abusing map_ptr\n");
9543                 return -EINVAL;
9544         }
9545
9546         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9547         if (!map->ops->map_set_for_each_callback_args ||
9548             !map->ops->map_for_each_callback) {
9549                 verbose(env, "callback function not allowed for map\n");
9550                 return -ENOTSUPP;
9551         }
9552
9553         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9554         if (err)
9555                 return err;
9556
9557         callee->in_callback_fn = true;
9558         callee->callback_ret_range = tnum_range(0, 1);
9559         return 0;
9560 }
9561
9562 static int set_loop_callback_state(struct bpf_verifier_env *env,
9563                                    struct bpf_func_state *caller,
9564                                    struct bpf_func_state *callee,
9565                                    int insn_idx)
9566 {
9567         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9568          *          u64 flags);
9569          * callback_fn(u32 index, void *callback_ctx);
9570          */
9571         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9572         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9573
9574         /* unused */
9575         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9576         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9577         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9578
9579         callee->in_callback_fn = true;
9580         callee->callback_ret_range = tnum_range(0, 1);
9581         return 0;
9582 }
9583
9584 static int set_timer_callback_state(struct bpf_verifier_env *env,
9585                                     struct bpf_func_state *caller,
9586                                     struct bpf_func_state *callee,
9587                                     int insn_idx)
9588 {
9589         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9590
9591         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9592          * callback_fn(struct bpf_map *map, void *key, void *value);
9593          */
9594         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9595         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9596         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9597
9598         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9599         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9600         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9601
9602         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9603         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9604         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9605
9606         /* unused */
9607         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9608         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9609         callee->in_async_callback_fn = true;
9610         callee->callback_ret_range = tnum_range(0, 1);
9611         return 0;
9612 }
9613
9614 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9615                                        struct bpf_func_state *caller,
9616                                        struct bpf_func_state *callee,
9617                                        int insn_idx)
9618 {
9619         /* bpf_find_vma(struct task_struct *task, u64 addr,
9620          *               void *callback_fn, void *callback_ctx, u64 flags)
9621          * (callback_fn)(struct task_struct *task,
9622          *               struct vm_area_struct *vma, void *callback_ctx);
9623          */
9624         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9625
9626         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9627         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9628         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9629         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9630
9631         /* pointer to stack or null */
9632         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9633
9634         /* unused */
9635         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9636         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9637         callee->in_callback_fn = true;
9638         callee->callback_ret_range = tnum_range(0, 1);
9639         return 0;
9640 }
9641
9642 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9643                                            struct bpf_func_state *caller,
9644                                            struct bpf_func_state *callee,
9645                                            int insn_idx)
9646 {
9647         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9648          *                        callback_ctx, u64 flags);
9649          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9650          */
9651         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9652         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9653         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9654
9655         /* unused */
9656         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9657         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9658         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9659
9660         callee->in_callback_fn = true;
9661         callee->callback_ret_range = tnum_range(0, 1);
9662         return 0;
9663 }
9664
9665 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9666                                          struct bpf_func_state *caller,
9667                                          struct bpf_func_state *callee,
9668                                          int insn_idx)
9669 {
9670         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9671          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9672          *
9673          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9674          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9675          * by this point, so look at 'root'
9676          */
9677         struct btf_field *field;
9678
9679         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9680                                       BPF_RB_ROOT);
9681         if (!field || !field->graph_root.value_btf_id)
9682                 return -EFAULT;
9683
9684         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9685         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9686         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9687         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9688
9689         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9690         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9691         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9692         callee->in_callback_fn = true;
9693         callee->callback_ret_range = tnum_range(0, 1);
9694         return 0;
9695 }
9696
9697 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9698
9699 /* Are we currently verifying the callback for a rbtree helper that must
9700  * be called with lock held? If so, no need to complain about unreleased
9701  * lock
9702  */
9703 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9704 {
9705         struct bpf_verifier_state *state = env->cur_state;
9706         struct bpf_insn *insn = env->prog->insnsi;
9707         struct bpf_func_state *callee;
9708         int kfunc_btf_id;
9709
9710         if (!state->curframe)
9711                 return false;
9712
9713         callee = state->frame[state->curframe];
9714
9715         if (!callee->in_callback_fn)
9716                 return false;
9717
9718         kfunc_btf_id = insn[callee->callsite].imm;
9719         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9720 }
9721
9722 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9723 {
9724         struct bpf_verifier_state *state = env->cur_state;
9725         struct bpf_func_state *caller, *callee;
9726         struct bpf_reg_state *r0;
9727         int err;
9728
9729         callee = state->frame[state->curframe];
9730         r0 = &callee->regs[BPF_REG_0];
9731         if (r0->type == PTR_TO_STACK) {
9732                 /* technically it's ok to return caller's stack pointer
9733                  * (or caller's caller's pointer) back to the caller,
9734                  * since these pointers are valid. Only current stack
9735                  * pointer will be invalid as soon as function exits,
9736                  * but let's be conservative
9737                  */
9738                 verbose(env, "cannot return stack pointer to the caller\n");
9739                 return -EINVAL;
9740         }
9741
9742         caller = state->frame[state->curframe - 1];
9743         if (callee->in_callback_fn) {
9744                 /* enforce R0 return value range [0, 1]. */
9745                 struct tnum range = callee->callback_ret_range;
9746
9747                 if (r0->type != SCALAR_VALUE) {
9748                         verbose(env, "R0 not a scalar value\n");
9749                         return -EACCES;
9750                 }
9751                 if (!tnum_in(range, r0->var_off)) {
9752                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9753                         return -EINVAL;
9754                 }
9755         } else {
9756                 /* return to the caller whatever r0 had in the callee */
9757                 caller->regs[BPF_REG_0] = *r0;
9758         }
9759
9760         /* callback_fn frame should have released its own additions to parent's
9761          * reference state at this point, or check_reference_leak would
9762          * complain, hence it must be the same as the caller. There is no need
9763          * to copy it back.
9764          */
9765         if (!callee->in_callback_fn) {
9766                 /* Transfer references to the caller */
9767                 err = copy_reference_state(caller, callee);
9768                 if (err)
9769                         return err;
9770         }
9771
9772         *insn_idx = callee->callsite + 1;
9773         if (env->log.level & BPF_LOG_LEVEL) {
9774                 verbose(env, "returning from callee:\n");
9775                 print_verifier_state(env, callee, true);
9776                 verbose(env, "to caller at %d:\n", *insn_idx);
9777                 print_verifier_state(env, caller, true);
9778         }
9779         /* clear everything in the callee. In case of exceptional exits using
9780          * bpf_throw, this will be done by copy_verifier_state for extra frames. */
9781         free_func_state(callee);
9782         state->frame[state->curframe--] = NULL;
9783         return 0;
9784 }
9785
9786 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9787                                    int func_id,
9788                                    struct bpf_call_arg_meta *meta)
9789 {
9790         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9791
9792         if (ret_type != RET_INTEGER)
9793                 return;
9794
9795         switch (func_id) {
9796         case BPF_FUNC_get_stack:
9797         case BPF_FUNC_get_task_stack:
9798         case BPF_FUNC_probe_read_str:
9799         case BPF_FUNC_probe_read_kernel_str:
9800         case BPF_FUNC_probe_read_user_str:
9801                 ret_reg->smax_value = meta->msize_max_value;
9802                 ret_reg->s32_max_value = meta->msize_max_value;
9803                 ret_reg->smin_value = -MAX_ERRNO;
9804                 ret_reg->s32_min_value = -MAX_ERRNO;
9805                 reg_bounds_sync(ret_reg);
9806                 break;
9807         case BPF_FUNC_get_smp_processor_id:
9808                 ret_reg->umax_value = nr_cpu_ids - 1;
9809                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9810                 ret_reg->smax_value = nr_cpu_ids - 1;
9811                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9812                 ret_reg->umin_value = 0;
9813                 ret_reg->u32_min_value = 0;
9814                 ret_reg->smin_value = 0;
9815                 ret_reg->s32_min_value = 0;
9816                 reg_bounds_sync(ret_reg);
9817                 break;
9818         }
9819 }
9820
9821 static int
9822 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9823                 int func_id, int insn_idx)
9824 {
9825         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9826         struct bpf_map *map = meta->map_ptr;
9827
9828         if (func_id != BPF_FUNC_tail_call &&
9829             func_id != BPF_FUNC_map_lookup_elem &&
9830             func_id != BPF_FUNC_map_update_elem &&
9831             func_id != BPF_FUNC_map_delete_elem &&
9832             func_id != BPF_FUNC_map_push_elem &&
9833             func_id != BPF_FUNC_map_pop_elem &&
9834             func_id != BPF_FUNC_map_peek_elem &&
9835             func_id != BPF_FUNC_for_each_map_elem &&
9836             func_id != BPF_FUNC_redirect_map &&
9837             func_id != BPF_FUNC_map_lookup_percpu_elem)
9838                 return 0;
9839
9840         if (map == NULL) {
9841                 verbose(env, "kernel subsystem misconfigured verifier\n");
9842                 return -EINVAL;
9843         }
9844
9845         /* In case of read-only, some additional restrictions
9846          * need to be applied in order to prevent altering the
9847          * state of the map from program side.
9848          */
9849         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9850             (func_id == BPF_FUNC_map_delete_elem ||
9851              func_id == BPF_FUNC_map_update_elem ||
9852              func_id == BPF_FUNC_map_push_elem ||
9853              func_id == BPF_FUNC_map_pop_elem)) {
9854                 verbose(env, "write into map forbidden\n");
9855                 return -EACCES;
9856         }
9857
9858         if (!BPF_MAP_PTR(aux->map_ptr_state))
9859                 bpf_map_ptr_store(aux, meta->map_ptr,
9860                                   !meta->map_ptr->bypass_spec_v1);
9861         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9862                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9863                                   !meta->map_ptr->bypass_spec_v1);
9864         return 0;
9865 }
9866
9867 static int
9868 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9869                 int func_id, int insn_idx)
9870 {
9871         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9872         struct bpf_reg_state *regs = cur_regs(env), *reg;
9873         struct bpf_map *map = meta->map_ptr;
9874         u64 val, max;
9875         int err;
9876
9877         if (func_id != BPF_FUNC_tail_call)
9878                 return 0;
9879         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9880                 verbose(env, "kernel subsystem misconfigured verifier\n");
9881                 return -EINVAL;
9882         }
9883
9884         reg = &regs[BPF_REG_3];
9885         val = reg->var_off.value;
9886         max = map->max_entries;
9887
9888         if (!(register_is_const(reg) && val < max)) {
9889                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9890                 return 0;
9891         }
9892
9893         err = mark_chain_precision(env, BPF_REG_3);
9894         if (err)
9895                 return err;
9896         if (bpf_map_key_unseen(aux))
9897                 bpf_map_key_store(aux, val);
9898         else if (!bpf_map_key_poisoned(aux) &&
9899                   bpf_map_key_immediate(aux) != val)
9900                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9901         return 0;
9902 }
9903
9904 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
9905 {
9906         struct bpf_func_state *state = cur_func(env);
9907         bool refs_lingering = false;
9908         int i;
9909
9910         if (!exception_exit && state->frameno && !state->in_callback_fn)
9911                 return 0;
9912
9913         for (i = 0; i < state->acquired_refs; i++) {
9914                 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9915                         continue;
9916                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9917                         state->refs[i].id, state->refs[i].insn_idx);
9918                 refs_lingering = true;
9919         }
9920         return refs_lingering ? -EINVAL : 0;
9921 }
9922
9923 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9924                                    struct bpf_reg_state *regs)
9925 {
9926         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9927         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9928         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9929         struct bpf_bprintf_data data = {};
9930         int err, fmt_map_off, num_args;
9931         u64 fmt_addr;
9932         char *fmt;
9933
9934         /* data must be an array of u64 */
9935         if (data_len_reg->var_off.value % 8)
9936                 return -EINVAL;
9937         num_args = data_len_reg->var_off.value / 8;
9938
9939         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9940          * and map_direct_value_addr is set.
9941          */
9942         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9943         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9944                                                   fmt_map_off);
9945         if (err) {
9946                 verbose(env, "verifier bug\n");
9947                 return -EFAULT;
9948         }
9949         fmt = (char *)(long)fmt_addr + fmt_map_off;
9950
9951         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9952          * can focus on validating the format specifiers.
9953          */
9954         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9955         if (err < 0)
9956                 verbose(env, "Invalid format string\n");
9957
9958         return err;
9959 }
9960
9961 static int check_get_func_ip(struct bpf_verifier_env *env)
9962 {
9963         enum bpf_prog_type type = resolve_prog_type(env->prog);
9964         int func_id = BPF_FUNC_get_func_ip;
9965
9966         if (type == BPF_PROG_TYPE_TRACING) {
9967                 if (!bpf_prog_has_trampoline(env->prog)) {
9968                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9969                                 func_id_name(func_id), func_id);
9970                         return -ENOTSUPP;
9971                 }
9972                 return 0;
9973         } else if (type == BPF_PROG_TYPE_KPROBE) {
9974                 return 0;
9975         }
9976
9977         verbose(env, "func %s#%d not supported for program type %d\n",
9978                 func_id_name(func_id), func_id, type);
9979         return -ENOTSUPP;
9980 }
9981
9982 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9983 {
9984         return &env->insn_aux_data[env->insn_idx];
9985 }
9986
9987 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9988 {
9989         struct bpf_reg_state *regs = cur_regs(env);
9990         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9991         bool reg_is_null = register_is_null(reg);
9992
9993         if (reg_is_null)
9994                 mark_chain_precision(env, BPF_REG_4);
9995
9996         return reg_is_null;
9997 }
9998
9999 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
10000 {
10001         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
10002
10003         if (!state->initialized) {
10004                 state->initialized = 1;
10005                 state->fit_for_inline = loop_flag_is_zero(env);
10006                 state->callback_subprogno = subprogno;
10007                 return;
10008         }
10009
10010         if (!state->fit_for_inline)
10011                 return;
10012
10013         state->fit_for_inline = (loop_flag_is_zero(env) &&
10014                                  state->callback_subprogno == subprogno);
10015 }
10016
10017 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
10018                              int *insn_idx_p)
10019 {
10020         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
10021         bool returns_cpu_specific_alloc_ptr = false;
10022         const struct bpf_func_proto *fn = NULL;
10023         enum bpf_return_type ret_type;
10024         enum bpf_type_flag ret_flag;
10025         struct bpf_reg_state *regs;
10026         struct bpf_call_arg_meta meta;
10027         int insn_idx = *insn_idx_p;
10028         bool changes_data;
10029         int i, err, func_id;
10030
10031         /* find function prototype */
10032         func_id = insn->imm;
10033         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
10034                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
10035                         func_id);
10036                 return -EINVAL;
10037         }
10038
10039         if (env->ops->get_func_proto)
10040                 fn = env->ops->get_func_proto(func_id, env->prog);
10041         if (!fn) {
10042                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
10043                         func_id);
10044                 return -EINVAL;
10045         }
10046
10047         /* eBPF programs must be GPL compatible to use GPL-ed functions */
10048         if (!env->prog->gpl_compatible && fn->gpl_only) {
10049                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
10050                 return -EINVAL;
10051         }
10052
10053         if (fn->allowed && !fn->allowed(env->prog)) {
10054                 verbose(env, "helper call is not allowed in probe\n");
10055                 return -EINVAL;
10056         }
10057
10058         if (!env->prog->aux->sleepable && fn->might_sleep) {
10059                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
10060                 return -EINVAL;
10061         }
10062
10063         /* With LD_ABS/IND some JITs save/restore skb from r1. */
10064         changes_data = bpf_helper_changes_pkt_data(fn->func);
10065         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
10066                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
10067                         func_id_name(func_id), func_id);
10068                 return -EINVAL;
10069         }
10070
10071         memset(&meta, 0, sizeof(meta));
10072         meta.pkt_access = fn->pkt_access;
10073
10074         err = check_func_proto(fn, func_id);
10075         if (err) {
10076                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
10077                         func_id_name(func_id), func_id);
10078                 return err;
10079         }
10080
10081         if (env->cur_state->active_rcu_lock) {
10082                 if (fn->might_sleep) {
10083                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
10084                                 func_id_name(func_id), func_id);
10085                         return -EINVAL;
10086                 }
10087
10088                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
10089                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
10090         }
10091
10092         meta.func_id = func_id;
10093         /* check args */
10094         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
10095                 err = check_func_arg(env, i, &meta, fn, insn_idx);
10096                 if (err)
10097                         return err;
10098         }
10099
10100         err = record_func_map(env, &meta, func_id, insn_idx);
10101         if (err)
10102                 return err;
10103
10104         err = record_func_key(env, &meta, func_id, insn_idx);
10105         if (err)
10106                 return err;
10107
10108         /* Mark slots with STACK_MISC in case of raw mode, stack offset
10109          * is inferred from register state.
10110          */
10111         for (i = 0; i < meta.access_size; i++) {
10112                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
10113                                        BPF_WRITE, -1, false, false);
10114                 if (err)
10115                         return err;
10116         }
10117
10118         regs = cur_regs(env);
10119
10120         if (meta.release_regno) {
10121                 err = -EINVAL;
10122                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
10123                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
10124                  * is safe to do directly.
10125                  */
10126                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
10127                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
10128                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
10129                                 return -EFAULT;
10130                         }
10131                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
10132                 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
10133                         u32 ref_obj_id = meta.ref_obj_id;
10134                         bool in_rcu = in_rcu_cs(env);
10135                         struct bpf_func_state *state;
10136                         struct bpf_reg_state *reg;
10137
10138                         err = release_reference_state(cur_func(env), ref_obj_id);
10139                         if (!err) {
10140                                 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
10141                                         if (reg->ref_obj_id == ref_obj_id) {
10142                                                 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) {
10143                                                         reg->ref_obj_id = 0;
10144                                                         reg->type &= ~MEM_ALLOC;
10145                                                         reg->type |= MEM_RCU;
10146                                                 } else {
10147                                                         mark_reg_invalid(env, reg);
10148                                                 }
10149                                         }
10150                                 }));
10151                         }
10152                 } else if (meta.ref_obj_id) {
10153                         err = release_reference(env, meta.ref_obj_id);
10154                 } else if (register_is_null(&regs[meta.release_regno])) {
10155                         /* meta.ref_obj_id can only be 0 if register that is meant to be
10156                          * released is NULL, which must be > R0.
10157                          */
10158                         err = 0;
10159                 }
10160                 if (err) {
10161                         verbose(env, "func %s#%d reference has not been acquired before\n",
10162                                 func_id_name(func_id), func_id);
10163                         return err;
10164                 }
10165         }
10166
10167         switch (func_id) {
10168         case BPF_FUNC_tail_call:
10169                 err = check_reference_leak(env, false);
10170                 if (err) {
10171                         verbose(env, "tail_call would lead to reference leak\n");
10172                         return err;
10173                 }
10174                 break;
10175         case BPF_FUNC_get_local_storage:
10176                 /* check that flags argument in get_local_storage(map, flags) is 0,
10177                  * this is required because get_local_storage() can't return an error.
10178                  */
10179                 if (!register_is_null(&regs[BPF_REG_2])) {
10180                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
10181                         return -EINVAL;
10182                 }
10183                 break;
10184         case BPF_FUNC_for_each_map_elem:
10185                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10186                                         set_map_elem_callback_state);
10187                 break;
10188         case BPF_FUNC_timer_set_callback:
10189                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10190                                         set_timer_callback_state);
10191                 break;
10192         case BPF_FUNC_find_vma:
10193                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10194                                         set_find_vma_callback_state);
10195                 break;
10196         case BPF_FUNC_snprintf:
10197                 err = check_bpf_snprintf_call(env, regs);
10198                 break;
10199         case BPF_FUNC_loop:
10200                 update_loop_inline_state(env, meta.subprogno);
10201                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10202                                         set_loop_callback_state);
10203                 break;
10204         case BPF_FUNC_dynptr_from_mem:
10205                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
10206                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
10207                                 reg_type_str(env, regs[BPF_REG_1].type));
10208                         return -EACCES;
10209                 }
10210                 break;
10211         case BPF_FUNC_set_retval:
10212                 if (prog_type == BPF_PROG_TYPE_LSM &&
10213                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
10214                         if (!env->prog->aux->attach_func_proto->type) {
10215                                 /* Make sure programs that attach to void
10216                                  * hooks don't try to modify return value.
10217                                  */
10218                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
10219                                 return -EINVAL;
10220                         }
10221                 }
10222                 break;
10223         case BPF_FUNC_dynptr_data:
10224         {
10225                 struct bpf_reg_state *reg;
10226                 int id, ref_obj_id;
10227
10228                 reg = get_dynptr_arg_reg(env, fn, regs);
10229                 if (!reg)
10230                         return -EFAULT;
10231
10232
10233                 if (meta.dynptr_id) {
10234                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
10235                         return -EFAULT;
10236                 }
10237                 if (meta.ref_obj_id) {
10238                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
10239                         return -EFAULT;
10240                 }
10241
10242                 id = dynptr_id(env, reg);
10243                 if (id < 0) {
10244                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
10245                         return id;
10246                 }
10247
10248                 ref_obj_id = dynptr_ref_obj_id(env, reg);
10249                 if (ref_obj_id < 0) {
10250                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
10251                         return ref_obj_id;
10252                 }
10253
10254                 meta.dynptr_id = id;
10255                 meta.ref_obj_id = ref_obj_id;
10256
10257                 break;
10258         }
10259         case BPF_FUNC_dynptr_write:
10260         {
10261                 enum bpf_dynptr_type dynptr_type;
10262                 struct bpf_reg_state *reg;
10263
10264                 reg = get_dynptr_arg_reg(env, fn, regs);
10265                 if (!reg)
10266                         return -EFAULT;
10267
10268                 dynptr_type = dynptr_get_type(env, reg);
10269                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
10270                         return -EFAULT;
10271
10272                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
10273                         /* this will trigger clear_all_pkt_pointers(), which will
10274                          * invalidate all dynptr slices associated with the skb
10275                          */
10276                         changes_data = true;
10277
10278                 break;
10279         }
10280         case BPF_FUNC_per_cpu_ptr:
10281         case BPF_FUNC_this_cpu_ptr:
10282         {
10283                 struct bpf_reg_state *reg = &regs[BPF_REG_1];
10284                 const struct btf_type *type;
10285
10286                 if (reg->type & MEM_RCU) {
10287                         type = btf_type_by_id(reg->btf, reg->btf_id);
10288                         if (!type || !btf_type_is_struct(type)) {
10289                                 verbose(env, "Helper has invalid btf/btf_id in R1\n");
10290                                 return -EFAULT;
10291                         }
10292                         returns_cpu_specific_alloc_ptr = true;
10293                         env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true;
10294                 }
10295                 break;
10296         }
10297         case BPF_FUNC_user_ringbuf_drain:
10298                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
10299                                         set_user_ringbuf_callback_state);
10300                 break;
10301         }
10302
10303         if (err)
10304                 return err;
10305
10306         /* reset caller saved regs */
10307         for (i = 0; i < CALLER_SAVED_REGS; i++) {
10308                 mark_reg_not_init(env, regs, caller_saved[i]);
10309                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
10310         }
10311
10312         /* helper call returns 64-bit value. */
10313         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
10314
10315         /* update return register (already marked as written above) */
10316         ret_type = fn->ret_type;
10317         ret_flag = type_flag(ret_type);
10318
10319         switch (base_type(ret_type)) {
10320         case RET_INTEGER:
10321                 /* sets type to SCALAR_VALUE */
10322                 mark_reg_unknown(env, regs, BPF_REG_0);
10323                 break;
10324         case RET_VOID:
10325                 regs[BPF_REG_0].type = NOT_INIT;
10326                 break;
10327         case RET_PTR_TO_MAP_VALUE:
10328                 /* There is no offset yet applied, variable or fixed */
10329                 mark_reg_known_zero(env, regs, BPF_REG_0);
10330                 /* remember map_ptr, so that check_map_access()
10331                  * can check 'value_size' boundary of memory access
10332                  * to map element returned from bpf_map_lookup_elem()
10333                  */
10334                 if (meta.map_ptr == NULL) {
10335                         verbose(env,
10336                                 "kernel subsystem misconfigured verifier\n");
10337                         return -EINVAL;
10338                 }
10339                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
10340                 regs[BPF_REG_0].map_uid = meta.map_uid;
10341                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
10342                 if (!type_may_be_null(ret_type) &&
10343                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
10344                         regs[BPF_REG_0].id = ++env->id_gen;
10345                 }
10346                 break;
10347         case RET_PTR_TO_SOCKET:
10348                 mark_reg_known_zero(env, regs, BPF_REG_0);
10349                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
10350                 break;
10351         case RET_PTR_TO_SOCK_COMMON:
10352                 mark_reg_known_zero(env, regs, BPF_REG_0);
10353                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
10354                 break;
10355         case RET_PTR_TO_TCP_SOCK:
10356                 mark_reg_known_zero(env, regs, BPF_REG_0);
10357                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
10358                 break;
10359         case RET_PTR_TO_MEM:
10360                 mark_reg_known_zero(env, regs, BPF_REG_0);
10361                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10362                 regs[BPF_REG_0].mem_size = meta.mem_size;
10363                 break;
10364         case RET_PTR_TO_MEM_OR_BTF_ID:
10365         {
10366                 const struct btf_type *t;
10367
10368                 mark_reg_known_zero(env, regs, BPF_REG_0);
10369                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
10370                 if (!btf_type_is_struct(t)) {
10371                         u32 tsize;
10372                         const struct btf_type *ret;
10373                         const char *tname;
10374
10375                         /* resolve the type size of ksym. */
10376                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
10377                         if (IS_ERR(ret)) {
10378                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
10379                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
10380                                         tname, PTR_ERR(ret));
10381                                 return -EINVAL;
10382                         }
10383                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
10384                         regs[BPF_REG_0].mem_size = tsize;
10385                 } else {
10386                         if (returns_cpu_specific_alloc_ptr) {
10387                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU;
10388                         } else {
10389                                 /* MEM_RDONLY may be carried from ret_flag, but it
10390                                  * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
10391                                  * it will confuse the check of PTR_TO_BTF_ID in
10392                                  * check_mem_access().
10393                                  */
10394                                 ret_flag &= ~MEM_RDONLY;
10395                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10396                         }
10397
10398                         regs[BPF_REG_0].btf = meta.ret_btf;
10399                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
10400                 }
10401                 break;
10402         }
10403         case RET_PTR_TO_BTF_ID:
10404         {
10405                 struct btf *ret_btf;
10406                 int ret_btf_id;
10407
10408                 mark_reg_known_zero(env, regs, BPF_REG_0);
10409                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
10410                 if (func_id == BPF_FUNC_kptr_xchg) {
10411                         ret_btf = meta.kptr_field->kptr.btf;
10412                         ret_btf_id = meta.kptr_field->kptr.btf_id;
10413                         if (!btf_is_kernel(ret_btf)) {
10414                                 regs[BPF_REG_0].type |= MEM_ALLOC;
10415                                 if (meta.kptr_field->type == BPF_KPTR_PERCPU)
10416                                         regs[BPF_REG_0].type |= MEM_PERCPU;
10417                         }
10418                 } else {
10419                         if (fn->ret_btf_id == BPF_PTR_POISON) {
10420                                 verbose(env, "verifier internal error:");
10421                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
10422                                         func_id_name(func_id));
10423                                 return -EINVAL;
10424                         }
10425                         ret_btf = btf_vmlinux;
10426                         ret_btf_id = *fn->ret_btf_id;
10427                 }
10428                 if (ret_btf_id == 0) {
10429                         verbose(env, "invalid return type %u of func %s#%d\n",
10430                                 base_type(ret_type), func_id_name(func_id),
10431                                 func_id);
10432                         return -EINVAL;
10433                 }
10434                 regs[BPF_REG_0].btf = ret_btf;
10435                 regs[BPF_REG_0].btf_id = ret_btf_id;
10436                 break;
10437         }
10438         default:
10439                 verbose(env, "unknown return type %u of func %s#%d\n",
10440                         base_type(ret_type), func_id_name(func_id), func_id);
10441                 return -EINVAL;
10442         }
10443
10444         if (type_may_be_null(regs[BPF_REG_0].type))
10445                 regs[BPF_REG_0].id = ++env->id_gen;
10446
10447         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
10448                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
10449                         func_id_name(func_id), func_id);
10450                 return -EFAULT;
10451         }
10452
10453         if (is_dynptr_ref_function(func_id))
10454                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
10455
10456         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
10457                 /* For release_reference() */
10458                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
10459         } else if (is_acquire_function(func_id, meta.map_ptr)) {
10460                 int id = acquire_reference_state(env, insn_idx);
10461
10462                 if (id < 0)
10463                         return id;
10464                 /* For mark_ptr_or_null_reg() */
10465                 regs[BPF_REG_0].id = id;
10466                 /* For release_reference() */
10467                 regs[BPF_REG_0].ref_obj_id = id;
10468         }
10469
10470         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
10471
10472         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
10473         if (err)
10474                 return err;
10475
10476         if ((func_id == BPF_FUNC_get_stack ||
10477              func_id == BPF_FUNC_get_task_stack) &&
10478             !env->prog->has_callchain_buf) {
10479                 const char *err_str;
10480
10481 #ifdef CONFIG_PERF_EVENTS
10482                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
10483                 err_str = "cannot get callchain buffer for func %s#%d\n";
10484 #else
10485                 err = -ENOTSUPP;
10486                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
10487 #endif
10488                 if (err) {
10489                         verbose(env, err_str, func_id_name(func_id), func_id);
10490                         return err;
10491                 }
10492
10493                 env->prog->has_callchain_buf = true;
10494         }
10495
10496         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
10497                 env->prog->call_get_stack = true;
10498
10499         if (func_id == BPF_FUNC_get_func_ip) {
10500                 if (check_get_func_ip(env))
10501                         return -ENOTSUPP;
10502                 env->prog->call_get_func_ip = true;
10503         }
10504
10505         if (changes_data)
10506                 clear_all_pkt_pointers(env);
10507         return 0;
10508 }
10509
10510 /* mark_btf_func_reg_size() is used when the reg size is determined by
10511  * the BTF func_proto's return value size and argument.
10512  */
10513 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10514                                    size_t reg_size)
10515 {
10516         struct bpf_reg_state *reg = &cur_regs(env)[regno];
10517
10518         if (regno == BPF_REG_0) {
10519                 /* Function return value */
10520                 reg->live |= REG_LIVE_WRITTEN;
10521                 reg->subreg_def = reg_size == sizeof(u64) ?
10522                         DEF_NOT_SUBREG : env->insn_idx + 1;
10523         } else {
10524                 /* Function argument */
10525                 if (reg_size == sizeof(u64)) {
10526                         mark_insn_zext(env, reg);
10527                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10528                 } else {
10529                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10530                 }
10531         }
10532 }
10533
10534 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10535 {
10536         return meta->kfunc_flags & KF_ACQUIRE;
10537 }
10538
10539 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10540 {
10541         return meta->kfunc_flags & KF_RELEASE;
10542 }
10543
10544 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10545 {
10546         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10547 }
10548
10549 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10550 {
10551         return meta->kfunc_flags & KF_SLEEPABLE;
10552 }
10553
10554 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10555 {
10556         return meta->kfunc_flags & KF_DESTRUCTIVE;
10557 }
10558
10559 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10560 {
10561         return meta->kfunc_flags & KF_RCU;
10562 }
10563
10564 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta)
10565 {
10566         return meta->kfunc_flags & KF_RCU_PROTECTED;
10567 }
10568
10569 static bool __kfunc_param_match_suffix(const struct btf *btf,
10570                                        const struct btf_param *arg,
10571                                        const char *suffix)
10572 {
10573         int suffix_len = strlen(suffix), len;
10574         const char *param_name;
10575
10576         /* In the future, this can be ported to use BTF tagging */
10577         param_name = btf_name_by_offset(btf, arg->name_off);
10578         if (str_is_empty(param_name))
10579                 return false;
10580         len = strlen(param_name);
10581         if (len < suffix_len)
10582                 return false;
10583         param_name += len - suffix_len;
10584         return !strncmp(param_name, suffix, suffix_len);
10585 }
10586
10587 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10588                                   const struct btf_param *arg,
10589                                   const struct bpf_reg_state *reg)
10590 {
10591         const struct btf_type *t;
10592
10593         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10594         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10595                 return false;
10596
10597         return __kfunc_param_match_suffix(btf, arg, "__sz");
10598 }
10599
10600 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10601                                         const struct btf_param *arg,
10602                                         const struct bpf_reg_state *reg)
10603 {
10604         const struct btf_type *t;
10605
10606         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10607         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10608                 return false;
10609
10610         return __kfunc_param_match_suffix(btf, arg, "__szk");
10611 }
10612
10613 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10614 {
10615         return __kfunc_param_match_suffix(btf, arg, "__opt");
10616 }
10617
10618 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10619 {
10620         return __kfunc_param_match_suffix(btf, arg, "__k");
10621 }
10622
10623 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10624 {
10625         return __kfunc_param_match_suffix(btf, arg, "__ign");
10626 }
10627
10628 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10629 {
10630         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10631 }
10632
10633 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10634 {
10635         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10636 }
10637
10638 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10639 {
10640         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10641 }
10642
10643 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg)
10644 {
10645         return __kfunc_param_match_suffix(btf, arg, "__nullable");
10646 }
10647
10648 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10649                                           const struct btf_param *arg,
10650                                           const char *name)
10651 {
10652         int len, target_len = strlen(name);
10653         const char *param_name;
10654
10655         param_name = btf_name_by_offset(btf, arg->name_off);
10656         if (str_is_empty(param_name))
10657                 return false;
10658         len = strlen(param_name);
10659         if (len != target_len)
10660                 return false;
10661         if (strcmp(param_name, name))
10662                 return false;
10663
10664         return true;
10665 }
10666
10667 enum {
10668         KF_ARG_DYNPTR_ID,
10669         KF_ARG_LIST_HEAD_ID,
10670         KF_ARG_LIST_NODE_ID,
10671         KF_ARG_RB_ROOT_ID,
10672         KF_ARG_RB_NODE_ID,
10673 };
10674
10675 BTF_ID_LIST(kf_arg_btf_ids)
10676 BTF_ID(struct, bpf_dynptr_kern)
10677 BTF_ID(struct, bpf_list_head)
10678 BTF_ID(struct, bpf_list_node)
10679 BTF_ID(struct, bpf_rb_root)
10680 BTF_ID(struct, bpf_rb_node)
10681
10682 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10683                                     const struct btf_param *arg, int type)
10684 {
10685         const struct btf_type *t;
10686         u32 res_id;
10687
10688         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10689         if (!t)
10690                 return false;
10691         if (!btf_type_is_ptr(t))
10692                 return false;
10693         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10694         if (!t)
10695                 return false;
10696         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10697 }
10698
10699 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10700 {
10701         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10702 }
10703
10704 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10705 {
10706         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10707 }
10708
10709 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10710 {
10711         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10712 }
10713
10714 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10715 {
10716         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10717 }
10718
10719 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10720 {
10721         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10722 }
10723
10724 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10725                                   const struct btf_param *arg)
10726 {
10727         const struct btf_type *t;
10728
10729         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10730         if (!t)
10731                 return false;
10732
10733         return true;
10734 }
10735
10736 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10737 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10738                                         const struct btf *btf,
10739                                         const struct btf_type *t, int rec)
10740 {
10741         const struct btf_type *member_type;
10742         const struct btf_member *member;
10743         u32 i;
10744
10745         if (!btf_type_is_struct(t))
10746                 return false;
10747
10748         for_each_member(i, t, member) {
10749                 const struct btf_array *array;
10750
10751                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10752                 if (btf_type_is_struct(member_type)) {
10753                         if (rec >= 3) {
10754                                 verbose(env, "max struct nesting depth exceeded\n");
10755                                 return false;
10756                         }
10757                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10758                                 return false;
10759                         continue;
10760                 }
10761                 if (btf_type_is_array(member_type)) {
10762                         array = btf_array(member_type);
10763                         if (!array->nelems)
10764                                 return false;
10765                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10766                         if (!btf_type_is_scalar(member_type))
10767                                 return false;
10768                         continue;
10769                 }
10770                 if (!btf_type_is_scalar(member_type))
10771                         return false;
10772         }
10773         return true;
10774 }
10775
10776 enum kfunc_ptr_arg_type {
10777         KF_ARG_PTR_TO_CTX,
10778         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10779         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10780         KF_ARG_PTR_TO_DYNPTR,
10781         KF_ARG_PTR_TO_ITER,
10782         KF_ARG_PTR_TO_LIST_HEAD,
10783         KF_ARG_PTR_TO_LIST_NODE,
10784         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10785         KF_ARG_PTR_TO_MEM,
10786         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10787         KF_ARG_PTR_TO_CALLBACK,
10788         KF_ARG_PTR_TO_RB_ROOT,
10789         KF_ARG_PTR_TO_RB_NODE,
10790         KF_ARG_PTR_TO_NULL,
10791 };
10792
10793 enum special_kfunc_type {
10794         KF_bpf_obj_new_impl,
10795         KF_bpf_obj_drop_impl,
10796         KF_bpf_refcount_acquire_impl,
10797         KF_bpf_list_push_front_impl,
10798         KF_bpf_list_push_back_impl,
10799         KF_bpf_list_pop_front,
10800         KF_bpf_list_pop_back,
10801         KF_bpf_cast_to_kern_ctx,
10802         KF_bpf_rdonly_cast,
10803         KF_bpf_rcu_read_lock,
10804         KF_bpf_rcu_read_unlock,
10805         KF_bpf_rbtree_remove,
10806         KF_bpf_rbtree_add_impl,
10807         KF_bpf_rbtree_first,
10808         KF_bpf_dynptr_from_skb,
10809         KF_bpf_dynptr_from_xdp,
10810         KF_bpf_dynptr_slice,
10811         KF_bpf_dynptr_slice_rdwr,
10812         KF_bpf_dynptr_clone,
10813         KF_bpf_percpu_obj_new_impl,
10814         KF_bpf_percpu_obj_drop_impl,
10815         KF_bpf_throw,
10816         KF_bpf_iter_css_task_new,
10817 };
10818
10819 BTF_SET_START(special_kfunc_set)
10820 BTF_ID(func, bpf_obj_new_impl)
10821 BTF_ID(func, bpf_obj_drop_impl)
10822 BTF_ID(func, bpf_refcount_acquire_impl)
10823 BTF_ID(func, bpf_list_push_front_impl)
10824 BTF_ID(func, bpf_list_push_back_impl)
10825 BTF_ID(func, bpf_list_pop_front)
10826 BTF_ID(func, bpf_list_pop_back)
10827 BTF_ID(func, bpf_cast_to_kern_ctx)
10828 BTF_ID(func, bpf_rdonly_cast)
10829 BTF_ID(func, bpf_rbtree_remove)
10830 BTF_ID(func, bpf_rbtree_add_impl)
10831 BTF_ID(func, bpf_rbtree_first)
10832 BTF_ID(func, bpf_dynptr_from_skb)
10833 BTF_ID(func, bpf_dynptr_from_xdp)
10834 BTF_ID(func, bpf_dynptr_slice)
10835 BTF_ID(func, bpf_dynptr_slice_rdwr)
10836 BTF_ID(func, bpf_dynptr_clone)
10837 BTF_ID(func, bpf_percpu_obj_new_impl)
10838 BTF_ID(func, bpf_percpu_obj_drop_impl)
10839 BTF_ID(func, bpf_throw)
10840 #ifdef CONFIG_CGROUPS
10841 BTF_ID(func, bpf_iter_css_task_new)
10842 #endif
10843 BTF_SET_END(special_kfunc_set)
10844
10845 BTF_ID_LIST(special_kfunc_list)
10846 BTF_ID(func, bpf_obj_new_impl)
10847 BTF_ID(func, bpf_obj_drop_impl)
10848 BTF_ID(func, bpf_refcount_acquire_impl)
10849 BTF_ID(func, bpf_list_push_front_impl)
10850 BTF_ID(func, bpf_list_push_back_impl)
10851 BTF_ID(func, bpf_list_pop_front)
10852 BTF_ID(func, bpf_list_pop_back)
10853 BTF_ID(func, bpf_cast_to_kern_ctx)
10854 BTF_ID(func, bpf_rdonly_cast)
10855 BTF_ID(func, bpf_rcu_read_lock)
10856 BTF_ID(func, bpf_rcu_read_unlock)
10857 BTF_ID(func, bpf_rbtree_remove)
10858 BTF_ID(func, bpf_rbtree_add_impl)
10859 BTF_ID(func, bpf_rbtree_first)
10860 BTF_ID(func, bpf_dynptr_from_skb)
10861 BTF_ID(func, bpf_dynptr_from_xdp)
10862 BTF_ID(func, bpf_dynptr_slice)
10863 BTF_ID(func, bpf_dynptr_slice_rdwr)
10864 BTF_ID(func, bpf_dynptr_clone)
10865 BTF_ID(func, bpf_percpu_obj_new_impl)
10866 BTF_ID(func, bpf_percpu_obj_drop_impl)
10867 BTF_ID(func, bpf_throw)
10868 #ifdef CONFIG_CGROUPS
10869 BTF_ID(func, bpf_iter_css_task_new)
10870 #else
10871 BTF_ID_UNUSED
10872 #endif
10873
10874 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10875 {
10876         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10877             meta->arg_owning_ref) {
10878                 return false;
10879         }
10880
10881         return meta->kfunc_flags & KF_RET_NULL;
10882 }
10883
10884 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10885 {
10886         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10887 }
10888
10889 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10890 {
10891         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10892 }
10893
10894 static enum kfunc_ptr_arg_type
10895 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10896                        struct bpf_kfunc_call_arg_meta *meta,
10897                        const struct btf_type *t, const struct btf_type *ref_t,
10898                        const char *ref_tname, const struct btf_param *args,
10899                        int argno, int nargs)
10900 {
10901         u32 regno = argno + 1;
10902         struct bpf_reg_state *regs = cur_regs(env);
10903         struct bpf_reg_state *reg = &regs[regno];
10904         bool arg_mem_size = false;
10905
10906         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10907                 return KF_ARG_PTR_TO_CTX;
10908
10909         /* In this function, we verify the kfunc's BTF as per the argument type,
10910          * leaving the rest of the verification with respect to the register
10911          * type to our caller. When a set of conditions hold in the BTF type of
10912          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10913          */
10914         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10915                 return KF_ARG_PTR_TO_CTX;
10916
10917         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10918                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10919
10920         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10921                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10922
10923         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10924                 return KF_ARG_PTR_TO_DYNPTR;
10925
10926         if (is_kfunc_arg_iter(meta, argno))
10927                 return KF_ARG_PTR_TO_ITER;
10928
10929         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10930                 return KF_ARG_PTR_TO_LIST_HEAD;
10931
10932         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10933                 return KF_ARG_PTR_TO_LIST_NODE;
10934
10935         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10936                 return KF_ARG_PTR_TO_RB_ROOT;
10937
10938         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10939                 return KF_ARG_PTR_TO_RB_NODE;
10940
10941         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10942                 if (!btf_type_is_struct(ref_t)) {
10943                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10944                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10945                         return -EINVAL;
10946                 }
10947                 return KF_ARG_PTR_TO_BTF_ID;
10948         }
10949
10950         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10951                 return KF_ARG_PTR_TO_CALLBACK;
10952
10953         if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg))
10954                 return KF_ARG_PTR_TO_NULL;
10955
10956         if (argno + 1 < nargs &&
10957             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10958              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10959                 arg_mem_size = true;
10960
10961         /* This is the catch all argument type of register types supported by
10962          * check_helper_mem_access. However, we only allow when argument type is
10963          * pointer to scalar, or struct composed (recursively) of scalars. When
10964          * arg_mem_size is true, the pointer can be void *.
10965          */
10966         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10967             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10968                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10969                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10970                 return -EINVAL;
10971         }
10972         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10973 }
10974
10975 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10976                                         struct bpf_reg_state *reg,
10977                                         const struct btf_type *ref_t,
10978                                         const char *ref_tname, u32 ref_id,
10979                                         struct bpf_kfunc_call_arg_meta *meta,
10980                                         int argno)
10981 {
10982         const struct btf_type *reg_ref_t;
10983         bool strict_type_match = false;
10984         const struct btf *reg_btf;
10985         const char *reg_ref_tname;
10986         u32 reg_ref_id;
10987
10988         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10989                 reg_btf = reg->btf;
10990                 reg_ref_id = reg->btf_id;
10991         } else {
10992                 reg_btf = btf_vmlinux;
10993                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10994         }
10995
10996         /* Enforce strict type matching for calls to kfuncs that are acquiring
10997          * or releasing a reference, or are no-cast aliases. We do _not_
10998          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10999          * as we want to enable BPF programs to pass types that are bitwise
11000          * equivalent without forcing them to explicitly cast with something
11001          * like bpf_cast_to_kern_ctx().
11002          *
11003          * For example, say we had a type like the following:
11004          *
11005          * struct bpf_cpumask {
11006          *      cpumask_t cpumask;
11007          *      refcount_t usage;
11008          * };
11009          *
11010          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
11011          * to a struct cpumask, so it would be safe to pass a struct
11012          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
11013          *
11014          * The philosophy here is similar to how we allow scalars of different
11015          * types to be passed to kfuncs as long as the size is the same. The
11016          * only difference here is that we're simply allowing
11017          * btf_struct_ids_match() to walk the struct at the 0th offset, and
11018          * resolve types.
11019          */
11020         if (is_kfunc_acquire(meta) ||
11021             (is_kfunc_release(meta) && reg->ref_obj_id) ||
11022             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
11023                 strict_type_match = true;
11024
11025         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
11026
11027         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
11028         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
11029         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
11030                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
11031                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
11032                         btf_type_str(reg_ref_t), reg_ref_tname);
11033                 return -EINVAL;
11034         }
11035         return 0;
11036 }
11037
11038 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11039 {
11040         struct bpf_verifier_state *state = env->cur_state;
11041         struct btf_record *rec = reg_btf_record(reg);
11042
11043         if (!state->active_lock.ptr) {
11044                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
11045                 return -EFAULT;
11046         }
11047
11048         if (type_flag(reg->type) & NON_OWN_REF) {
11049                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
11050                 return -EFAULT;
11051         }
11052
11053         reg->type |= NON_OWN_REF;
11054         if (rec->refcount_off >= 0)
11055                 reg->type |= MEM_RCU;
11056
11057         return 0;
11058 }
11059
11060 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
11061 {
11062         struct bpf_func_state *state, *unused;
11063         struct bpf_reg_state *reg;
11064         int i;
11065
11066         state = cur_func(env);
11067
11068         if (!ref_obj_id) {
11069                 verbose(env, "verifier internal error: ref_obj_id is zero for "
11070                              "owning -> non-owning conversion\n");
11071                 return -EFAULT;
11072         }
11073
11074         for (i = 0; i < state->acquired_refs; i++) {
11075                 if (state->refs[i].id != ref_obj_id)
11076                         continue;
11077
11078                 /* Clear ref_obj_id here so release_reference doesn't clobber
11079                  * the whole reg
11080                  */
11081                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
11082                         if (reg->ref_obj_id == ref_obj_id) {
11083                                 reg->ref_obj_id = 0;
11084                                 ref_set_non_owning(env, reg);
11085                         }
11086                 }));
11087                 return 0;
11088         }
11089
11090         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
11091         return -EFAULT;
11092 }
11093
11094 /* Implementation details:
11095  *
11096  * Each register points to some region of memory, which we define as an
11097  * allocation. Each allocation may embed a bpf_spin_lock which protects any
11098  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
11099  * allocation. The lock and the data it protects are colocated in the same
11100  * memory region.
11101  *
11102  * Hence, everytime a register holds a pointer value pointing to such
11103  * allocation, the verifier preserves a unique reg->id for it.
11104  *
11105  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
11106  * bpf_spin_lock is called.
11107  *
11108  * To enable this, lock state in the verifier captures two values:
11109  *      active_lock.ptr = Register's type specific pointer
11110  *      active_lock.id  = A unique ID for each register pointer value
11111  *
11112  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
11113  * supported register types.
11114  *
11115  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
11116  * allocated objects is the reg->btf pointer.
11117  *
11118  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
11119  * can establish the provenance of the map value statically for each distinct
11120  * lookup into such maps. They always contain a single map value hence unique
11121  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
11122  *
11123  * So, in case of global variables, they use array maps with max_entries = 1,
11124  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
11125  * into the same map value as max_entries is 1, as described above).
11126  *
11127  * In case of inner map lookups, the inner map pointer has same map_ptr as the
11128  * outer map pointer (in verifier context), but each lookup into an inner map
11129  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
11130  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
11131  * will get different reg->id assigned to each lookup, hence different
11132  * active_lock.id.
11133  *
11134  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
11135  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
11136  * returned from bpf_obj_new. Each allocation receives a new reg->id.
11137  */
11138 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
11139 {
11140         void *ptr;
11141         u32 id;
11142
11143         switch ((int)reg->type) {
11144         case PTR_TO_MAP_VALUE:
11145                 ptr = reg->map_ptr;
11146                 break;
11147         case PTR_TO_BTF_ID | MEM_ALLOC:
11148                 ptr = reg->btf;
11149                 break;
11150         default:
11151                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
11152                 return -EFAULT;
11153         }
11154         id = reg->id;
11155
11156         if (!env->cur_state->active_lock.ptr)
11157                 return -EINVAL;
11158         if (env->cur_state->active_lock.ptr != ptr ||
11159             env->cur_state->active_lock.id != id) {
11160                 verbose(env, "held lock and object are not in the same allocation\n");
11161                 return -EINVAL;
11162         }
11163         return 0;
11164 }
11165
11166 static bool is_bpf_list_api_kfunc(u32 btf_id)
11167 {
11168         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11169                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11170                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11171                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
11172 }
11173
11174 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
11175 {
11176         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
11177                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11178                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
11179 }
11180
11181 static bool is_bpf_graph_api_kfunc(u32 btf_id)
11182 {
11183         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
11184                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
11185 }
11186
11187 static bool is_callback_calling_kfunc(u32 btf_id)
11188 {
11189         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
11190 }
11191
11192 static bool is_bpf_throw_kfunc(struct bpf_insn *insn)
11193 {
11194         return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
11195                insn->imm == special_kfunc_list[KF_bpf_throw];
11196 }
11197
11198 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
11199 {
11200         return is_bpf_rbtree_api_kfunc(btf_id);
11201 }
11202
11203 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
11204                                           enum btf_field_type head_field_type,
11205                                           u32 kfunc_btf_id)
11206 {
11207         bool ret;
11208
11209         switch (head_field_type) {
11210         case BPF_LIST_HEAD:
11211                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
11212                 break;
11213         case BPF_RB_ROOT:
11214                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
11215                 break;
11216         default:
11217                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
11218                         btf_field_type_name(head_field_type));
11219                 return false;
11220         }
11221
11222         if (!ret)
11223                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
11224                         btf_field_type_name(head_field_type));
11225         return ret;
11226 }
11227
11228 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
11229                                           enum btf_field_type node_field_type,
11230                                           u32 kfunc_btf_id)
11231 {
11232         bool ret;
11233
11234         switch (node_field_type) {
11235         case BPF_LIST_NODE:
11236                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11237                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
11238                 break;
11239         case BPF_RB_NODE:
11240                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11241                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
11242                 break;
11243         default:
11244                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
11245                         btf_field_type_name(node_field_type));
11246                 return false;
11247         }
11248
11249         if (!ret)
11250                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
11251                         btf_field_type_name(node_field_type));
11252         return ret;
11253 }
11254
11255 static int
11256 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
11257                                    struct bpf_reg_state *reg, u32 regno,
11258                                    struct bpf_kfunc_call_arg_meta *meta,
11259                                    enum btf_field_type head_field_type,
11260                                    struct btf_field **head_field)
11261 {
11262         const char *head_type_name;
11263         struct btf_field *field;
11264         struct btf_record *rec;
11265         u32 head_off;
11266
11267         if (meta->btf != btf_vmlinux) {
11268                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11269                 return -EFAULT;
11270         }
11271
11272         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
11273                 return -EFAULT;
11274
11275         head_type_name = btf_field_type_name(head_field_type);
11276         if (!tnum_is_const(reg->var_off)) {
11277                 verbose(env,
11278                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11279                         regno, head_type_name);
11280                 return -EINVAL;
11281         }
11282
11283         rec = reg_btf_record(reg);
11284         head_off = reg->off + reg->var_off.value;
11285         field = btf_record_find(rec, head_off, head_field_type);
11286         if (!field) {
11287                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
11288                 return -EINVAL;
11289         }
11290
11291         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
11292         if (check_reg_allocation_locked(env, reg)) {
11293                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
11294                         rec->spin_lock_off, head_type_name);
11295                 return -EINVAL;
11296         }
11297
11298         if (*head_field) {
11299                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
11300                 return -EFAULT;
11301         }
11302         *head_field = field;
11303         return 0;
11304 }
11305
11306 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
11307                                            struct bpf_reg_state *reg, u32 regno,
11308                                            struct bpf_kfunc_call_arg_meta *meta)
11309 {
11310         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
11311                                                           &meta->arg_list_head.field);
11312 }
11313
11314 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
11315                                              struct bpf_reg_state *reg, u32 regno,
11316                                              struct bpf_kfunc_call_arg_meta *meta)
11317 {
11318         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
11319                                                           &meta->arg_rbtree_root.field);
11320 }
11321
11322 static int
11323 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
11324                                    struct bpf_reg_state *reg, u32 regno,
11325                                    struct bpf_kfunc_call_arg_meta *meta,
11326                                    enum btf_field_type head_field_type,
11327                                    enum btf_field_type node_field_type,
11328                                    struct btf_field **node_field)
11329 {
11330         const char *node_type_name;
11331         const struct btf_type *et, *t;
11332         struct btf_field *field;
11333         u32 node_off;
11334
11335         if (meta->btf != btf_vmlinux) {
11336                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
11337                 return -EFAULT;
11338         }
11339
11340         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
11341                 return -EFAULT;
11342
11343         node_type_name = btf_field_type_name(node_field_type);
11344         if (!tnum_is_const(reg->var_off)) {
11345                 verbose(env,
11346                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
11347                         regno, node_type_name);
11348                 return -EINVAL;
11349         }
11350
11351         node_off = reg->off + reg->var_off.value;
11352         field = reg_find_field_offset(reg, node_off, node_field_type);
11353         if (!field || field->offset != node_off) {
11354                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
11355                 return -EINVAL;
11356         }
11357
11358         field = *node_field;
11359
11360         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
11361         t = btf_type_by_id(reg->btf, reg->btf_id);
11362         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
11363                                   field->graph_root.value_btf_id, true)) {
11364                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
11365                         "in struct %s, but arg is at offset=%d in struct %s\n",
11366                         btf_field_type_name(head_field_type),
11367                         btf_field_type_name(node_field_type),
11368                         field->graph_root.node_offset,
11369                         btf_name_by_offset(field->graph_root.btf, et->name_off),
11370                         node_off, btf_name_by_offset(reg->btf, t->name_off));
11371                 return -EINVAL;
11372         }
11373         meta->arg_btf = reg->btf;
11374         meta->arg_btf_id = reg->btf_id;
11375
11376         if (node_off != field->graph_root.node_offset) {
11377                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
11378                         node_off, btf_field_type_name(node_field_type),
11379                         field->graph_root.node_offset,
11380                         btf_name_by_offset(field->graph_root.btf, et->name_off));
11381                 return -EINVAL;
11382         }
11383
11384         return 0;
11385 }
11386
11387 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
11388                                            struct bpf_reg_state *reg, u32 regno,
11389                                            struct bpf_kfunc_call_arg_meta *meta)
11390 {
11391         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11392                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
11393                                                   &meta->arg_list_head.field);
11394 }
11395
11396 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
11397                                              struct bpf_reg_state *reg, u32 regno,
11398                                              struct bpf_kfunc_call_arg_meta *meta)
11399 {
11400         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
11401                                                   BPF_RB_ROOT, BPF_RB_NODE,
11402                                                   &meta->arg_rbtree_root.field);
11403 }
11404
11405 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env)
11406 {
11407         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
11408
11409         switch (prog_type) {
11410         case BPF_PROG_TYPE_LSM:
11411                 return true;
11412         case BPF_TRACE_ITER:
11413                 return env->prog->aux->sleepable;
11414         default:
11415                 return false;
11416         }
11417 }
11418
11419 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
11420                             int insn_idx)
11421 {
11422         const char *func_name = meta->func_name, *ref_tname;
11423         const struct btf *btf = meta->btf;
11424         const struct btf_param *args;
11425         struct btf_record *rec;
11426         u32 i, nargs;
11427         int ret;
11428
11429         args = (const struct btf_param *)(meta->func_proto + 1);
11430         nargs = btf_type_vlen(meta->func_proto);
11431         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
11432                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
11433                         MAX_BPF_FUNC_REG_ARGS);
11434                 return -EINVAL;
11435         }
11436
11437         /* Check that BTF function arguments match actual types that the
11438          * verifier sees.
11439          */
11440         for (i = 0; i < nargs; i++) {
11441                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
11442                 const struct btf_type *t, *ref_t, *resolve_ret;
11443                 enum bpf_arg_type arg_type = ARG_DONTCARE;
11444                 u32 regno = i + 1, ref_id, type_size;
11445                 bool is_ret_buf_sz = false;
11446                 int kf_arg_type;
11447
11448                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
11449
11450                 if (is_kfunc_arg_ignore(btf, &args[i]))
11451                         continue;
11452
11453                 if (btf_type_is_scalar(t)) {
11454                         if (reg->type != SCALAR_VALUE) {
11455                                 verbose(env, "R%d is not a scalar\n", regno);
11456                                 return -EINVAL;
11457                         }
11458
11459                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
11460                                 if (meta->arg_constant.found) {
11461                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11462                                         return -EFAULT;
11463                                 }
11464                                 if (!tnum_is_const(reg->var_off)) {
11465                                         verbose(env, "R%d must be a known constant\n", regno);
11466                                         return -EINVAL;
11467                                 }
11468                                 ret = mark_chain_precision(env, regno);
11469                                 if (ret < 0)
11470                                         return ret;
11471                                 meta->arg_constant.found = true;
11472                                 meta->arg_constant.value = reg->var_off.value;
11473                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
11474                                 meta->r0_rdonly = true;
11475                                 is_ret_buf_sz = true;
11476                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
11477                                 is_ret_buf_sz = true;
11478                         }
11479
11480                         if (is_ret_buf_sz) {
11481                                 if (meta->r0_size) {
11482                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
11483                                         return -EINVAL;
11484                                 }
11485
11486                                 if (!tnum_is_const(reg->var_off)) {
11487                                         verbose(env, "R%d is not a const\n", regno);
11488                                         return -EINVAL;
11489                                 }
11490
11491                                 meta->r0_size = reg->var_off.value;
11492                                 ret = mark_chain_precision(env, regno);
11493                                 if (ret)
11494                                         return ret;
11495                         }
11496                         continue;
11497                 }
11498
11499                 if (!btf_type_is_ptr(t)) {
11500                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
11501                         return -EINVAL;
11502                 }
11503
11504                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
11505                     (register_is_null(reg) || type_may_be_null(reg->type)) &&
11506                         !is_kfunc_arg_nullable(meta->btf, &args[i])) {
11507                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
11508                         return -EACCES;
11509                 }
11510
11511                 if (reg->ref_obj_id) {
11512                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
11513                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
11514                                         regno, reg->ref_obj_id,
11515                                         meta->ref_obj_id);
11516                                 return -EFAULT;
11517                         }
11518                         meta->ref_obj_id = reg->ref_obj_id;
11519                         if (is_kfunc_release(meta))
11520                                 meta->release_regno = regno;
11521                 }
11522
11523                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
11524                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
11525
11526                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
11527                 if (kf_arg_type < 0)
11528                         return kf_arg_type;
11529
11530                 switch (kf_arg_type) {
11531                 case KF_ARG_PTR_TO_NULL:
11532                         continue;
11533                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11534                 case KF_ARG_PTR_TO_BTF_ID:
11535                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
11536                                 break;
11537
11538                         if (!is_trusted_reg(reg)) {
11539                                 if (!is_kfunc_rcu(meta)) {
11540                                         verbose(env, "R%d must be referenced or trusted\n", regno);
11541                                         return -EINVAL;
11542                                 }
11543                                 if (!is_rcu_reg(reg)) {
11544                                         verbose(env, "R%d must be a rcu pointer\n", regno);
11545                                         return -EINVAL;
11546                                 }
11547                         }
11548
11549                         fallthrough;
11550                 case KF_ARG_PTR_TO_CTX:
11551                         /* Trusted arguments have the same offset checks as release arguments */
11552                         arg_type |= OBJ_RELEASE;
11553                         break;
11554                 case KF_ARG_PTR_TO_DYNPTR:
11555                 case KF_ARG_PTR_TO_ITER:
11556                 case KF_ARG_PTR_TO_LIST_HEAD:
11557                 case KF_ARG_PTR_TO_LIST_NODE:
11558                 case KF_ARG_PTR_TO_RB_ROOT:
11559                 case KF_ARG_PTR_TO_RB_NODE:
11560                 case KF_ARG_PTR_TO_MEM:
11561                 case KF_ARG_PTR_TO_MEM_SIZE:
11562                 case KF_ARG_PTR_TO_CALLBACK:
11563                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11564                         /* Trusted by default */
11565                         break;
11566                 default:
11567                         WARN_ON_ONCE(1);
11568                         return -EFAULT;
11569                 }
11570
11571                 if (is_kfunc_release(meta) && reg->ref_obj_id)
11572                         arg_type |= OBJ_RELEASE;
11573                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11574                 if (ret < 0)
11575                         return ret;
11576
11577                 switch (kf_arg_type) {
11578                 case KF_ARG_PTR_TO_CTX:
11579                         if (reg->type != PTR_TO_CTX) {
11580                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11581                                 return -EINVAL;
11582                         }
11583
11584                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11585                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11586                                 if (ret < 0)
11587                                         return -EINVAL;
11588                                 meta->ret_btf_id  = ret;
11589                         }
11590                         break;
11591                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11592                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) {
11593                                 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) {
11594                                         verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i);
11595                                         return -EINVAL;
11596                                 }
11597                         } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) {
11598                                 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
11599                                         verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i);
11600                                         return -EINVAL;
11601                                 }
11602                         } else {
11603                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11604                                 return -EINVAL;
11605                         }
11606                         if (!reg->ref_obj_id) {
11607                                 verbose(env, "allocated object must be referenced\n");
11608                                 return -EINVAL;
11609                         }
11610                         if (meta->btf == btf_vmlinux) {
11611                                 meta->arg_btf = reg->btf;
11612                                 meta->arg_btf_id = reg->btf_id;
11613                         }
11614                         break;
11615                 case KF_ARG_PTR_TO_DYNPTR:
11616                 {
11617                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11618                         int clone_ref_obj_id = 0;
11619
11620                         if (reg->type != PTR_TO_STACK &&
11621                             reg->type != CONST_PTR_TO_DYNPTR) {
11622                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11623                                 return -EINVAL;
11624                         }
11625
11626                         if (reg->type == CONST_PTR_TO_DYNPTR)
11627                                 dynptr_arg_type |= MEM_RDONLY;
11628
11629                         if (is_kfunc_arg_uninit(btf, &args[i]))
11630                                 dynptr_arg_type |= MEM_UNINIT;
11631
11632                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11633                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11634                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11635                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11636                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11637                                    (dynptr_arg_type & MEM_UNINIT)) {
11638                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11639
11640                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11641                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11642                                         return -EFAULT;
11643                                 }
11644
11645                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11646                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11647                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11648                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11649                                         return -EFAULT;
11650                                 }
11651                         }
11652
11653                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11654                         if (ret < 0)
11655                                 return ret;
11656
11657                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11658                                 int id = dynptr_id(env, reg);
11659
11660                                 if (id < 0) {
11661                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11662                                         return id;
11663                                 }
11664                                 meta->initialized_dynptr.id = id;
11665                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11666                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11667                         }
11668
11669                         break;
11670                 }
11671                 case KF_ARG_PTR_TO_ITER:
11672                         if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) {
11673                                 if (!check_css_task_iter_allowlist(env)) {
11674                                         verbose(env, "css_task_iter is only allowed in bpf_lsm and bpf iter-s\n");
11675                                         return -EINVAL;
11676                                 }
11677                         }
11678                         ret = process_iter_arg(env, regno, insn_idx, meta);
11679                         if (ret < 0)
11680                                 return ret;
11681                         break;
11682                 case KF_ARG_PTR_TO_LIST_HEAD:
11683                         if (reg->type != PTR_TO_MAP_VALUE &&
11684                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11685                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11686                                 return -EINVAL;
11687                         }
11688                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11689                                 verbose(env, "allocated object must be referenced\n");
11690                                 return -EINVAL;
11691                         }
11692                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11693                         if (ret < 0)
11694                                 return ret;
11695                         break;
11696                 case KF_ARG_PTR_TO_RB_ROOT:
11697                         if (reg->type != PTR_TO_MAP_VALUE &&
11698                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11699                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11700                                 return -EINVAL;
11701                         }
11702                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11703                                 verbose(env, "allocated object must be referenced\n");
11704                                 return -EINVAL;
11705                         }
11706                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11707                         if (ret < 0)
11708                                 return ret;
11709                         break;
11710                 case KF_ARG_PTR_TO_LIST_NODE:
11711                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11712                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11713                                 return -EINVAL;
11714                         }
11715                         if (!reg->ref_obj_id) {
11716                                 verbose(env, "allocated object must be referenced\n");
11717                                 return -EINVAL;
11718                         }
11719                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11720                         if (ret < 0)
11721                                 return ret;
11722                         break;
11723                 case KF_ARG_PTR_TO_RB_NODE:
11724                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11725                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11726                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11727                                         return -EINVAL;
11728                                 }
11729                                 if (in_rbtree_lock_required_cb(env)) {
11730                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11731                                         return -EINVAL;
11732                                 }
11733                         } else {
11734                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11735                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11736                                         return -EINVAL;
11737                                 }
11738                                 if (!reg->ref_obj_id) {
11739                                         verbose(env, "allocated object must be referenced\n");
11740                                         return -EINVAL;
11741                                 }
11742                         }
11743
11744                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11745                         if (ret < 0)
11746                                 return ret;
11747                         break;
11748                 case KF_ARG_PTR_TO_BTF_ID:
11749                         /* Only base_type is checked, further checks are done here */
11750                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11751                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11752                             !reg2btf_ids[base_type(reg->type)]) {
11753                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11754                                 verbose(env, "expected %s or socket\n",
11755                                         reg_type_str(env, base_type(reg->type) |
11756                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11757                                 return -EINVAL;
11758                         }
11759                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11760                         if (ret < 0)
11761                                 return ret;
11762                         break;
11763                 case KF_ARG_PTR_TO_MEM:
11764                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11765                         if (IS_ERR(resolve_ret)) {
11766                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11767                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11768                                 return -EINVAL;
11769                         }
11770                         ret = check_mem_reg(env, reg, regno, type_size);
11771                         if (ret < 0)
11772                                 return ret;
11773                         break;
11774                 case KF_ARG_PTR_TO_MEM_SIZE:
11775                 {
11776                         struct bpf_reg_state *buff_reg = &regs[regno];
11777                         const struct btf_param *buff_arg = &args[i];
11778                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11779                         const struct btf_param *size_arg = &args[i + 1];
11780
11781                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11782                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11783                                 if (ret < 0) {
11784                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11785                                         return ret;
11786                                 }
11787                         }
11788
11789                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11790                                 if (meta->arg_constant.found) {
11791                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11792                                         return -EFAULT;
11793                                 }
11794                                 if (!tnum_is_const(size_reg->var_off)) {
11795                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11796                                         return -EINVAL;
11797                                 }
11798                                 meta->arg_constant.found = true;
11799                                 meta->arg_constant.value = size_reg->var_off.value;
11800                         }
11801
11802                         /* Skip next '__sz' or '__szk' argument */
11803                         i++;
11804                         break;
11805                 }
11806                 case KF_ARG_PTR_TO_CALLBACK:
11807                         if (reg->type != PTR_TO_FUNC) {
11808                                 verbose(env, "arg%d expected pointer to func\n", i);
11809                                 return -EINVAL;
11810                         }
11811                         meta->subprogno = reg->subprogno;
11812                         break;
11813                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11814                         if (!type_is_ptr_alloc_obj(reg->type)) {
11815                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11816                                 return -EINVAL;
11817                         }
11818                         if (!type_is_non_owning_ref(reg->type))
11819                                 meta->arg_owning_ref = true;
11820
11821                         rec = reg_btf_record(reg);
11822                         if (!rec) {
11823                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11824                                 return -EFAULT;
11825                         }
11826
11827                         if (rec->refcount_off < 0) {
11828                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11829                                 return -EINVAL;
11830                         }
11831
11832                         meta->arg_btf = reg->btf;
11833                         meta->arg_btf_id = reg->btf_id;
11834                         break;
11835                 }
11836         }
11837
11838         if (is_kfunc_release(meta) && !meta->release_regno) {
11839                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11840                         func_name);
11841                 return -EINVAL;
11842         }
11843
11844         return 0;
11845 }
11846
11847 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11848                             struct bpf_insn *insn,
11849                             struct bpf_kfunc_call_arg_meta *meta,
11850                             const char **kfunc_name)
11851 {
11852         const struct btf_type *func, *func_proto;
11853         u32 func_id, *kfunc_flags;
11854         const char *func_name;
11855         struct btf *desc_btf;
11856
11857         if (kfunc_name)
11858                 *kfunc_name = NULL;
11859
11860         if (!insn->imm)
11861                 return -EINVAL;
11862
11863         desc_btf = find_kfunc_desc_btf(env, insn->off);
11864         if (IS_ERR(desc_btf))
11865                 return PTR_ERR(desc_btf);
11866
11867         func_id = insn->imm;
11868         func = btf_type_by_id(desc_btf, func_id);
11869         func_name = btf_name_by_offset(desc_btf, func->name_off);
11870         if (kfunc_name)
11871                 *kfunc_name = func_name;
11872         func_proto = btf_type_by_id(desc_btf, func->type);
11873
11874         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11875         if (!kfunc_flags) {
11876                 return -EACCES;
11877         }
11878
11879         memset(meta, 0, sizeof(*meta));
11880         meta->btf = desc_btf;
11881         meta->func_id = func_id;
11882         meta->kfunc_flags = *kfunc_flags;
11883         meta->func_proto = func_proto;
11884         meta->func_name = func_name;
11885
11886         return 0;
11887 }
11888
11889 static int check_return_code(struct bpf_verifier_env *env, int regno);
11890
11891 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11892                             int *insn_idx_p)
11893 {
11894         const struct btf_type *t, *ptr_type;
11895         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11896         struct bpf_reg_state *regs = cur_regs(env);
11897         const char *func_name, *ptr_type_name;
11898         bool sleepable, rcu_lock, rcu_unlock;
11899         struct bpf_kfunc_call_arg_meta meta;
11900         struct bpf_insn_aux_data *insn_aux;
11901         int err, insn_idx = *insn_idx_p;
11902         const struct btf_param *args;
11903         const struct btf_type *ret_t;
11904         struct btf *desc_btf;
11905
11906         /* skip for now, but return error when we find this in fixup_kfunc_call */
11907         if (!insn->imm)
11908                 return 0;
11909
11910         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11911         if (err == -EACCES && func_name)
11912                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11913         if (err)
11914                 return err;
11915         desc_btf = meta.btf;
11916         insn_aux = &env->insn_aux_data[insn_idx];
11917
11918         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11919
11920         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11921                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11922                 return -EACCES;
11923         }
11924
11925         sleepable = is_kfunc_sleepable(&meta);
11926         if (sleepable && !env->prog->aux->sleepable) {
11927                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11928                 return -EACCES;
11929         }
11930
11931         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11932         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11933
11934         if (env->cur_state->active_rcu_lock) {
11935                 struct bpf_func_state *state;
11936                 struct bpf_reg_state *reg;
11937                 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER);
11938
11939                 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11940                         verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11941                         return -EACCES;
11942                 }
11943
11944                 if (rcu_lock) {
11945                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11946                         return -EINVAL;
11947                 } else if (rcu_unlock) {
11948                         bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({
11949                                 if (reg->type & MEM_RCU) {
11950                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11951                                         reg->type |= PTR_UNTRUSTED;
11952                                 }
11953                         }));
11954                         env->cur_state->active_rcu_lock = false;
11955                 } else if (sleepable) {
11956                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11957                         return -EACCES;
11958                 }
11959         } else if (rcu_lock) {
11960                 env->cur_state->active_rcu_lock = true;
11961         } else if (rcu_unlock) {
11962                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11963                 return -EINVAL;
11964         }
11965
11966         /* Check the arguments */
11967         err = check_kfunc_args(env, &meta, insn_idx);
11968         if (err < 0)
11969                 return err;
11970         /* In case of release function, we get register number of refcounted
11971          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11972          */
11973         if (meta.release_regno) {
11974                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11975                 if (err) {
11976                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11977                                 func_name, meta.func_id);
11978                         return err;
11979                 }
11980         }
11981
11982         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11983             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11984             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11985                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11986                 insn_aux->insert_off = regs[BPF_REG_2].off;
11987                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11988                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11989                 if (err) {
11990                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11991                                 func_name, meta.func_id);
11992                         return err;
11993                 }
11994
11995                 err = release_reference(env, release_ref_obj_id);
11996                 if (err) {
11997                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11998                                 func_name, meta.func_id);
11999                         return err;
12000                 }
12001         }
12002
12003         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
12004                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
12005                                         set_rbtree_add_callback_state);
12006                 if (err) {
12007                         verbose(env, "kfunc %s#%d failed callback verification\n",
12008                                 func_name, meta.func_id);
12009                         return err;
12010                 }
12011         }
12012
12013         if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
12014                 if (!bpf_jit_supports_exceptions()) {
12015                         verbose(env, "JIT does not support calling kfunc %s#%d\n",
12016                                 func_name, meta.func_id);
12017                         return -ENOTSUPP;
12018                 }
12019                 env->seen_exception = true;
12020
12021                 /* In the case of the default callback, the cookie value passed
12022                  * to bpf_throw becomes the return value of the program.
12023                  */
12024                 if (!env->exception_callback_subprog) {
12025                         err = check_return_code(env, BPF_REG_1);
12026                         if (err < 0)
12027                                 return err;
12028                 }
12029         }
12030
12031         for (i = 0; i < CALLER_SAVED_REGS; i++)
12032                 mark_reg_not_init(env, regs, caller_saved[i]);
12033
12034         /* Check return type */
12035         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
12036
12037         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
12038                 /* Only exception is bpf_obj_new_impl */
12039                 if (meta.btf != btf_vmlinux ||
12040                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
12041                      meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] &&
12042                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
12043                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
12044                         return -EINVAL;
12045                 }
12046         }
12047
12048         if (btf_type_is_scalar(t)) {
12049                 mark_reg_unknown(env, regs, BPF_REG_0);
12050                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
12051         } else if (btf_type_is_ptr(t)) {
12052                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
12053
12054                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12055                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
12056                             meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12057                                 struct btf_struct_meta *struct_meta;
12058                                 struct btf *ret_btf;
12059                                 u32 ret_btf_id;
12060
12061                                 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set)
12062                                         return -ENOMEM;
12063
12064                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && !bpf_global_percpu_ma_set)
12065                                         return -ENOMEM;
12066
12067                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
12068                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
12069                                         return -EINVAL;
12070                                 }
12071
12072                                 ret_btf = env->prog->aux->btf;
12073                                 ret_btf_id = meta.arg_constant.value;
12074
12075                                 /* This may be NULL due to user not supplying a BTF */
12076                                 if (!ret_btf) {
12077                                         verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n");
12078                                         return -EINVAL;
12079                                 }
12080
12081                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
12082                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
12083                                         verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n");
12084                                         return -EINVAL;
12085                                 }
12086
12087                                 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id);
12088                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
12089                                         if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) {
12090                                                 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n");
12091                                                 return -EINVAL;
12092                                         }
12093
12094                                         if (struct_meta) {
12095                                                 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n");
12096                                                 return -EINVAL;
12097                                         }
12098                                 }
12099
12100                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12101                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12102                                 regs[BPF_REG_0].btf = ret_btf;
12103                                 regs[BPF_REG_0].btf_id = ret_btf_id;
12104                                 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl])
12105                                         regs[BPF_REG_0].type |= MEM_PERCPU;
12106
12107                                 insn_aux->obj_new_size = ret_t->size;
12108                                 insn_aux->kptr_struct_meta = struct_meta;
12109                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
12110                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12111                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
12112                                 regs[BPF_REG_0].btf = meta.arg_btf;
12113                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
12114
12115                                 insn_aux->kptr_struct_meta =
12116                                         btf_find_struct_meta(meta.arg_btf,
12117                                                              meta.arg_btf_id);
12118                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
12119                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
12120                                 struct btf_field *field = meta.arg_list_head.field;
12121
12122                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12123                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
12124                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12125                                 struct btf_field *field = meta.arg_rbtree_root.field;
12126
12127                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
12128                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
12129                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12130                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
12131                                 regs[BPF_REG_0].btf = desc_btf;
12132                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
12133                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
12134                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
12135                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
12136                                         verbose(env,
12137                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
12138                                         return -EINVAL;
12139                                 }
12140
12141                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12142                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
12143                                 regs[BPF_REG_0].btf = desc_btf;
12144                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
12145                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
12146                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
12147                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
12148
12149                                 mark_reg_known_zero(env, regs, BPF_REG_0);
12150
12151                                 if (!meta.arg_constant.found) {
12152                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
12153                                         return -EFAULT;
12154                                 }
12155
12156                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
12157
12158                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
12159                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
12160
12161                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
12162                                         regs[BPF_REG_0].type |= MEM_RDONLY;
12163                                 } else {
12164                                         /* this will set env->seen_direct_write to true */
12165                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
12166                                                 verbose(env, "the prog does not allow writes to packet data\n");
12167                                                 return -EINVAL;
12168                                         }
12169                                 }
12170
12171                                 if (!meta.initialized_dynptr.id) {
12172                                         verbose(env, "verifier internal error: no dynptr id\n");
12173                                         return -EFAULT;
12174                                 }
12175                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
12176
12177                                 /* we don't need to set BPF_REG_0's ref obj id
12178                                  * because packet slices are not refcounted (see
12179                                  * dynptr_type_refcounted)
12180                                  */
12181                         } else {
12182                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
12183                                         meta.func_name);
12184                                 return -EFAULT;
12185                         }
12186                 } else if (!__btf_type_is_struct(ptr_type)) {
12187                         if (!meta.r0_size) {
12188                                 __u32 sz;
12189
12190                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
12191                                         meta.r0_size = sz;
12192                                         meta.r0_rdonly = true;
12193                                 }
12194                         }
12195                         if (!meta.r0_size) {
12196                                 ptr_type_name = btf_name_by_offset(desc_btf,
12197                                                                    ptr_type->name_off);
12198                                 verbose(env,
12199                                         "kernel function %s returns pointer type %s %s is not supported\n",
12200                                         func_name,
12201                                         btf_type_str(ptr_type),
12202                                         ptr_type_name);
12203                                 return -EINVAL;
12204                         }
12205
12206                         mark_reg_known_zero(env, regs, BPF_REG_0);
12207                         regs[BPF_REG_0].type = PTR_TO_MEM;
12208                         regs[BPF_REG_0].mem_size = meta.r0_size;
12209
12210                         if (meta.r0_rdonly)
12211                                 regs[BPF_REG_0].type |= MEM_RDONLY;
12212
12213                         /* Ensures we don't access the memory after a release_reference() */
12214                         if (meta.ref_obj_id)
12215                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
12216                 } else {
12217                         mark_reg_known_zero(env, regs, BPF_REG_0);
12218                         regs[BPF_REG_0].btf = desc_btf;
12219                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
12220                         regs[BPF_REG_0].btf_id = ptr_type_id;
12221                 }
12222
12223                 if (is_kfunc_ret_null(&meta)) {
12224                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
12225                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
12226                         regs[BPF_REG_0].id = ++env->id_gen;
12227                 }
12228                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
12229                 if (is_kfunc_acquire(&meta)) {
12230                         int id = acquire_reference_state(env, insn_idx);
12231
12232                         if (id < 0)
12233                                 return id;
12234                         if (is_kfunc_ret_null(&meta))
12235                                 regs[BPF_REG_0].id = id;
12236                         regs[BPF_REG_0].ref_obj_id = id;
12237                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
12238                         ref_set_non_owning(env, &regs[BPF_REG_0]);
12239                 }
12240
12241                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
12242                         regs[BPF_REG_0].id = ++env->id_gen;
12243         } else if (btf_type_is_void(t)) {
12244                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
12245                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
12246                             meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) {
12247                                 insn_aux->kptr_struct_meta =
12248                                         btf_find_struct_meta(meta.arg_btf,
12249                                                              meta.arg_btf_id);
12250                         }
12251                 }
12252         }
12253
12254         nargs = btf_type_vlen(meta.func_proto);
12255         args = (const struct btf_param *)(meta.func_proto + 1);
12256         for (i = 0; i < nargs; i++) {
12257                 u32 regno = i + 1;
12258
12259                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
12260                 if (btf_type_is_ptr(t))
12261                         mark_btf_func_reg_size(env, regno, sizeof(void *));
12262                 else
12263                         /* scalar. ensured by btf_check_kfunc_arg_match() */
12264                         mark_btf_func_reg_size(env, regno, t->size);
12265         }
12266
12267         if (is_iter_next_kfunc(&meta)) {
12268                 err = process_iter_next_call(env, insn_idx, &meta);
12269                 if (err)
12270                         return err;
12271         }
12272
12273         return 0;
12274 }
12275
12276 static bool signed_add_overflows(s64 a, s64 b)
12277 {
12278         /* Do the add in u64, where overflow is well-defined */
12279         s64 res = (s64)((u64)a + (u64)b);
12280
12281         if (b < 0)
12282                 return res > a;
12283         return res < a;
12284 }
12285
12286 static bool signed_add32_overflows(s32 a, s32 b)
12287 {
12288         /* Do the add in u32, where overflow is well-defined */
12289         s32 res = (s32)((u32)a + (u32)b);
12290
12291         if (b < 0)
12292                 return res > a;
12293         return res < a;
12294 }
12295
12296 static bool signed_sub_overflows(s64 a, s64 b)
12297 {
12298         /* Do the sub in u64, where overflow is well-defined */
12299         s64 res = (s64)((u64)a - (u64)b);
12300
12301         if (b < 0)
12302                 return res < a;
12303         return res > a;
12304 }
12305
12306 static bool signed_sub32_overflows(s32 a, s32 b)
12307 {
12308         /* Do the sub in u32, where overflow is well-defined */
12309         s32 res = (s32)((u32)a - (u32)b);
12310
12311         if (b < 0)
12312                 return res < a;
12313         return res > a;
12314 }
12315
12316 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
12317                                   const struct bpf_reg_state *reg,
12318                                   enum bpf_reg_type type)
12319 {
12320         bool known = tnum_is_const(reg->var_off);
12321         s64 val = reg->var_off.value;
12322         s64 smin = reg->smin_value;
12323
12324         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
12325                 verbose(env, "math between %s pointer and %lld is not allowed\n",
12326                         reg_type_str(env, type), val);
12327                 return false;
12328         }
12329
12330         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
12331                 verbose(env, "%s pointer offset %d is not allowed\n",
12332                         reg_type_str(env, type), reg->off);
12333                 return false;
12334         }
12335
12336         if (smin == S64_MIN) {
12337                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
12338                         reg_type_str(env, type));
12339                 return false;
12340         }
12341
12342         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
12343                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
12344                         smin, reg_type_str(env, type));
12345                 return false;
12346         }
12347
12348         return true;
12349 }
12350
12351 enum {
12352         REASON_BOUNDS   = -1,
12353         REASON_TYPE     = -2,
12354         REASON_PATHS    = -3,
12355         REASON_LIMIT    = -4,
12356         REASON_STACK    = -5,
12357 };
12358
12359 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
12360                               u32 *alu_limit, bool mask_to_left)
12361 {
12362         u32 max = 0, ptr_limit = 0;
12363
12364         switch (ptr_reg->type) {
12365         case PTR_TO_STACK:
12366                 /* Offset 0 is out-of-bounds, but acceptable start for the
12367                  * left direction, see BPF_REG_FP. Also, unknown scalar
12368                  * offset where we would need to deal with min/max bounds is
12369                  * currently prohibited for unprivileged.
12370                  */
12371                 max = MAX_BPF_STACK + mask_to_left;
12372                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
12373                 break;
12374         case PTR_TO_MAP_VALUE:
12375                 max = ptr_reg->map_ptr->value_size;
12376                 ptr_limit = (mask_to_left ?
12377                              ptr_reg->smin_value :
12378                              ptr_reg->umax_value) + ptr_reg->off;
12379                 break;
12380         default:
12381                 return REASON_TYPE;
12382         }
12383
12384         if (ptr_limit >= max)
12385                 return REASON_LIMIT;
12386         *alu_limit = ptr_limit;
12387         return 0;
12388 }
12389
12390 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
12391                                     const struct bpf_insn *insn)
12392 {
12393         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
12394 }
12395
12396 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
12397                                        u32 alu_state, u32 alu_limit)
12398 {
12399         /* If we arrived here from different branches with different
12400          * state or limits to sanitize, then this won't work.
12401          */
12402         if (aux->alu_state &&
12403             (aux->alu_state != alu_state ||
12404              aux->alu_limit != alu_limit))
12405                 return REASON_PATHS;
12406
12407         /* Corresponding fixup done in do_misc_fixups(). */
12408         aux->alu_state = alu_state;
12409         aux->alu_limit = alu_limit;
12410         return 0;
12411 }
12412
12413 static int sanitize_val_alu(struct bpf_verifier_env *env,
12414                             struct bpf_insn *insn)
12415 {
12416         struct bpf_insn_aux_data *aux = cur_aux(env);
12417
12418         if (can_skip_alu_sanitation(env, insn))
12419                 return 0;
12420
12421         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
12422 }
12423
12424 static bool sanitize_needed(u8 opcode)
12425 {
12426         return opcode == BPF_ADD || opcode == BPF_SUB;
12427 }
12428
12429 struct bpf_sanitize_info {
12430         struct bpf_insn_aux_data aux;
12431         bool mask_to_left;
12432 };
12433
12434 static struct bpf_verifier_state *
12435 sanitize_speculative_path(struct bpf_verifier_env *env,
12436                           const struct bpf_insn *insn,
12437                           u32 next_idx, u32 curr_idx)
12438 {
12439         struct bpf_verifier_state *branch;
12440         struct bpf_reg_state *regs;
12441
12442         branch = push_stack(env, next_idx, curr_idx, true);
12443         if (branch && insn) {
12444                 regs = branch->frame[branch->curframe]->regs;
12445                 if (BPF_SRC(insn->code) == BPF_K) {
12446                         mark_reg_unknown(env, regs, insn->dst_reg);
12447                 } else if (BPF_SRC(insn->code) == BPF_X) {
12448                         mark_reg_unknown(env, regs, insn->dst_reg);
12449                         mark_reg_unknown(env, regs, insn->src_reg);
12450                 }
12451         }
12452         return branch;
12453 }
12454
12455 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
12456                             struct bpf_insn *insn,
12457                             const struct bpf_reg_state *ptr_reg,
12458                             const struct bpf_reg_state *off_reg,
12459                             struct bpf_reg_state *dst_reg,
12460                             struct bpf_sanitize_info *info,
12461                             const bool commit_window)
12462 {
12463         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
12464         struct bpf_verifier_state *vstate = env->cur_state;
12465         bool off_is_imm = tnum_is_const(off_reg->var_off);
12466         bool off_is_neg = off_reg->smin_value < 0;
12467         bool ptr_is_dst_reg = ptr_reg == dst_reg;
12468         u8 opcode = BPF_OP(insn->code);
12469         u32 alu_state, alu_limit;
12470         struct bpf_reg_state tmp;
12471         bool ret;
12472         int err;
12473
12474         if (can_skip_alu_sanitation(env, insn))
12475                 return 0;
12476
12477         /* We already marked aux for masking from non-speculative
12478          * paths, thus we got here in the first place. We only care
12479          * to explore bad access from here.
12480          */
12481         if (vstate->speculative)
12482                 goto do_sim;
12483
12484         if (!commit_window) {
12485                 if (!tnum_is_const(off_reg->var_off) &&
12486                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
12487                         return REASON_BOUNDS;
12488
12489                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
12490                                      (opcode == BPF_SUB && !off_is_neg);
12491         }
12492
12493         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
12494         if (err < 0)
12495                 return err;
12496
12497         if (commit_window) {
12498                 /* In commit phase we narrow the masking window based on
12499                  * the observed pointer move after the simulated operation.
12500                  */
12501                 alu_state = info->aux.alu_state;
12502                 alu_limit = abs(info->aux.alu_limit - alu_limit);
12503         } else {
12504                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
12505                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
12506                 alu_state |= ptr_is_dst_reg ?
12507                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
12508
12509                 /* Limit pruning on unknown scalars to enable deep search for
12510                  * potential masking differences from other program paths.
12511                  */
12512                 if (!off_is_imm)
12513                         env->explore_alu_limits = true;
12514         }
12515
12516         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
12517         if (err < 0)
12518                 return err;
12519 do_sim:
12520         /* If we're in commit phase, we're done here given we already
12521          * pushed the truncated dst_reg into the speculative verification
12522          * stack.
12523          *
12524          * Also, when register is a known constant, we rewrite register-based
12525          * operation to immediate-based, and thus do not need masking (and as
12526          * a consequence, do not need to simulate the zero-truncation either).
12527          */
12528         if (commit_window || off_is_imm)
12529                 return 0;
12530
12531         /* Simulate and find potential out-of-bounds access under
12532          * speculative execution from truncation as a result of
12533          * masking when off was not within expected range. If off
12534          * sits in dst, then we temporarily need to move ptr there
12535          * to simulate dst (== 0) +/-= ptr. Needed, for example,
12536          * for cases where we use K-based arithmetic in one direction
12537          * and truncated reg-based in the other in order to explore
12538          * bad access.
12539          */
12540         if (!ptr_is_dst_reg) {
12541                 tmp = *dst_reg;
12542                 copy_register_state(dst_reg, ptr_reg);
12543         }
12544         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
12545                                         env->insn_idx);
12546         if (!ptr_is_dst_reg && ret)
12547                 *dst_reg = tmp;
12548         return !ret ? REASON_STACK : 0;
12549 }
12550
12551 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
12552 {
12553         struct bpf_verifier_state *vstate = env->cur_state;
12554
12555         /* If we simulate paths under speculation, we don't update the
12556          * insn as 'seen' such that when we verify unreachable paths in
12557          * the non-speculative domain, sanitize_dead_code() can still
12558          * rewrite/sanitize them.
12559          */
12560         if (!vstate->speculative)
12561                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
12562 }
12563
12564 static int sanitize_err(struct bpf_verifier_env *env,
12565                         const struct bpf_insn *insn, int reason,
12566                         const struct bpf_reg_state *off_reg,
12567                         const struct bpf_reg_state *dst_reg)
12568 {
12569         static const char *err = "pointer arithmetic with it prohibited for !root";
12570         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
12571         u32 dst = insn->dst_reg, src = insn->src_reg;
12572
12573         switch (reason) {
12574         case REASON_BOUNDS:
12575                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
12576                         off_reg == dst_reg ? dst : src, err);
12577                 break;
12578         case REASON_TYPE:
12579                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
12580                         off_reg == dst_reg ? src : dst, err);
12581                 break;
12582         case REASON_PATHS:
12583                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
12584                         dst, op, err);
12585                 break;
12586         case REASON_LIMIT:
12587                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
12588                         dst, op, err);
12589                 break;
12590         case REASON_STACK:
12591                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
12592                         dst, err);
12593                 break;
12594         default:
12595                 verbose(env, "verifier internal error: unknown reason (%d)\n",
12596                         reason);
12597                 break;
12598         }
12599
12600         return -EACCES;
12601 }
12602
12603 /* check that stack access falls within stack limits and that 'reg' doesn't
12604  * have a variable offset.
12605  *
12606  * Variable offset is prohibited for unprivileged mode for simplicity since it
12607  * requires corresponding support in Spectre masking for stack ALU.  See also
12608  * retrieve_ptr_limit().
12609  *
12610  *
12611  * 'off' includes 'reg->off'.
12612  */
12613 static int check_stack_access_for_ptr_arithmetic(
12614                                 struct bpf_verifier_env *env,
12615                                 int regno,
12616                                 const struct bpf_reg_state *reg,
12617                                 int off)
12618 {
12619         if (!tnum_is_const(reg->var_off)) {
12620                 char tn_buf[48];
12621
12622                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12623                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12624                         regno, tn_buf, off);
12625                 return -EACCES;
12626         }
12627
12628         if (off >= 0 || off < -MAX_BPF_STACK) {
12629                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12630                         "prohibited for !root; off=%d\n", regno, off);
12631                 return -EACCES;
12632         }
12633
12634         return 0;
12635 }
12636
12637 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12638                                  const struct bpf_insn *insn,
12639                                  const struct bpf_reg_state *dst_reg)
12640 {
12641         u32 dst = insn->dst_reg;
12642
12643         /* For unprivileged we require that resulting offset must be in bounds
12644          * in order to be able to sanitize access later on.
12645          */
12646         if (env->bypass_spec_v1)
12647                 return 0;
12648
12649         switch (dst_reg->type) {
12650         case PTR_TO_STACK:
12651                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12652                                         dst_reg->off + dst_reg->var_off.value))
12653                         return -EACCES;
12654                 break;
12655         case PTR_TO_MAP_VALUE:
12656                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12657                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12658                                 "prohibited for !root\n", dst);
12659                         return -EACCES;
12660                 }
12661                 break;
12662         default:
12663                 break;
12664         }
12665
12666         return 0;
12667 }
12668
12669 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12670  * Caller should also handle BPF_MOV case separately.
12671  * If we return -EACCES, caller may want to try again treating pointer as a
12672  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12673  */
12674 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12675                                    struct bpf_insn *insn,
12676                                    const struct bpf_reg_state *ptr_reg,
12677                                    const struct bpf_reg_state *off_reg)
12678 {
12679         struct bpf_verifier_state *vstate = env->cur_state;
12680         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12681         struct bpf_reg_state *regs = state->regs, *dst_reg;
12682         bool known = tnum_is_const(off_reg->var_off);
12683         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12684             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12685         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12686             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12687         struct bpf_sanitize_info info = {};
12688         u8 opcode = BPF_OP(insn->code);
12689         u32 dst = insn->dst_reg;
12690         int ret;
12691
12692         dst_reg = &regs[dst];
12693
12694         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12695             smin_val > smax_val || umin_val > umax_val) {
12696                 /* Taint dst register if offset had invalid bounds derived from
12697                  * e.g. dead branches.
12698                  */
12699                 __mark_reg_unknown(env, dst_reg);
12700                 return 0;
12701         }
12702
12703         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12704                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12705                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12706                         __mark_reg_unknown(env, dst_reg);
12707                         return 0;
12708                 }
12709
12710                 verbose(env,
12711                         "R%d 32-bit pointer arithmetic prohibited\n",
12712                         dst);
12713                 return -EACCES;
12714         }
12715
12716         if (ptr_reg->type & PTR_MAYBE_NULL) {
12717                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12718                         dst, reg_type_str(env, ptr_reg->type));
12719                 return -EACCES;
12720         }
12721
12722         switch (base_type(ptr_reg->type)) {
12723         case CONST_PTR_TO_MAP:
12724                 /* smin_val represents the known value */
12725                 if (known && smin_val == 0 && opcode == BPF_ADD)
12726                         break;
12727                 fallthrough;
12728         case PTR_TO_PACKET_END:
12729         case PTR_TO_SOCKET:
12730         case PTR_TO_SOCK_COMMON:
12731         case PTR_TO_TCP_SOCK:
12732         case PTR_TO_XDP_SOCK:
12733                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12734                         dst, reg_type_str(env, ptr_reg->type));
12735                 return -EACCES;
12736         default:
12737                 break;
12738         }
12739
12740         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12741          * The id may be overwritten later if we create a new variable offset.
12742          */
12743         dst_reg->type = ptr_reg->type;
12744         dst_reg->id = ptr_reg->id;
12745
12746         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12747             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12748                 return -EINVAL;
12749
12750         /* pointer types do not carry 32-bit bounds at the moment. */
12751         __mark_reg32_unbounded(dst_reg);
12752
12753         if (sanitize_needed(opcode)) {
12754                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12755                                        &info, false);
12756                 if (ret < 0)
12757                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12758         }
12759
12760         switch (opcode) {
12761         case BPF_ADD:
12762                 /* We can take a fixed offset as long as it doesn't overflow
12763                  * the s32 'off' field
12764                  */
12765                 if (known && (ptr_reg->off + smin_val ==
12766                               (s64)(s32)(ptr_reg->off + smin_val))) {
12767                         /* pointer += K.  Accumulate it into fixed offset */
12768                         dst_reg->smin_value = smin_ptr;
12769                         dst_reg->smax_value = smax_ptr;
12770                         dst_reg->umin_value = umin_ptr;
12771                         dst_reg->umax_value = umax_ptr;
12772                         dst_reg->var_off = ptr_reg->var_off;
12773                         dst_reg->off = ptr_reg->off + smin_val;
12774                         dst_reg->raw = ptr_reg->raw;
12775                         break;
12776                 }
12777                 /* A new variable offset is created.  Note that off_reg->off
12778                  * == 0, since it's a scalar.
12779                  * dst_reg gets the pointer type and since some positive
12780                  * integer value was added to the pointer, give it a new 'id'
12781                  * if it's a PTR_TO_PACKET.
12782                  * this creates a new 'base' pointer, off_reg (variable) gets
12783                  * added into the variable offset, and we copy the fixed offset
12784                  * from ptr_reg.
12785                  */
12786                 if (signed_add_overflows(smin_ptr, smin_val) ||
12787                     signed_add_overflows(smax_ptr, smax_val)) {
12788                         dst_reg->smin_value = S64_MIN;
12789                         dst_reg->smax_value = S64_MAX;
12790                 } else {
12791                         dst_reg->smin_value = smin_ptr + smin_val;
12792                         dst_reg->smax_value = smax_ptr + smax_val;
12793                 }
12794                 if (umin_ptr + umin_val < umin_ptr ||
12795                     umax_ptr + umax_val < umax_ptr) {
12796                         dst_reg->umin_value = 0;
12797                         dst_reg->umax_value = U64_MAX;
12798                 } else {
12799                         dst_reg->umin_value = umin_ptr + umin_val;
12800                         dst_reg->umax_value = umax_ptr + umax_val;
12801                 }
12802                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12803                 dst_reg->off = ptr_reg->off;
12804                 dst_reg->raw = ptr_reg->raw;
12805                 if (reg_is_pkt_pointer(ptr_reg)) {
12806                         dst_reg->id = ++env->id_gen;
12807                         /* something was added to pkt_ptr, set range to zero */
12808                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12809                 }
12810                 break;
12811         case BPF_SUB:
12812                 if (dst_reg == off_reg) {
12813                         /* scalar -= pointer.  Creates an unknown scalar */
12814                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12815                                 dst);
12816                         return -EACCES;
12817                 }
12818                 /* We don't allow subtraction from FP, because (according to
12819                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12820                  * be able to deal with it.
12821                  */
12822                 if (ptr_reg->type == PTR_TO_STACK) {
12823                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12824                                 dst);
12825                         return -EACCES;
12826                 }
12827                 if (known && (ptr_reg->off - smin_val ==
12828                               (s64)(s32)(ptr_reg->off - smin_val))) {
12829                         /* pointer -= K.  Subtract it from fixed offset */
12830                         dst_reg->smin_value = smin_ptr;
12831                         dst_reg->smax_value = smax_ptr;
12832                         dst_reg->umin_value = umin_ptr;
12833                         dst_reg->umax_value = umax_ptr;
12834                         dst_reg->var_off = ptr_reg->var_off;
12835                         dst_reg->id = ptr_reg->id;
12836                         dst_reg->off = ptr_reg->off - smin_val;
12837                         dst_reg->raw = ptr_reg->raw;
12838                         break;
12839                 }
12840                 /* A new variable offset is created.  If the subtrahend is known
12841                  * nonnegative, then any reg->range we had before is still good.
12842                  */
12843                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12844                     signed_sub_overflows(smax_ptr, smin_val)) {
12845                         /* Overflow possible, we know nothing */
12846                         dst_reg->smin_value = S64_MIN;
12847                         dst_reg->smax_value = S64_MAX;
12848                 } else {
12849                         dst_reg->smin_value = smin_ptr - smax_val;
12850                         dst_reg->smax_value = smax_ptr - smin_val;
12851                 }
12852                 if (umin_ptr < umax_val) {
12853                         /* Overflow possible, we know nothing */
12854                         dst_reg->umin_value = 0;
12855                         dst_reg->umax_value = U64_MAX;
12856                 } else {
12857                         /* Cannot overflow (as long as bounds are consistent) */
12858                         dst_reg->umin_value = umin_ptr - umax_val;
12859                         dst_reg->umax_value = umax_ptr - umin_val;
12860                 }
12861                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12862                 dst_reg->off = ptr_reg->off;
12863                 dst_reg->raw = ptr_reg->raw;
12864                 if (reg_is_pkt_pointer(ptr_reg)) {
12865                         dst_reg->id = ++env->id_gen;
12866                         /* something was added to pkt_ptr, set range to zero */
12867                         if (smin_val < 0)
12868                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12869                 }
12870                 break;
12871         case BPF_AND:
12872         case BPF_OR:
12873         case BPF_XOR:
12874                 /* bitwise ops on pointers are troublesome, prohibit. */
12875                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12876                         dst, bpf_alu_string[opcode >> 4]);
12877                 return -EACCES;
12878         default:
12879                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12880                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12881                         dst, bpf_alu_string[opcode >> 4]);
12882                 return -EACCES;
12883         }
12884
12885         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12886                 return -EINVAL;
12887         reg_bounds_sync(dst_reg);
12888         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12889                 return -EACCES;
12890         if (sanitize_needed(opcode)) {
12891                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12892                                        &info, true);
12893                 if (ret < 0)
12894                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12895         }
12896
12897         return 0;
12898 }
12899
12900 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12901                                  struct bpf_reg_state *src_reg)
12902 {
12903         s32 smin_val = src_reg->s32_min_value;
12904         s32 smax_val = src_reg->s32_max_value;
12905         u32 umin_val = src_reg->u32_min_value;
12906         u32 umax_val = src_reg->u32_max_value;
12907
12908         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12909             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12910                 dst_reg->s32_min_value = S32_MIN;
12911                 dst_reg->s32_max_value = S32_MAX;
12912         } else {
12913                 dst_reg->s32_min_value += smin_val;
12914                 dst_reg->s32_max_value += smax_val;
12915         }
12916         if (dst_reg->u32_min_value + umin_val < umin_val ||
12917             dst_reg->u32_max_value + umax_val < umax_val) {
12918                 dst_reg->u32_min_value = 0;
12919                 dst_reg->u32_max_value = U32_MAX;
12920         } else {
12921                 dst_reg->u32_min_value += umin_val;
12922                 dst_reg->u32_max_value += umax_val;
12923         }
12924 }
12925
12926 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12927                                struct bpf_reg_state *src_reg)
12928 {
12929         s64 smin_val = src_reg->smin_value;
12930         s64 smax_val = src_reg->smax_value;
12931         u64 umin_val = src_reg->umin_value;
12932         u64 umax_val = src_reg->umax_value;
12933
12934         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12935             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12936                 dst_reg->smin_value = S64_MIN;
12937                 dst_reg->smax_value = S64_MAX;
12938         } else {
12939                 dst_reg->smin_value += smin_val;
12940                 dst_reg->smax_value += smax_val;
12941         }
12942         if (dst_reg->umin_value + umin_val < umin_val ||
12943             dst_reg->umax_value + umax_val < umax_val) {
12944                 dst_reg->umin_value = 0;
12945                 dst_reg->umax_value = U64_MAX;
12946         } else {
12947                 dst_reg->umin_value += umin_val;
12948                 dst_reg->umax_value += umax_val;
12949         }
12950 }
12951
12952 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12953                                  struct bpf_reg_state *src_reg)
12954 {
12955         s32 smin_val = src_reg->s32_min_value;
12956         s32 smax_val = src_reg->s32_max_value;
12957         u32 umin_val = src_reg->u32_min_value;
12958         u32 umax_val = src_reg->u32_max_value;
12959
12960         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12961             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12962                 /* Overflow possible, we know nothing */
12963                 dst_reg->s32_min_value = S32_MIN;
12964                 dst_reg->s32_max_value = S32_MAX;
12965         } else {
12966                 dst_reg->s32_min_value -= smax_val;
12967                 dst_reg->s32_max_value -= smin_val;
12968         }
12969         if (dst_reg->u32_min_value < umax_val) {
12970                 /* Overflow possible, we know nothing */
12971                 dst_reg->u32_min_value = 0;
12972                 dst_reg->u32_max_value = U32_MAX;
12973         } else {
12974                 /* Cannot overflow (as long as bounds are consistent) */
12975                 dst_reg->u32_min_value -= umax_val;
12976                 dst_reg->u32_max_value -= umin_val;
12977         }
12978 }
12979
12980 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12981                                struct bpf_reg_state *src_reg)
12982 {
12983         s64 smin_val = src_reg->smin_value;
12984         s64 smax_val = src_reg->smax_value;
12985         u64 umin_val = src_reg->umin_value;
12986         u64 umax_val = src_reg->umax_value;
12987
12988         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12989             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12990                 /* Overflow possible, we know nothing */
12991                 dst_reg->smin_value = S64_MIN;
12992                 dst_reg->smax_value = S64_MAX;
12993         } else {
12994                 dst_reg->smin_value -= smax_val;
12995                 dst_reg->smax_value -= smin_val;
12996         }
12997         if (dst_reg->umin_value < umax_val) {
12998                 /* Overflow possible, we know nothing */
12999                 dst_reg->umin_value = 0;
13000                 dst_reg->umax_value = U64_MAX;
13001         } else {
13002                 /* Cannot overflow (as long as bounds are consistent) */
13003                 dst_reg->umin_value -= umax_val;
13004                 dst_reg->umax_value -= umin_val;
13005         }
13006 }
13007
13008 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
13009                                  struct bpf_reg_state *src_reg)
13010 {
13011         s32 smin_val = src_reg->s32_min_value;
13012         u32 umin_val = src_reg->u32_min_value;
13013         u32 umax_val = src_reg->u32_max_value;
13014
13015         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
13016                 /* Ain't nobody got time to multiply that sign */
13017                 __mark_reg32_unbounded(dst_reg);
13018                 return;
13019         }
13020         /* Both values are positive, so we can work with unsigned and
13021          * copy the result to signed (unless it exceeds S32_MAX).
13022          */
13023         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
13024                 /* Potential overflow, we know nothing */
13025                 __mark_reg32_unbounded(dst_reg);
13026                 return;
13027         }
13028         dst_reg->u32_min_value *= umin_val;
13029         dst_reg->u32_max_value *= umax_val;
13030         if (dst_reg->u32_max_value > S32_MAX) {
13031                 /* Overflow possible, we know nothing */
13032                 dst_reg->s32_min_value = S32_MIN;
13033                 dst_reg->s32_max_value = S32_MAX;
13034         } else {
13035                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13036                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13037         }
13038 }
13039
13040 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
13041                                struct bpf_reg_state *src_reg)
13042 {
13043         s64 smin_val = src_reg->smin_value;
13044         u64 umin_val = src_reg->umin_value;
13045         u64 umax_val = src_reg->umax_value;
13046
13047         if (smin_val < 0 || dst_reg->smin_value < 0) {
13048                 /* Ain't nobody got time to multiply that sign */
13049                 __mark_reg64_unbounded(dst_reg);
13050                 return;
13051         }
13052         /* Both values are positive, so we can work with unsigned and
13053          * copy the result to signed (unless it exceeds S64_MAX).
13054          */
13055         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
13056                 /* Potential overflow, we know nothing */
13057                 __mark_reg64_unbounded(dst_reg);
13058                 return;
13059         }
13060         dst_reg->umin_value *= umin_val;
13061         dst_reg->umax_value *= umax_val;
13062         if (dst_reg->umax_value > S64_MAX) {
13063                 /* Overflow possible, we know nothing */
13064                 dst_reg->smin_value = S64_MIN;
13065                 dst_reg->smax_value = S64_MAX;
13066         } else {
13067                 dst_reg->smin_value = dst_reg->umin_value;
13068                 dst_reg->smax_value = dst_reg->umax_value;
13069         }
13070 }
13071
13072 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
13073                                  struct bpf_reg_state *src_reg)
13074 {
13075         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13076         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13077         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13078         s32 smin_val = src_reg->s32_min_value;
13079         u32 umax_val = src_reg->u32_max_value;
13080
13081         if (src_known && dst_known) {
13082                 __mark_reg32_known(dst_reg, var32_off.value);
13083                 return;
13084         }
13085
13086         /* We get our minimum from the var_off, since that's inherently
13087          * bitwise.  Our maximum is the minimum of the operands' maxima.
13088          */
13089         dst_reg->u32_min_value = var32_off.value;
13090         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
13091         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13092                 /* Lose signed bounds when ANDing negative numbers,
13093                  * ain't nobody got time for that.
13094                  */
13095                 dst_reg->s32_min_value = S32_MIN;
13096                 dst_reg->s32_max_value = S32_MAX;
13097         } else {
13098                 /* ANDing two positives gives a positive, so safe to
13099                  * cast result into s64.
13100                  */
13101                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13102                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13103         }
13104 }
13105
13106 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
13107                                struct bpf_reg_state *src_reg)
13108 {
13109         bool src_known = tnum_is_const(src_reg->var_off);
13110         bool dst_known = tnum_is_const(dst_reg->var_off);
13111         s64 smin_val = src_reg->smin_value;
13112         u64 umax_val = src_reg->umax_value;
13113
13114         if (src_known && dst_known) {
13115                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13116                 return;
13117         }
13118
13119         /* We get our minimum from the var_off, since that's inherently
13120          * bitwise.  Our maximum is the minimum of the operands' maxima.
13121          */
13122         dst_reg->umin_value = dst_reg->var_off.value;
13123         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
13124         if (dst_reg->smin_value < 0 || smin_val < 0) {
13125                 /* Lose signed bounds when ANDing negative numbers,
13126                  * ain't nobody got time for that.
13127                  */
13128                 dst_reg->smin_value = S64_MIN;
13129                 dst_reg->smax_value = S64_MAX;
13130         } else {
13131                 /* ANDing two positives gives a positive, so safe to
13132                  * cast result into s64.
13133                  */
13134                 dst_reg->smin_value = dst_reg->umin_value;
13135                 dst_reg->smax_value = dst_reg->umax_value;
13136         }
13137         /* We may learn something more from the var_off */
13138         __update_reg_bounds(dst_reg);
13139 }
13140
13141 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
13142                                 struct bpf_reg_state *src_reg)
13143 {
13144         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13145         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13146         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13147         s32 smin_val = src_reg->s32_min_value;
13148         u32 umin_val = src_reg->u32_min_value;
13149
13150         if (src_known && dst_known) {
13151                 __mark_reg32_known(dst_reg, var32_off.value);
13152                 return;
13153         }
13154
13155         /* We get our maximum from the var_off, and our minimum is the
13156          * maximum of the operands' minima
13157          */
13158         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
13159         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13160         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
13161                 /* Lose signed bounds when ORing negative numbers,
13162                  * ain't nobody got time for that.
13163                  */
13164                 dst_reg->s32_min_value = S32_MIN;
13165                 dst_reg->s32_max_value = S32_MAX;
13166         } else {
13167                 /* ORing two positives gives a positive, so safe to
13168                  * cast result into s64.
13169                  */
13170                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13171                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13172         }
13173 }
13174
13175 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
13176                               struct bpf_reg_state *src_reg)
13177 {
13178         bool src_known = tnum_is_const(src_reg->var_off);
13179         bool dst_known = tnum_is_const(dst_reg->var_off);
13180         s64 smin_val = src_reg->smin_value;
13181         u64 umin_val = src_reg->umin_value;
13182
13183         if (src_known && dst_known) {
13184                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13185                 return;
13186         }
13187
13188         /* We get our maximum from the var_off, and our minimum is the
13189          * maximum of the operands' minima
13190          */
13191         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
13192         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13193         if (dst_reg->smin_value < 0 || smin_val < 0) {
13194                 /* Lose signed bounds when ORing negative numbers,
13195                  * ain't nobody got time for that.
13196                  */
13197                 dst_reg->smin_value = S64_MIN;
13198                 dst_reg->smax_value = S64_MAX;
13199         } else {
13200                 /* ORing two positives gives a positive, so safe to
13201                  * cast result into s64.
13202                  */
13203                 dst_reg->smin_value = dst_reg->umin_value;
13204                 dst_reg->smax_value = dst_reg->umax_value;
13205         }
13206         /* We may learn something more from the var_off */
13207         __update_reg_bounds(dst_reg);
13208 }
13209
13210 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
13211                                  struct bpf_reg_state *src_reg)
13212 {
13213         bool src_known = tnum_subreg_is_const(src_reg->var_off);
13214         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
13215         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
13216         s32 smin_val = src_reg->s32_min_value;
13217
13218         if (src_known && dst_known) {
13219                 __mark_reg32_known(dst_reg, var32_off.value);
13220                 return;
13221         }
13222
13223         /* We get both minimum and maximum from the var32_off. */
13224         dst_reg->u32_min_value = var32_off.value;
13225         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
13226
13227         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
13228                 /* XORing two positive sign numbers gives a positive,
13229                  * so safe to cast u32 result into s32.
13230                  */
13231                 dst_reg->s32_min_value = dst_reg->u32_min_value;
13232                 dst_reg->s32_max_value = dst_reg->u32_max_value;
13233         } else {
13234                 dst_reg->s32_min_value = S32_MIN;
13235                 dst_reg->s32_max_value = S32_MAX;
13236         }
13237 }
13238
13239 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
13240                                struct bpf_reg_state *src_reg)
13241 {
13242         bool src_known = tnum_is_const(src_reg->var_off);
13243         bool dst_known = tnum_is_const(dst_reg->var_off);
13244         s64 smin_val = src_reg->smin_value;
13245
13246         if (src_known && dst_known) {
13247                 /* dst_reg->var_off.value has been updated earlier */
13248                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
13249                 return;
13250         }
13251
13252         /* We get both minimum and maximum from the var_off. */
13253         dst_reg->umin_value = dst_reg->var_off.value;
13254         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
13255
13256         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
13257                 /* XORing two positive sign numbers gives a positive,
13258                  * so safe to cast u64 result into s64.
13259                  */
13260                 dst_reg->smin_value = dst_reg->umin_value;
13261                 dst_reg->smax_value = dst_reg->umax_value;
13262         } else {
13263                 dst_reg->smin_value = S64_MIN;
13264                 dst_reg->smax_value = S64_MAX;
13265         }
13266
13267         __update_reg_bounds(dst_reg);
13268 }
13269
13270 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13271                                    u64 umin_val, u64 umax_val)
13272 {
13273         /* We lose all sign bit information (except what we can pick
13274          * up from var_off)
13275          */
13276         dst_reg->s32_min_value = S32_MIN;
13277         dst_reg->s32_max_value = S32_MAX;
13278         /* If we might shift our top bit out, then we know nothing */
13279         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
13280                 dst_reg->u32_min_value = 0;
13281                 dst_reg->u32_max_value = U32_MAX;
13282         } else {
13283                 dst_reg->u32_min_value <<= umin_val;
13284                 dst_reg->u32_max_value <<= umax_val;
13285         }
13286 }
13287
13288 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
13289                                  struct bpf_reg_state *src_reg)
13290 {
13291         u32 umax_val = src_reg->u32_max_value;
13292         u32 umin_val = src_reg->u32_min_value;
13293         /* u32 alu operation will zext upper bits */
13294         struct tnum subreg = tnum_subreg(dst_reg->var_off);
13295
13296         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13297         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
13298         /* Not required but being careful mark reg64 bounds as unknown so
13299          * that we are forced to pick them up from tnum and zext later and
13300          * if some path skips this step we are still safe.
13301          */
13302         __mark_reg64_unbounded(dst_reg);
13303         __update_reg32_bounds(dst_reg);
13304 }
13305
13306 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
13307                                    u64 umin_val, u64 umax_val)
13308 {
13309         /* Special case <<32 because it is a common compiler pattern to sign
13310          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
13311          * positive we know this shift will also be positive so we can track
13312          * bounds correctly. Otherwise we lose all sign bit information except
13313          * what we can pick up from var_off. Perhaps we can generalize this
13314          * later to shifts of any length.
13315          */
13316         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
13317                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
13318         else
13319                 dst_reg->smax_value = S64_MAX;
13320
13321         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
13322                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
13323         else
13324                 dst_reg->smin_value = S64_MIN;
13325
13326         /* If we might shift our top bit out, then we know nothing */
13327         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
13328                 dst_reg->umin_value = 0;
13329                 dst_reg->umax_value = U64_MAX;
13330         } else {
13331                 dst_reg->umin_value <<= umin_val;
13332                 dst_reg->umax_value <<= umax_val;
13333         }
13334 }
13335
13336 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
13337                                struct bpf_reg_state *src_reg)
13338 {
13339         u64 umax_val = src_reg->umax_value;
13340         u64 umin_val = src_reg->umin_value;
13341
13342         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
13343         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
13344         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
13345
13346         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
13347         /* We may learn something more from the var_off */
13348         __update_reg_bounds(dst_reg);
13349 }
13350
13351 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
13352                                  struct bpf_reg_state *src_reg)
13353 {
13354         struct tnum subreg = tnum_subreg(dst_reg->var_off);
13355         u32 umax_val = src_reg->u32_max_value;
13356         u32 umin_val = src_reg->u32_min_value;
13357
13358         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13359          * be negative, then either:
13360          * 1) src_reg might be zero, so the sign bit of the result is
13361          *    unknown, so we lose our signed bounds
13362          * 2) it's known negative, thus the unsigned bounds capture the
13363          *    signed bounds
13364          * 3) the signed bounds cross zero, so they tell us nothing
13365          *    about the result
13366          * If the value in dst_reg is known nonnegative, then again the
13367          * unsigned bounds capture the signed bounds.
13368          * Thus, in all cases it suffices to blow away our signed bounds
13369          * and rely on inferring new ones from the unsigned bounds and
13370          * var_off of the result.
13371          */
13372         dst_reg->s32_min_value = S32_MIN;
13373         dst_reg->s32_max_value = S32_MAX;
13374
13375         dst_reg->var_off = tnum_rshift(subreg, umin_val);
13376         dst_reg->u32_min_value >>= umax_val;
13377         dst_reg->u32_max_value >>= umin_val;
13378
13379         __mark_reg64_unbounded(dst_reg);
13380         __update_reg32_bounds(dst_reg);
13381 }
13382
13383 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
13384                                struct bpf_reg_state *src_reg)
13385 {
13386         u64 umax_val = src_reg->umax_value;
13387         u64 umin_val = src_reg->umin_value;
13388
13389         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
13390          * be negative, then either:
13391          * 1) src_reg might be zero, so the sign bit of the result is
13392          *    unknown, so we lose our signed bounds
13393          * 2) it's known negative, thus the unsigned bounds capture the
13394          *    signed bounds
13395          * 3) the signed bounds cross zero, so they tell us nothing
13396          *    about the result
13397          * If the value in dst_reg is known nonnegative, then again the
13398          * unsigned bounds capture the signed bounds.
13399          * Thus, in all cases it suffices to blow away our signed bounds
13400          * and rely on inferring new ones from the unsigned bounds and
13401          * var_off of the result.
13402          */
13403         dst_reg->smin_value = S64_MIN;
13404         dst_reg->smax_value = S64_MAX;
13405         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
13406         dst_reg->umin_value >>= umax_val;
13407         dst_reg->umax_value >>= umin_val;
13408
13409         /* Its not easy to operate on alu32 bounds here because it depends
13410          * on bits being shifted in. Take easy way out and mark unbounded
13411          * so we can recalculate later from tnum.
13412          */
13413         __mark_reg32_unbounded(dst_reg);
13414         __update_reg_bounds(dst_reg);
13415 }
13416
13417 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
13418                                   struct bpf_reg_state *src_reg)
13419 {
13420         u64 umin_val = src_reg->u32_min_value;
13421
13422         /* Upon reaching here, src_known is true and
13423          * umax_val is equal to umin_val.
13424          */
13425         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
13426         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
13427
13428         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
13429
13430         /* blow away the dst_reg umin_value/umax_value and rely on
13431          * dst_reg var_off to refine the result.
13432          */
13433         dst_reg->u32_min_value = 0;
13434         dst_reg->u32_max_value = U32_MAX;
13435
13436         __mark_reg64_unbounded(dst_reg);
13437         __update_reg32_bounds(dst_reg);
13438 }
13439
13440 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
13441                                 struct bpf_reg_state *src_reg)
13442 {
13443         u64 umin_val = src_reg->umin_value;
13444
13445         /* Upon reaching here, src_known is true and umax_val is equal
13446          * to umin_val.
13447          */
13448         dst_reg->smin_value >>= umin_val;
13449         dst_reg->smax_value >>= umin_val;
13450
13451         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
13452
13453         /* blow away the dst_reg umin_value/umax_value and rely on
13454          * dst_reg var_off to refine the result.
13455          */
13456         dst_reg->umin_value = 0;
13457         dst_reg->umax_value = U64_MAX;
13458
13459         /* Its not easy to operate on alu32 bounds here because it depends
13460          * on bits being shifted in from upper 32-bits. Take easy way out
13461          * and mark unbounded so we can recalculate later from tnum.
13462          */
13463         __mark_reg32_unbounded(dst_reg);
13464         __update_reg_bounds(dst_reg);
13465 }
13466
13467 /* WARNING: This function does calculations on 64-bit values, but the actual
13468  * execution may occur on 32-bit values. Therefore, things like bitshifts
13469  * need extra checks in the 32-bit case.
13470  */
13471 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
13472                                       struct bpf_insn *insn,
13473                                       struct bpf_reg_state *dst_reg,
13474                                       struct bpf_reg_state src_reg)
13475 {
13476         struct bpf_reg_state *regs = cur_regs(env);
13477         u8 opcode = BPF_OP(insn->code);
13478         bool src_known;
13479         s64 smin_val, smax_val;
13480         u64 umin_val, umax_val;
13481         s32 s32_min_val, s32_max_val;
13482         u32 u32_min_val, u32_max_val;
13483         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
13484         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
13485         int ret;
13486
13487         smin_val = src_reg.smin_value;
13488         smax_val = src_reg.smax_value;
13489         umin_val = src_reg.umin_value;
13490         umax_val = src_reg.umax_value;
13491
13492         s32_min_val = src_reg.s32_min_value;
13493         s32_max_val = src_reg.s32_max_value;
13494         u32_min_val = src_reg.u32_min_value;
13495         u32_max_val = src_reg.u32_max_value;
13496
13497         if (alu32) {
13498                 src_known = tnum_subreg_is_const(src_reg.var_off);
13499                 if ((src_known &&
13500                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
13501                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
13502                         /* Taint dst register if offset had invalid bounds
13503                          * derived from e.g. dead branches.
13504                          */
13505                         __mark_reg_unknown(env, dst_reg);
13506                         return 0;
13507                 }
13508         } else {
13509                 src_known = tnum_is_const(src_reg.var_off);
13510                 if ((src_known &&
13511                      (smin_val != smax_val || umin_val != umax_val)) ||
13512                     smin_val > smax_val || umin_val > umax_val) {
13513                         /* Taint dst register if offset had invalid bounds
13514                          * derived from e.g. dead branches.
13515                          */
13516                         __mark_reg_unknown(env, dst_reg);
13517                         return 0;
13518                 }
13519         }
13520
13521         if (!src_known &&
13522             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
13523                 __mark_reg_unknown(env, dst_reg);
13524                 return 0;
13525         }
13526
13527         if (sanitize_needed(opcode)) {
13528                 ret = sanitize_val_alu(env, insn);
13529                 if (ret < 0)
13530                         return sanitize_err(env, insn, ret, NULL, NULL);
13531         }
13532
13533         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
13534          * There are two classes of instructions: The first class we track both
13535          * alu32 and alu64 sign/unsigned bounds independently this provides the
13536          * greatest amount of precision when alu operations are mixed with jmp32
13537          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
13538          * and BPF_OR. This is possible because these ops have fairly easy to
13539          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
13540          * See alu32 verifier tests for examples. The second class of
13541          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
13542          * with regards to tracking sign/unsigned bounds because the bits may
13543          * cross subreg boundaries in the alu64 case. When this happens we mark
13544          * the reg unbounded in the subreg bound space and use the resulting
13545          * tnum to calculate an approximation of the sign/unsigned bounds.
13546          */
13547         switch (opcode) {
13548         case BPF_ADD:
13549                 scalar32_min_max_add(dst_reg, &src_reg);
13550                 scalar_min_max_add(dst_reg, &src_reg);
13551                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
13552                 break;
13553         case BPF_SUB:
13554                 scalar32_min_max_sub(dst_reg, &src_reg);
13555                 scalar_min_max_sub(dst_reg, &src_reg);
13556                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
13557                 break;
13558         case BPF_MUL:
13559                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
13560                 scalar32_min_max_mul(dst_reg, &src_reg);
13561                 scalar_min_max_mul(dst_reg, &src_reg);
13562                 break;
13563         case BPF_AND:
13564                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
13565                 scalar32_min_max_and(dst_reg, &src_reg);
13566                 scalar_min_max_and(dst_reg, &src_reg);
13567                 break;
13568         case BPF_OR:
13569                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
13570                 scalar32_min_max_or(dst_reg, &src_reg);
13571                 scalar_min_max_or(dst_reg, &src_reg);
13572                 break;
13573         case BPF_XOR:
13574                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
13575                 scalar32_min_max_xor(dst_reg, &src_reg);
13576                 scalar_min_max_xor(dst_reg, &src_reg);
13577                 break;
13578         case BPF_LSH:
13579                 if (umax_val >= insn_bitness) {
13580                         /* Shifts greater than 31 or 63 are undefined.
13581                          * This includes shifts by a negative number.
13582                          */
13583                         mark_reg_unknown(env, regs, insn->dst_reg);
13584                         break;
13585                 }
13586                 if (alu32)
13587                         scalar32_min_max_lsh(dst_reg, &src_reg);
13588                 else
13589                         scalar_min_max_lsh(dst_reg, &src_reg);
13590                 break;
13591         case BPF_RSH:
13592                 if (umax_val >= insn_bitness) {
13593                         /* Shifts greater than 31 or 63 are undefined.
13594                          * This includes shifts by a negative number.
13595                          */
13596                         mark_reg_unknown(env, regs, insn->dst_reg);
13597                         break;
13598                 }
13599                 if (alu32)
13600                         scalar32_min_max_rsh(dst_reg, &src_reg);
13601                 else
13602                         scalar_min_max_rsh(dst_reg, &src_reg);
13603                 break;
13604         case BPF_ARSH:
13605                 if (umax_val >= insn_bitness) {
13606                         /* Shifts greater than 31 or 63 are undefined.
13607                          * This includes shifts by a negative number.
13608                          */
13609                         mark_reg_unknown(env, regs, insn->dst_reg);
13610                         break;
13611                 }
13612                 if (alu32)
13613                         scalar32_min_max_arsh(dst_reg, &src_reg);
13614                 else
13615                         scalar_min_max_arsh(dst_reg, &src_reg);
13616                 break;
13617         default:
13618                 mark_reg_unknown(env, regs, insn->dst_reg);
13619                 break;
13620         }
13621
13622         /* ALU32 ops are zero extended into 64bit register */
13623         if (alu32)
13624                 zext_32_to_64(dst_reg);
13625         reg_bounds_sync(dst_reg);
13626         return 0;
13627 }
13628
13629 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13630  * and var_off.
13631  */
13632 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13633                                    struct bpf_insn *insn)
13634 {
13635         struct bpf_verifier_state *vstate = env->cur_state;
13636         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13637         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13638         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13639         u8 opcode = BPF_OP(insn->code);
13640         int err;
13641
13642         dst_reg = &regs[insn->dst_reg];
13643         src_reg = NULL;
13644         if (dst_reg->type != SCALAR_VALUE)
13645                 ptr_reg = dst_reg;
13646         else
13647                 /* Make sure ID is cleared otherwise dst_reg min/max could be
13648                  * incorrectly propagated into other registers by find_equal_scalars()
13649                  */
13650                 dst_reg->id = 0;
13651         if (BPF_SRC(insn->code) == BPF_X) {
13652                 src_reg = &regs[insn->src_reg];
13653                 if (src_reg->type != SCALAR_VALUE) {
13654                         if (dst_reg->type != SCALAR_VALUE) {
13655                                 /* Combining two pointers by any ALU op yields
13656                                  * an arbitrary scalar. Disallow all math except
13657                                  * pointer subtraction
13658                                  */
13659                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13660                                         mark_reg_unknown(env, regs, insn->dst_reg);
13661                                         return 0;
13662                                 }
13663                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13664                                         insn->dst_reg,
13665                                         bpf_alu_string[opcode >> 4]);
13666                                 return -EACCES;
13667                         } else {
13668                                 /* scalar += pointer
13669                                  * This is legal, but we have to reverse our
13670                                  * src/dest handling in computing the range
13671                                  */
13672                                 err = mark_chain_precision(env, insn->dst_reg);
13673                                 if (err)
13674                                         return err;
13675                                 return adjust_ptr_min_max_vals(env, insn,
13676                                                                src_reg, dst_reg);
13677                         }
13678                 } else if (ptr_reg) {
13679                         /* pointer += scalar */
13680                         err = mark_chain_precision(env, insn->src_reg);
13681                         if (err)
13682                                 return err;
13683                         return adjust_ptr_min_max_vals(env, insn,
13684                                                        dst_reg, src_reg);
13685                 } else if (dst_reg->precise) {
13686                         /* if dst_reg is precise, src_reg should be precise as well */
13687                         err = mark_chain_precision(env, insn->src_reg);
13688                         if (err)
13689                                 return err;
13690                 }
13691         } else {
13692                 /* Pretend the src is a reg with a known value, since we only
13693                  * need to be able to read from this state.
13694                  */
13695                 off_reg.type = SCALAR_VALUE;
13696                 __mark_reg_known(&off_reg, insn->imm);
13697                 src_reg = &off_reg;
13698                 if (ptr_reg) /* pointer += K */
13699                         return adjust_ptr_min_max_vals(env, insn,
13700                                                        ptr_reg, src_reg);
13701         }
13702
13703         /* Got here implies adding two SCALAR_VALUEs */
13704         if (WARN_ON_ONCE(ptr_reg)) {
13705                 print_verifier_state(env, state, true);
13706                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13707                 return -EINVAL;
13708         }
13709         if (WARN_ON(!src_reg)) {
13710                 print_verifier_state(env, state, true);
13711                 verbose(env, "verifier internal error: no src_reg\n");
13712                 return -EINVAL;
13713         }
13714         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13715 }
13716
13717 /* check validity of 32-bit and 64-bit arithmetic operations */
13718 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13719 {
13720         struct bpf_reg_state *regs = cur_regs(env);
13721         u8 opcode = BPF_OP(insn->code);
13722         int err;
13723
13724         if (opcode == BPF_END || opcode == BPF_NEG) {
13725                 if (opcode == BPF_NEG) {
13726                         if (BPF_SRC(insn->code) != BPF_K ||
13727                             insn->src_reg != BPF_REG_0 ||
13728                             insn->off != 0 || insn->imm != 0) {
13729                                 verbose(env, "BPF_NEG uses reserved fields\n");
13730                                 return -EINVAL;
13731                         }
13732                 } else {
13733                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13734                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13735                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13736                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13737                                 verbose(env, "BPF_END uses reserved fields\n");
13738                                 return -EINVAL;
13739                         }
13740                 }
13741
13742                 /* check src operand */
13743                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13744                 if (err)
13745                         return err;
13746
13747                 if (is_pointer_value(env, insn->dst_reg)) {
13748                         verbose(env, "R%d pointer arithmetic prohibited\n",
13749                                 insn->dst_reg);
13750                         return -EACCES;
13751                 }
13752
13753                 /* check dest operand */
13754                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13755                 if (err)
13756                         return err;
13757
13758         } else if (opcode == BPF_MOV) {
13759
13760                 if (BPF_SRC(insn->code) == BPF_X) {
13761                         if (insn->imm != 0) {
13762                                 verbose(env, "BPF_MOV uses reserved fields\n");
13763                                 return -EINVAL;
13764                         }
13765
13766                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13767                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13768                                         verbose(env, "BPF_MOV uses reserved fields\n");
13769                                         return -EINVAL;
13770                                 }
13771                         } else {
13772                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13773                                     insn->off != 32) {
13774                                         verbose(env, "BPF_MOV uses reserved fields\n");
13775                                         return -EINVAL;
13776                                 }
13777                         }
13778
13779                         /* check src operand */
13780                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13781                         if (err)
13782                                 return err;
13783                 } else {
13784                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13785                                 verbose(env, "BPF_MOV uses reserved fields\n");
13786                                 return -EINVAL;
13787                         }
13788                 }
13789
13790                 /* check dest operand, mark as required later */
13791                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13792                 if (err)
13793                         return err;
13794
13795                 if (BPF_SRC(insn->code) == BPF_X) {
13796                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13797                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13798                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13799                                        !tnum_is_const(src_reg->var_off);
13800
13801                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13802                                 if (insn->off == 0) {
13803                                         /* case: R1 = R2
13804                                          * copy register state to dest reg
13805                                          */
13806                                         if (need_id)
13807                                                 /* Assign src and dst registers the same ID
13808                                                  * that will be used by find_equal_scalars()
13809                                                  * to propagate min/max range.
13810                                                  */
13811                                                 src_reg->id = ++env->id_gen;
13812                                         copy_register_state(dst_reg, src_reg);
13813                                         dst_reg->live |= REG_LIVE_WRITTEN;
13814                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13815                                 } else {
13816                                         /* case: R1 = (s8, s16 s32)R2 */
13817                                         if (is_pointer_value(env, insn->src_reg)) {
13818                                                 verbose(env,
13819                                                         "R%d sign-extension part of pointer\n",
13820                                                         insn->src_reg);
13821                                                 return -EACCES;
13822                                         } else if (src_reg->type == SCALAR_VALUE) {
13823                                                 bool no_sext;
13824
13825                                                 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13826                                                 if (no_sext && need_id)
13827                                                         src_reg->id = ++env->id_gen;
13828                                                 copy_register_state(dst_reg, src_reg);
13829                                                 if (!no_sext)
13830                                                         dst_reg->id = 0;
13831                                                 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13832                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13833                                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
13834                                         } else {
13835                                                 mark_reg_unknown(env, regs, insn->dst_reg);
13836                                         }
13837                                 }
13838                         } else {
13839                                 /* R1 = (u32) R2 */
13840                                 if (is_pointer_value(env, insn->src_reg)) {
13841                                         verbose(env,
13842                                                 "R%d partial copy of pointer\n",
13843                                                 insn->src_reg);
13844                                         return -EACCES;
13845                                 } else if (src_reg->type == SCALAR_VALUE) {
13846                                         if (insn->off == 0) {
13847                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13848
13849                                                 if (is_src_reg_u32 && need_id)
13850                                                         src_reg->id = ++env->id_gen;
13851                                                 copy_register_state(dst_reg, src_reg);
13852                                                 /* Make sure ID is cleared if src_reg is not in u32
13853                                                  * range otherwise dst_reg min/max could be incorrectly
13854                                                  * propagated into src_reg by find_equal_scalars()
13855                                                  */
13856                                                 if (!is_src_reg_u32)
13857                                                         dst_reg->id = 0;
13858                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13859                                                 dst_reg->subreg_def = env->insn_idx + 1;
13860                                         } else {
13861                                                 /* case: W1 = (s8, s16)W2 */
13862                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13863
13864                                                 if (no_sext && need_id)
13865                                                         src_reg->id = ++env->id_gen;
13866                                                 copy_register_state(dst_reg, src_reg);
13867                                                 if (!no_sext)
13868                                                         dst_reg->id = 0;
13869                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13870                                                 dst_reg->subreg_def = env->insn_idx + 1;
13871                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13872                                         }
13873                                 } else {
13874                                         mark_reg_unknown(env, regs,
13875                                                          insn->dst_reg);
13876                                 }
13877                                 zext_32_to_64(dst_reg);
13878                                 reg_bounds_sync(dst_reg);
13879                         }
13880                 } else {
13881                         /* case: R = imm
13882                          * remember the value we stored into this reg
13883                          */
13884                         /* clear any state __mark_reg_known doesn't set */
13885                         mark_reg_unknown(env, regs, insn->dst_reg);
13886                         regs[insn->dst_reg].type = SCALAR_VALUE;
13887                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13888                                 __mark_reg_known(regs + insn->dst_reg,
13889                                                  insn->imm);
13890                         } else {
13891                                 __mark_reg_known(regs + insn->dst_reg,
13892                                                  (u32)insn->imm);
13893                         }
13894                 }
13895
13896         } else if (opcode > BPF_END) {
13897                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13898                 return -EINVAL;
13899
13900         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13901
13902                 if (BPF_SRC(insn->code) == BPF_X) {
13903                         if (insn->imm != 0 || insn->off > 1 ||
13904                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13905                                 verbose(env, "BPF_ALU uses reserved fields\n");
13906                                 return -EINVAL;
13907                         }
13908                         /* check src1 operand */
13909                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13910                         if (err)
13911                                 return err;
13912                 } else {
13913                         if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13914                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13915                                 verbose(env, "BPF_ALU uses reserved fields\n");
13916                                 return -EINVAL;
13917                         }
13918                 }
13919
13920                 /* check src2 operand */
13921                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13922                 if (err)
13923                         return err;
13924
13925                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13926                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13927                         verbose(env, "div by zero\n");
13928                         return -EINVAL;
13929                 }
13930
13931                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13932                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13933                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13934
13935                         if (insn->imm < 0 || insn->imm >= size) {
13936                                 verbose(env, "invalid shift %d\n", insn->imm);
13937                                 return -EINVAL;
13938                         }
13939                 }
13940
13941                 /* check dest operand */
13942                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13943                 if (err)
13944                         return err;
13945
13946                 return adjust_reg_min_max_vals(env, insn);
13947         }
13948
13949         return 0;
13950 }
13951
13952 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13953                                    struct bpf_reg_state *dst_reg,
13954                                    enum bpf_reg_type type,
13955                                    bool range_right_open)
13956 {
13957         struct bpf_func_state *state;
13958         struct bpf_reg_state *reg;
13959         int new_range;
13960
13961         if (dst_reg->off < 0 ||
13962             (dst_reg->off == 0 && range_right_open))
13963                 /* This doesn't give us any range */
13964                 return;
13965
13966         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13967             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13968                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13969                  * than pkt_end, but that's because it's also less than pkt.
13970                  */
13971                 return;
13972
13973         new_range = dst_reg->off;
13974         if (range_right_open)
13975                 new_range++;
13976
13977         /* Examples for register markings:
13978          *
13979          * pkt_data in dst register:
13980          *
13981          *   r2 = r3;
13982          *   r2 += 8;
13983          *   if (r2 > pkt_end) goto <handle exception>
13984          *   <access okay>
13985          *
13986          *   r2 = r3;
13987          *   r2 += 8;
13988          *   if (r2 < pkt_end) goto <access okay>
13989          *   <handle exception>
13990          *
13991          *   Where:
13992          *     r2 == dst_reg, pkt_end == src_reg
13993          *     r2=pkt(id=n,off=8,r=0)
13994          *     r3=pkt(id=n,off=0,r=0)
13995          *
13996          * pkt_data in src register:
13997          *
13998          *   r2 = r3;
13999          *   r2 += 8;
14000          *   if (pkt_end >= r2) goto <access okay>
14001          *   <handle exception>
14002          *
14003          *   r2 = r3;
14004          *   r2 += 8;
14005          *   if (pkt_end <= r2) goto <handle exception>
14006          *   <access okay>
14007          *
14008          *   Where:
14009          *     pkt_end == dst_reg, r2 == src_reg
14010          *     r2=pkt(id=n,off=8,r=0)
14011          *     r3=pkt(id=n,off=0,r=0)
14012          *
14013          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
14014          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
14015          * and [r3, r3 + 8-1) respectively is safe to access depending on
14016          * the check.
14017          */
14018
14019         /* If our ids match, then we must have the same max_value.  And we
14020          * don't care about the other reg's fixed offset, since if it's too big
14021          * the range won't allow anything.
14022          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
14023          */
14024         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14025                 if (reg->type == type && reg->id == dst_reg->id)
14026                         /* keep the maximum range already checked */
14027                         reg->range = max(reg->range, new_range);
14028         }));
14029 }
14030
14031 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
14032 {
14033         struct tnum subreg = tnum_subreg(reg->var_off);
14034         s32 sval = (s32)val;
14035
14036         switch (opcode) {
14037         case BPF_JEQ:
14038                 if (tnum_is_const(subreg))
14039                         return !!tnum_equals_const(subreg, val);
14040                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14041                         return 0;
14042                 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14043                         return 0;
14044                 break;
14045         case BPF_JNE:
14046                 if (tnum_is_const(subreg))
14047                         return !tnum_equals_const(subreg, val);
14048                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
14049                         return 1;
14050                 else if (sval < reg->s32_min_value || sval > reg->s32_max_value)
14051                         return 1;
14052                 break;
14053         case BPF_JSET:
14054                 if ((~subreg.mask & subreg.value) & val)
14055                         return 1;
14056                 if (!((subreg.mask | subreg.value) & val))
14057                         return 0;
14058                 break;
14059         case BPF_JGT:
14060                 if (reg->u32_min_value > val)
14061                         return 1;
14062                 else if (reg->u32_max_value <= val)
14063                         return 0;
14064                 break;
14065         case BPF_JSGT:
14066                 if (reg->s32_min_value > sval)
14067                         return 1;
14068                 else if (reg->s32_max_value <= sval)
14069                         return 0;
14070                 break;
14071         case BPF_JLT:
14072                 if (reg->u32_max_value < val)
14073                         return 1;
14074                 else if (reg->u32_min_value >= val)
14075                         return 0;
14076                 break;
14077         case BPF_JSLT:
14078                 if (reg->s32_max_value < sval)
14079                         return 1;
14080                 else if (reg->s32_min_value >= sval)
14081                         return 0;
14082                 break;
14083         case BPF_JGE:
14084                 if (reg->u32_min_value >= val)
14085                         return 1;
14086                 else if (reg->u32_max_value < val)
14087                         return 0;
14088                 break;
14089         case BPF_JSGE:
14090                 if (reg->s32_min_value >= sval)
14091                         return 1;
14092                 else if (reg->s32_max_value < sval)
14093                         return 0;
14094                 break;
14095         case BPF_JLE:
14096                 if (reg->u32_max_value <= val)
14097                         return 1;
14098                 else if (reg->u32_min_value > val)
14099                         return 0;
14100                 break;
14101         case BPF_JSLE:
14102                 if (reg->s32_max_value <= sval)
14103                         return 1;
14104                 else if (reg->s32_min_value > sval)
14105                         return 0;
14106                 break;
14107         }
14108
14109         return -1;
14110 }
14111
14112
14113 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
14114 {
14115         s64 sval = (s64)val;
14116
14117         switch (opcode) {
14118         case BPF_JEQ:
14119                 if (tnum_is_const(reg->var_off))
14120                         return !!tnum_equals_const(reg->var_off, val);
14121                 else if (val < reg->umin_value || val > reg->umax_value)
14122                         return 0;
14123                 else if (sval < reg->smin_value || sval > reg->smax_value)
14124                         return 0;
14125                 break;
14126         case BPF_JNE:
14127                 if (tnum_is_const(reg->var_off))
14128                         return !tnum_equals_const(reg->var_off, val);
14129                 else if (val < reg->umin_value || val > reg->umax_value)
14130                         return 1;
14131                 else if (sval < reg->smin_value || sval > reg->smax_value)
14132                         return 1;
14133                 break;
14134         case BPF_JSET:
14135                 if ((~reg->var_off.mask & reg->var_off.value) & val)
14136                         return 1;
14137                 if (!((reg->var_off.mask | reg->var_off.value) & val))
14138                         return 0;
14139                 break;
14140         case BPF_JGT:
14141                 if (reg->umin_value > val)
14142                         return 1;
14143                 else if (reg->umax_value <= val)
14144                         return 0;
14145                 break;
14146         case BPF_JSGT:
14147                 if (reg->smin_value > sval)
14148                         return 1;
14149                 else if (reg->smax_value <= sval)
14150                         return 0;
14151                 break;
14152         case BPF_JLT:
14153                 if (reg->umax_value < val)
14154                         return 1;
14155                 else if (reg->umin_value >= val)
14156                         return 0;
14157                 break;
14158         case BPF_JSLT:
14159                 if (reg->smax_value < sval)
14160                         return 1;
14161                 else if (reg->smin_value >= sval)
14162                         return 0;
14163                 break;
14164         case BPF_JGE:
14165                 if (reg->umin_value >= val)
14166                         return 1;
14167                 else if (reg->umax_value < val)
14168                         return 0;
14169                 break;
14170         case BPF_JSGE:
14171                 if (reg->smin_value >= sval)
14172                         return 1;
14173                 else if (reg->smax_value < sval)
14174                         return 0;
14175                 break;
14176         case BPF_JLE:
14177                 if (reg->umax_value <= val)
14178                         return 1;
14179                 else if (reg->umin_value > val)
14180                         return 0;
14181                 break;
14182         case BPF_JSLE:
14183                 if (reg->smax_value <= sval)
14184                         return 1;
14185                 else if (reg->smin_value > sval)
14186                         return 0;
14187                 break;
14188         }
14189
14190         return -1;
14191 }
14192
14193 /* compute branch direction of the expression "if (reg opcode val) goto target;"
14194  * and return:
14195  *  1 - branch will be taken and "goto target" will be executed
14196  *  0 - branch will not be taken and fall-through to next insn
14197  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
14198  *      range [0,10]
14199  */
14200 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
14201                            bool is_jmp32)
14202 {
14203         if (__is_pointer_value(false, reg)) {
14204                 if (!reg_not_null(reg))
14205                         return -1;
14206
14207                 /* If pointer is valid tests against zero will fail so we can
14208                  * use this to direct branch taken.
14209                  */
14210                 if (val != 0)
14211                         return -1;
14212
14213                 switch (opcode) {
14214                 case BPF_JEQ:
14215                         return 0;
14216                 case BPF_JNE:
14217                         return 1;
14218                 default:
14219                         return -1;
14220                 }
14221         }
14222
14223         if (is_jmp32)
14224                 return is_branch32_taken(reg, val, opcode);
14225         return is_branch64_taken(reg, val, opcode);
14226 }
14227
14228 static int flip_opcode(u32 opcode)
14229 {
14230         /* How can we transform "a <op> b" into "b <op> a"? */
14231         static const u8 opcode_flip[16] = {
14232                 /* these stay the same */
14233                 [BPF_JEQ  >> 4] = BPF_JEQ,
14234                 [BPF_JNE  >> 4] = BPF_JNE,
14235                 [BPF_JSET >> 4] = BPF_JSET,
14236                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
14237                 [BPF_JGE  >> 4] = BPF_JLE,
14238                 [BPF_JGT  >> 4] = BPF_JLT,
14239                 [BPF_JLE  >> 4] = BPF_JGE,
14240                 [BPF_JLT  >> 4] = BPF_JGT,
14241                 [BPF_JSGE >> 4] = BPF_JSLE,
14242                 [BPF_JSGT >> 4] = BPF_JSLT,
14243                 [BPF_JSLE >> 4] = BPF_JSGE,
14244                 [BPF_JSLT >> 4] = BPF_JSGT
14245         };
14246         return opcode_flip[opcode >> 4];
14247 }
14248
14249 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
14250                                    struct bpf_reg_state *src_reg,
14251                                    u8 opcode)
14252 {
14253         struct bpf_reg_state *pkt;
14254
14255         if (src_reg->type == PTR_TO_PACKET_END) {
14256                 pkt = dst_reg;
14257         } else if (dst_reg->type == PTR_TO_PACKET_END) {
14258                 pkt = src_reg;
14259                 opcode = flip_opcode(opcode);
14260         } else {
14261                 return -1;
14262         }
14263
14264         if (pkt->range >= 0)
14265                 return -1;
14266
14267         switch (opcode) {
14268         case BPF_JLE:
14269                 /* pkt <= pkt_end */
14270                 fallthrough;
14271         case BPF_JGT:
14272                 /* pkt > pkt_end */
14273                 if (pkt->range == BEYOND_PKT_END)
14274                         /* pkt has at last one extra byte beyond pkt_end */
14275                         return opcode == BPF_JGT;
14276                 break;
14277         case BPF_JLT:
14278                 /* pkt < pkt_end */
14279                 fallthrough;
14280         case BPF_JGE:
14281                 /* pkt >= pkt_end */
14282                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
14283                         return opcode == BPF_JGE;
14284                 break;
14285         }
14286         return -1;
14287 }
14288
14289 /* Adjusts the register min/max values in the case that the dst_reg is the
14290  * variable register that we are working on, and src_reg is a constant or we're
14291  * simply doing a BPF_K check.
14292  * In JEQ/JNE cases we also adjust the var_off values.
14293  */
14294 static void reg_set_min_max(struct bpf_reg_state *true_reg,
14295                             struct bpf_reg_state *false_reg,
14296                             u64 val, u32 val32,
14297                             u8 opcode, bool is_jmp32)
14298 {
14299         struct tnum false_32off = tnum_subreg(false_reg->var_off);
14300         struct tnum false_64off = false_reg->var_off;
14301         struct tnum true_32off = tnum_subreg(true_reg->var_off);
14302         struct tnum true_64off = true_reg->var_off;
14303         s64 sval = (s64)val;
14304         s32 sval32 = (s32)val32;
14305
14306         /* If the dst_reg is a pointer, we can't learn anything about its
14307          * variable offset from the compare (unless src_reg were a pointer into
14308          * the same object, but we don't bother with that.
14309          * Since false_reg and true_reg have the same type by construction, we
14310          * only need to check one of them for pointerness.
14311          */
14312         if (__is_pointer_value(false, false_reg))
14313                 return;
14314
14315         switch (opcode) {
14316         /* JEQ/JNE comparison doesn't change the register equivalence.
14317          *
14318          * r1 = r2;
14319          * if (r1 == 42) goto label;
14320          * ...
14321          * label: // here both r1 and r2 are known to be 42.
14322          *
14323          * Hence when marking register as known preserve it's ID.
14324          */
14325         case BPF_JEQ:
14326                 if (is_jmp32) {
14327                         __mark_reg32_known(true_reg, val32);
14328                         true_32off = tnum_subreg(true_reg->var_off);
14329                 } else {
14330                         ___mark_reg_known(true_reg, val);
14331                         true_64off = true_reg->var_off;
14332                 }
14333                 break;
14334         case BPF_JNE:
14335                 if (is_jmp32) {
14336                         __mark_reg32_known(false_reg, val32);
14337                         false_32off = tnum_subreg(false_reg->var_off);
14338                 } else {
14339                         ___mark_reg_known(false_reg, val);
14340                         false_64off = false_reg->var_off;
14341                 }
14342                 break;
14343         case BPF_JSET:
14344                 if (is_jmp32) {
14345                         false_32off = tnum_and(false_32off, tnum_const(~val32));
14346                         if (is_power_of_2(val32))
14347                                 true_32off = tnum_or(true_32off,
14348                                                      tnum_const(val32));
14349                 } else {
14350                         false_64off = tnum_and(false_64off, tnum_const(~val));
14351                         if (is_power_of_2(val))
14352                                 true_64off = tnum_or(true_64off,
14353                                                      tnum_const(val));
14354                 }
14355                 break;
14356         case BPF_JGE:
14357         case BPF_JGT:
14358         {
14359                 if (is_jmp32) {
14360                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
14361                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
14362
14363                         false_reg->u32_max_value = min(false_reg->u32_max_value,
14364                                                        false_umax);
14365                         true_reg->u32_min_value = max(true_reg->u32_min_value,
14366                                                       true_umin);
14367                 } else {
14368                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
14369                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
14370
14371                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
14372                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
14373                 }
14374                 break;
14375         }
14376         case BPF_JSGE:
14377         case BPF_JSGT:
14378         {
14379                 if (is_jmp32) {
14380                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
14381                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
14382
14383                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
14384                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
14385                 } else {
14386                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
14387                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
14388
14389                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
14390                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
14391                 }
14392                 break;
14393         }
14394         case BPF_JLE:
14395         case BPF_JLT:
14396         {
14397                 if (is_jmp32) {
14398                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
14399                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
14400
14401                         false_reg->u32_min_value = max(false_reg->u32_min_value,
14402                                                        false_umin);
14403                         true_reg->u32_max_value = min(true_reg->u32_max_value,
14404                                                       true_umax);
14405                 } else {
14406                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
14407                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
14408
14409                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
14410                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
14411                 }
14412                 break;
14413         }
14414         case BPF_JSLE:
14415         case BPF_JSLT:
14416         {
14417                 if (is_jmp32) {
14418                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
14419                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
14420
14421                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
14422                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
14423                 } else {
14424                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
14425                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
14426
14427                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
14428                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
14429                 }
14430                 break;
14431         }
14432         default:
14433                 return;
14434         }
14435
14436         if (is_jmp32) {
14437                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
14438                                              tnum_subreg(false_32off));
14439                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
14440                                             tnum_subreg(true_32off));
14441                 __reg_combine_32_into_64(false_reg);
14442                 __reg_combine_32_into_64(true_reg);
14443         } else {
14444                 false_reg->var_off = false_64off;
14445                 true_reg->var_off = true_64off;
14446                 __reg_combine_64_into_32(false_reg);
14447                 __reg_combine_64_into_32(true_reg);
14448         }
14449 }
14450
14451 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
14452  * the variable reg.
14453  */
14454 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
14455                                 struct bpf_reg_state *false_reg,
14456                                 u64 val, u32 val32,
14457                                 u8 opcode, bool is_jmp32)
14458 {
14459         opcode = flip_opcode(opcode);
14460         /* This uses zero as "not present in table"; luckily the zero opcode,
14461          * BPF_JA, can't get here.
14462          */
14463         if (opcode)
14464                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
14465 }
14466
14467 /* Regs are known to be equal, so intersect their min/max/var_off */
14468 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
14469                                   struct bpf_reg_state *dst_reg)
14470 {
14471         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
14472                                                         dst_reg->umin_value);
14473         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
14474                                                         dst_reg->umax_value);
14475         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
14476                                                         dst_reg->smin_value);
14477         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
14478                                                         dst_reg->smax_value);
14479         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
14480                                                              dst_reg->var_off);
14481         reg_bounds_sync(src_reg);
14482         reg_bounds_sync(dst_reg);
14483 }
14484
14485 static void reg_combine_min_max(struct bpf_reg_state *true_src,
14486                                 struct bpf_reg_state *true_dst,
14487                                 struct bpf_reg_state *false_src,
14488                                 struct bpf_reg_state *false_dst,
14489                                 u8 opcode)
14490 {
14491         switch (opcode) {
14492         case BPF_JEQ:
14493                 __reg_combine_min_max(true_src, true_dst);
14494                 break;
14495         case BPF_JNE:
14496                 __reg_combine_min_max(false_src, false_dst);
14497                 break;
14498         }
14499 }
14500
14501 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
14502                                  struct bpf_reg_state *reg, u32 id,
14503                                  bool is_null)
14504 {
14505         if (type_may_be_null(reg->type) && reg->id == id &&
14506             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
14507                 /* Old offset (both fixed and variable parts) should have been
14508                  * known-zero, because we don't allow pointer arithmetic on
14509                  * pointers that might be NULL. If we see this happening, don't
14510                  * convert the register.
14511                  *
14512                  * But in some cases, some helpers that return local kptrs
14513                  * advance offset for the returned pointer. In those cases, it
14514                  * is fine to expect to see reg->off.
14515                  */
14516                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
14517                         return;
14518                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
14519                     WARN_ON_ONCE(reg->off))
14520                         return;
14521
14522                 if (is_null) {
14523                         reg->type = SCALAR_VALUE;
14524                         /* We don't need id and ref_obj_id from this point
14525                          * onwards anymore, thus we should better reset it,
14526                          * so that state pruning has chances to take effect.
14527                          */
14528                         reg->id = 0;
14529                         reg->ref_obj_id = 0;
14530
14531                         return;
14532                 }
14533
14534                 mark_ptr_not_null_reg(reg);
14535
14536                 if (!reg_may_point_to_spin_lock(reg)) {
14537                         /* For not-NULL ptr, reg->ref_obj_id will be reset
14538                          * in release_reference().
14539                          *
14540                          * reg->id is still used by spin_lock ptr. Other
14541                          * than spin_lock ptr type, reg->id can be reset.
14542                          */
14543                         reg->id = 0;
14544                 }
14545         }
14546 }
14547
14548 /* The logic is similar to find_good_pkt_pointers(), both could eventually
14549  * be folded together at some point.
14550  */
14551 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
14552                                   bool is_null)
14553 {
14554         struct bpf_func_state *state = vstate->frame[vstate->curframe];
14555         struct bpf_reg_state *regs = state->regs, *reg;
14556         u32 ref_obj_id = regs[regno].ref_obj_id;
14557         u32 id = regs[regno].id;
14558
14559         if (ref_obj_id && ref_obj_id == id && is_null)
14560                 /* regs[regno] is in the " == NULL" branch.
14561                  * No one could have freed the reference state before
14562                  * doing the NULL check.
14563                  */
14564                 WARN_ON_ONCE(release_reference_state(state, id));
14565
14566         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14567                 mark_ptr_or_null_reg(state, reg, id, is_null);
14568         }));
14569 }
14570
14571 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
14572                                    struct bpf_reg_state *dst_reg,
14573                                    struct bpf_reg_state *src_reg,
14574                                    struct bpf_verifier_state *this_branch,
14575                                    struct bpf_verifier_state *other_branch)
14576 {
14577         if (BPF_SRC(insn->code) != BPF_X)
14578                 return false;
14579
14580         /* Pointers are always 64-bit. */
14581         if (BPF_CLASS(insn->code) == BPF_JMP32)
14582                 return false;
14583
14584         switch (BPF_OP(insn->code)) {
14585         case BPF_JGT:
14586                 if ((dst_reg->type == PTR_TO_PACKET &&
14587                      src_reg->type == PTR_TO_PACKET_END) ||
14588                     (dst_reg->type == PTR_TO_PACKET_META &&
14589                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14590                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
14591                         find_good_pkt_pointers(this_branch, dst_reg,
14592                                                dst_reg->type, false);
14593                         mark_pkt_end(other_branch, insn->dst_reg, true);
14594                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14595                             src_reg->type == PTR_TO_PACKET) ||
14596                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14597                             src_reg->type == PTR_TO_PACKET_META)) {
14598                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
14599                         find_good_pkt_pointers(other_branch, src_reg,
14600                                                src_reg->type, true);
14601                         mark_pkt_end(this_branch, insn->src_reg, false);
14602                 } else {
14603                         return false;
14604                 }
14605                 break;
14606         case BPF_JLT:
14607                 if ((dst_reg->type == PTR_TO_PACKET &&
14608                      src_reg->type == PTR_TO_PACKET_END) ||
14609                     (dst_reg->type == PTR_TO_PACKET_META &&
14610                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14611                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
14612                         find_good_pkt_pointers(other_branch, dst_reg,
14613                                                dst_reg->type, true);
14614                         mark_pkt_end(this_branch, insn->dst_reg, false);
14615                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14616                             src_reg->type == PTR_TO_PACKET) ||
14617                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14618                             src_reg->type == PTR_TO_PACKET_META)) {
14619                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
14620                         find_good_pkt_pointers(this_branch, src_reg,
14621                                                src_reg->type, false);
14622                         mark_pkt_end(other_branch, insn->src_reg, true);
14623                 } else {
14624                         return false;
14625                 }
14626                 break;
14627         case BPF_JGE:
14628                 if ((dst_reg->type == PTR_TO_PACKET &&
14629                      src_reg->type == PTR_TO_PACKET_END) ||
14630                     (dst_reg->type == PTR_TO_PACKET_META &&
14631                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14632                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14633                         find_good_pkt_pointers(this_branch, dst_reg,
14634                                                dst_reg->type, true);
14635                         mark_pkt_end(other_branch, insn->dst_reg, false);
14636                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14637                             src_reg->type == PTR_TO_PACKET) ||
14638                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14639                             src_reg->type == PTR_TO_PACKET_META)) {
14640                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14641                         find_good_pkt_pointers(other_branch, src_reg,
14642                                                src_reg->type, false);
14643                         mark_pkt_end(this_branch, insn->src_reg, true);
14644                 } else {
14645                         return false;
14646                 }
14647                 break;
14648         case BPF_JLE:
14649                 if ((dst_reg->type == PTR_TO_PACKET &&
14650                      src_reg->type == PTR_TO_PACKET_END) ||
14651                     (dst_reg->type == PTR_TO_PACKET_META &&
14652                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14653                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14654                         find_good_pkt_pointers(other_branch, dst_reg,
14655                                                dst_reg->type, false);
14656                         mark_pkt_end(this_branch, insn->dst_reg, true);
14657                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14658                             src_reg->type == PTR_TO_PACKET) ||
14659                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14660                             src_reg->type == PTR_TO_PACKET_META)) {
14661                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14662                         find_good_pkt_pointers(this_branch, src_reg,
14663                                                src_reg->type, true);
14664                         mark_pkt_end(other_branch, insn->src_reg, false);
14665                 } else {
14666                         return false;
14667                 }
14668                 break;
14669         default:
14670                 return false;
14671         }
14672
14673         return true;
14674 }
14675
14676 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14677                                struct bpf_reg_state *known_reg)
14678 {
14679         struct bpf_func_state *state;
14680         struct bpf_reg_state *reg;
14681
14682         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14683                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14684                         copy_register_state(reg, known_reg);
14685         }));
14686 }
14687
14688 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14689                              struct bpf_insn *insn, int *insn_idx)
14690 {
14691         struct bpf_verifier_state *this_branch = env->cur_state;
14692         struct bpf_verifier_state *other_branch;
14693         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14694         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14695         struct bpf_reg_state *eq_branch_regs;
14696         u8 opcode = BPF_OP(insn->code);
14697         bool is_jmp32;
14698         int pred = -1;
14699         int err;
14700
14701         /* Only conditional jumps are expected to reach here. */
14702         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14703                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14704                 return -EINVAL;
14705         }
14706
14707         /* check src2 operand */
14708         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14709         if (err)
14710                 return err;
14711
14712         dst_reg = &regs[insn->dst_reg];
14713         if (BPF_SRC(insn->code) == BPF_X) {
14714                 if (insn->imm != 0) {
14715                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14716                         return -EINVAL;
14717                 }
14718
14719                 /* check src1 operand */
14720                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14721                 if (err)
14722                         return err;
14723
14724                 src_reg = &regs[insn->src_reg];
14725                 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14726                     is_pointer_value(env, insn->src_reg)) {
14727                         verbose(env, "R%d pointer comparison prohibited\n",
14728                                 insn->src_reg);
14729                         return -EACCES;
14730                 }
14731         } else {
14732                 if (insn->src_reg != BPF_REG_0) {
14733                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14734                         return -EINVAL;
14735                 }
14736         }
14737
14738         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14739
14740         if (BPF_SRC(insn->code) == BPF_K) {
14741                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14742         } else if (src_reg->type == SCALAR_VALUE &&
14743                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14744                 pred = is_branch_taken(dst_reg,
14745                                        tnum_subreg(src_reg->var_off).value,
14746                                        opcode,
14747                                        is_jmp32);
14748         } else if (src_reg->type == SCALAR_VALUE &&
14749                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14750                 pred = is_branch_taken(dst_reg,
14751                                        src_reg->var_off.value,
14752                                        opcode,
14753                                        is_jmp32);
14754         } else if (dst_reg->type == SCALAR_VALUE &&
14755                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14756                 pred = is_branch_taken(src_reg,
14757                                        tnum_subreg(dst_reg->var_off).value,
14758                                        flip_opcode(opcode),
14759                                        is_jmp32);
14760         } else if (dst_reg->type == SCALAR_VALUE &&
14761                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14762                 pred = is_branch_taken(src_reg,
14763                                        dst_reg->var_off.value,
14764                                        flip_opcode(opcode),
14765                                        is_jmp32);
14766         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14767                    reg_is_pkt_pointer_any(src_reg) &&
14768                    !is_jmp32) {
14769                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14770         }
14771
14772         if (pred >= 0) {
14773                 /* If we get here with a dst_reg pointer type it is because
14774                  * above is_branch_taken() special cased the 0 comparison.
14775                  */
14776                 if (!__is_pointer_value(false, dst_reg))
14777                         err = mark_chain_precision(env, insn->dst_reg);
14778                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14779                     !__is_pointer_value(false, src_reg))
14780                         err = mark_chain_precision(env, insn->src_reg);
14781                 if (err)
14782                         return err;
14783         }
14784
14785         if (pred == 1) {
14786                 /* Only follow the goto, ignore fall-through. If needed, push
14787                  * the fall-through branch for simulation under speculative
14788                  * execution.
14789                  */
14790                 if (!env->bypass_spec_v1 &&
14791                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14792                                                *insn_idx))
14793                         return -EFAULT;
14794                 if (env->log.level & BPF_LOG_LEVEL)
14795                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14796                 *insn_idx += insn->off;
14797                 return 0;
14798         } else if (pred == 0) {
14799                 /* Only follow the fall-through branch, since that's where the
14800                  * program will go. If needed, push the goto branch for
14801                  * simulation under speculative execution.
14802                  */
14803                 if (!env->bypass_spec_v1 &&
14804                     !sanitize_speculative_path(env, insn,
14805                                                *insn_idx + insn->off + 1,
14806                                                *insn_idx))
14807                         return -EFAULT;
14808                 if (env->log.level & BPF_LOG_LEVEL)
14809                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14810                 return 0;
14811         }
14812
14813         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14814                                   false);
14815         if (!other_branch)
14816                 return -EFAULT;
14817         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14818
14819         /* detect if we are comparing against a constant value so we can adjust
14820          * our min/max values for our dst register.
14821          * this is only legit if both are scalars (or pointers to the same
14822          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14823          * because otherwise the different base pointers mean the offsets aren't
14824          * comparable.
14825          */
14826         if (BPF_SRC(insn->code) == BPF_X) {
14827                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14828
14829                 if (dst_reg->type == SCALAR_VALUE &&
14830                     src_reg->type == SCALAR_VALUE) {
14831                         if (tnum_is_const(src_reg->var_off) ||
14832                             (is_jmp32 &&
14833                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14834                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14835                                                 dst_reg,
14836                                                 src_reg->var_off.value,
14837                                                 tnum_subreg(src_reg->var_off).value,
14838                                                 opcode, is_jmp32);
14839                         else if (tnum_is_const(dst_reg->var_off) ||
14840                                  (is_jmp32 &&
14841                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14842                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14843                                                     src_reg,
14844                                                     dst_reg->var_off.value,
14845                                                     tnum_subreg(dst_reg->var_off).value,
14846                                                     opcode, is_jmp32);
14847                         else if (!is_jmp32 &&
14848                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14849                                 /* Comparing for equality, we can combine knowledge */
14850                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14851                                                     &other_branch_regs[insn->dst_reg],
14852                                                     src_reg, dst_reg, opcode);
14853                         if (src_reg->id &&
14854                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14855                                 find_equal_scalars(this_branch, src_reg);
14856                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14857                         }
14858
14859                 }
14860         } else if (dst_reg->type == SCALAR_VALUE) {
14861                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14862                                         dst_reg, insn->imm, (u32)insn->imm,
14863                                         opcode, is_jmp32);
14864         }
14865
14866         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14867             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14868                 find_equal_scalars(this_branch, dst_reg);
14869                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14870         }
14871
14872         /* if one pointer register is compared to another pointer
14873          * register check if PTR_MAYBE_NULL could be lifted.
14874          * E.g. register A - maybe null
14875          *      register B - not null
14876          * for JNE A, B, ... - A is not null in the false branch;
14877          * for JEQ A, B, ... - A is not null in the true branch.
14878          *
14879          * Since PTR_TO_BTF_ID points to a kernel struct that does
14880          * not need to be null checked by the BPF program, i.e.,
14881          * could be null even without PTR_MAYBE_NULL marking, so
14882          * only propagate nullness when neither reg is that type.
14883          */
14884         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14885             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14886             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14887             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14888             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14889                 eq_branch_regs = NULL;
14890                 switch (opcode) {
14891                 case BPF_JEQ:
14892                         eq_branch_regs = other_branch_regs;
14893                         break;
14894                 case BPF_JNE:
14895                         eq_branch_regs = regs;
14896                         break;
14897                 default:
14898                         /* do nothing */
14899                         break;
14900                 }
14901                 if (eq_branch_regs) {
14902                         if (type_may_be_null(src_reg->type))
14903                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14904                         else
14905                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14906                 }
14907         }
14908
14909         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14910          * NOTE: these optimizations below are related with pointer comparison
14911          *       which will never be JMP32.
14912          */
14913         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14914             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14915             type_may_be_null(dst_reg->type)) {
14916                 /* Mark all identical registers in each branch as either
14917                  * safe or unknown depending R == 0 or R != 0 conditional.
14918                  */
14919                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14920                                       opcode == BPF_JNE);
14921                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14922                                       opcode == BPF_JEQ);
14923         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14924                                            this_branch, other_branch) &&
14925                    is_pointer_value(env, insn->dst_reg)) {
14926                 verbose(env, "R%d pointer comparison prohibited\n",
14927                         insn->dst_reg);
14928                 return -EACCES;
14929         }
14930         if (env->log.level & BPF_LOG_LEVEL)
14931                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14932         return 0;
14933 }
14934
14935 /* verify BPF_LD_IMM64 instruction */
14936 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14937 {
14938         struct bpf_insn_aux_data *aux = cur_aux(env);
14939         struct bpf_reg_state *regs = cur_regs(env);
14940         struct bpf_reg_state *dst_reg;
14941         struct bpf_map *map;
14942         int err;
14943
14944         if (BPF_SIZE(insn->code) != BPF_DW) {
14945                 verbose(env, "invalid BPF_LD_IMM insn\n");
14946                 return -EINVAL;
14947         }
14948         if (insn->off != 0) {
14949                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14950                 return -EINVAL;
14951         }
14952
14953         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14954         if (err)
14955                 return err;
14956
14957         dst_reg = &regs[insn->dst_reg];
14958         if (insn->src_reg == 0) {
14959                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14960
14961                 dst_reg->type = SCALAR_VALUE;
14962                 __mark_reg_known(&regs[insn->dst_reg], imm);
14963                 return 0;
14964         }
14965
14966         /* All special src_reg cases are listed below. From this point onwards
14967          * we either succeed and assign a corresponding dst_reg->type after
14968          * zeroing the offset, or fail and reject the program.
14969          */
14970         mark_reg_known_zero(env, regs, insn->dst_reg);
14971
14972         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14973                 dst_reg->type = aux->btf_var.reg_type;
14974                 switch (base_type(dst_reg->type)) {
14975                 case PTR_TO_MEM:
14976                         dst_reg->mem_size = aux->btf_var.mem_size;
14977                         break;
14978                 case PTR_TO_BTF_ID:
14979                         dst_reg->btf = aux->btf_var.btf;
14980                         dst_reg->btf_id = aux->btf_var.btf_id;
14981                         break;
14982                 default:
14983                         verbose(env, "bpf verifier is misconfigured\n");
14984                         return -EFAULT;
14985                 }
14986                 return 0;
14987         }
14988
14989         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14990                 struct bpf_prog_aux *aux = env->prog->aux;
14991                 u32 subprogno = find_subprog(env,
14992                                              env->insn_idx + insn->imm + 1);
14993
14994                 if (!aux->func_info) {
14995                         verbose(env, "missing btf func_info\n");
14996                         return -EINVAL;
14997                 }
14998                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14999                         verbose(env, "callback function not static\n");
15000                         return -EINVAL;
15001                 }
15002
15003                 dst_reg->type = PTR_TO_FUNC;
15004                 dst_reg->subprogno = subprogno;
15005                 return 0;
15006         }
15007
15008         map = env->used_maps[aux->map_index];
15009         dst_reg->map_ptr = map;
15010
15011         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
15012             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
15013                 dst_reg->type = PTR_TO_MAP_VALUE;
15014                 dst_reg->off = aux->map_off;
15015                 WARN_ON_ONCE(map->max_entries != 1);
15016                 /* We want reg->id to be same (0) as map_value is not distinct */
15017         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
15018                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
15019                 dst_reg->type = CONST_PTR_TO_MAP;
15020         } else {
15021                 verbose(env, "bpf verifier is misconfigured\n");
15022                 return -EINVAL;
15023         }
15024
15025         return 0;
15026 }
15027
15028 static bool may_access_skb(enum bpf_prog_type type)
15029 {
15030         switch (type) {
15031         case BPF_PROG_TYPE_SOCKET_FILTER:
15032         case BPF_PROG_TYPE_SCHED_CLS:
15033         case BPF_PROG_TYPE_SCHED_ACT:
15034                 return true;
15035         default:
15036                 return false;
15037         }
15038 }
15039
15040 /* verify safety of LD_ABS|LD_IND instructions:
15041  * - they can only appear in the programs where ctx == skb
15042  * - since they are wrappers of function calls, they scratch R1-R5 registers,
15043  *   preserve R6-R9, and store return value into R0
15044  *
15045  * Implicit input:
15046  *   ctx == skb == R6 == CTX
15047  *
15048  * Explicit input:
15049  *   SRC == any register
15050  *   IMM == 32-bit immediate
15051  *
15052  * Output:
15053  *   R0 - 8/16/32-bit skb data converted to cpu endianness
15054  */
15055 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
15056 {
15057         struct bpf_reg_state *regs = cur_regs(env);
15058         static const int ctx_reg = BPF_REG_6;
15059         u8 mode = BPF_MODE(insn->code);
15060         int i, err;
15061
15062         if (!may_access_skb(resolve_prog_type(env->prog))) {
15063                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
15064                 return -EINVAL;
15065         }
15066
15067         if (!env->ops->gen_ld_abs) {
15068                 verbose(env, "bpf verifier is misconfigured\n");
15069                 return -EINVAL;
15070         }
15071
15072         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
15073             BPF_SIZE(insn->code) == BPF_DW ||
15074             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
15075                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
15076                 return -EINVAL;
15077         }
15078
15079         /* check whether implicit source operand (register R6) is readable */
15080         err = check_reg_arg(env, ctx_reg, SRC_OP);
15081         if (err)
15082                 return err;
15083
15084         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
15085          * gen_ld_abs() may terminate the program at runtime, leading to
15086          * reference leak.
15087          */
15088         err = check_reference_leak(env, false);
15089         if (err) {
15090                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
15091                 return err;
15092         }
15093
15094         if (env->cur_state->active_lock.ptr) {
15095                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
15096                 return -EINVAL;
15097         }
15098
15099         if (env->cur_state->active_rcu_lock) {
15100                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
15101                 return -EINVAL;
15102         }
15103
15104         if (regs[ctx_reg].type != PTR_TO_CTX) {
15105                 verbose(env,
15106                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
15107                 return -EINVAL;
15108         }
15109
15110         if (mode == BPF_IND) {
15111                 /* check explicit source operand */
15112                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
15113                 if (err)
15114                         return err;
15115         }
15116
15117         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
15118         if (err < 0)
15119                 return err;
15120
15121         /* reset caller saved regs to unreadable */
15122         for (i = 0; i < CALLER_SAVED_REGS; i++) {
15123                 mark_reg_not_init(env, regs, caller_saved[i]);
15124                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
15125         }
15126
15127         /* mark destination R0 register as readable, since it contains
15128          * the value fetched from the packet.
15129          * Already marked as written above.
15130          */
15131         mark_reg_unknown(env, regs, BPF_REG_0);
15132         /* ld_abs load up to 32-bit skb data. */
15133         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
15134         return 0;
15135 }
15136
15137 static int check_return_code(struct bpf_verifier_env *env, int regno)
15138 {
15139         struct tnum enforce_attach_type_range = tnum_unknown;
15140         const struct bpf_prog *prog = env->prog;
15141         struct bpf_reg_state *reg;
15142         struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
15143         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
15144         int err;
15145         struct bpf_func_state *frame = env->cur_state->frame[0];
15146         const bool is_subprog = frame->subprogno;
15147
15148         /* LSM and struct_ops func-ptr's return type could be "void" */
15149         if (!is_subprog || frame->in_exception_callback_fn) {
15150                 switch (prog_type) {
15151                 case BPF_PROG_TYPE_LSM:
15152                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
15153                                 /* See below, can be 0 or 0-1 depending on hook. */
15154                                 break;
15155                         fallthrough;
15156                 case BPF_PROG_TYPE_STRUCT_OPS:
15157                         if (!prog->aux->attach_func_proto->type)
15158                                 return 0;
15159                         break;
15160                 default:
15161                         break;
15162                 }
15163         }
15164
15165         /* eBPF calling convention is such that R0 is used
15166          * to return the value from eBPF program.
15167          * Make sure that it's readable at this time
15168          * of bpf_exit, which means that program wrote
15169          * something into it earlier
15170          */
15171         err = check_reg_arg(env, regno, SRC_OP);
15172         if (err)
15173                 return err;
15174
15175         if (is_pointer_value(env, regno)) {
15176                 verbose(env, "R%d leaks addr as return value\n", regno);
15177                 return -EACCES;
15178         }
15179
15180         reg = cur_regs(env) + regno;
15181
15182         if (frame->in_async_callback_fn) {
15183                 /* enforce return zero from async callbacks like timer */
15184                 if (reg->type != SCALAR_VALUE) {
15185                         verbose(env, "In async callback the register R%d is not a known value (%s)\n",
15186                                 regno, reg_type_str(env, reg->type));
15187                         return -EINVAL;
15188                 }
15189
15190                 if (!tnum_in(const_0, reg->var_off)) {
15191                         verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
15192                         return -EINVAL;
15193                 }
15194                 return 0;
15195         }
15196
15197         if (is_subprog && !frame->in_exception_callback_fn) {
15198                 if (reg->type != SCALAR_VALUE) {
15199                         verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n",
15200                                 regno, reg_type_str(env, reg->type));
15201                         return -EINVAL;
15202                 }
15203                 return 0;
15204         }
15205
15206         switch (prog_type) {
15207         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
15208                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
15209                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
15210                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG ||
15211                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
15212                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
15213                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME ||
15214                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
15215                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME ||
15216                     env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME)
15217                         range = tnum_range(1, 1);
15218                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
15219                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
15220                         range = tnum_range(0, 3);
15221                 break;
15222         case BPF_PROG_TYPE_CGROUP_SKB:
15223                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
15224                         range = tnum_range(0, 3);
15225                         enforce_attach_type_range = tnum_range(2, 3);
15226                 }
15227                 break;
15228         case BPF_PROG_TYPE_CGROUP_SOCK:
15229         case BPF_PROG_TYPE_SOCK_OPS:
15230         case BPF_PROG_TYPE_CGROUP_DEVICE:
15231         case BPF_PROG_TYPE_CGROUP_SYSCTL:
15232         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
15233                 break;
15234         case BPF_PROG_TYPE_RAW_TRACEPOINT:
15235                 if (!env->prog->aux->attach_btf_id)
15236                         return 0;
15237                 range = tnum_const(0);
15238                 break;
15239         case BPF_PROG_TYPE_TRACING:
15240                 switch (env->prog->expected_attach_type) {
15241                 case BPF_TRACE_FENTRY:
15242                 case BPF_TRACE_FEXIT:
15243                         range = tnum_const(0);
15244                         break;
15245                 case BPF_TRACE_RAW_TP:
15246                 case BPF_MODIFY_RETURN:
15247                         return 0;
15248                 case BPF_TRACE_ITER:
15249                         break;
15250                 default:
15251                         return -ENOTSUPP;
15252                 }
15253                 break;
15254         case BPF_PROG_TYPE_SK_LOOKUP:
15255                 range = tnum_range(SK_DROP, SK_PASS);
15256                 break;
15257
15258         case BPF_PROG_TYPE_LSM:
15259                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
15260                         /* Regular BPF_PROG_TYPE_LSM programs can return
15261                          * any value.
15262                          */
15263                         return 0;
15264                 }
15265                 if (!env->prog->aux->attach_func_proto->type) {
15266                         /* Make sure programs that attach to void
15267                          * hooks don't try to modify return value.
15268                          */
15269                         range = tnum_range(1, 1);
15270                 }
15271                 break;
15272
15273         case BPF_PROG_TYPE_NETFILTER:
15274                 range = tnum_range(NF_DROP, NF_ACCEPT);
15275                 break;
15276         case BPF_PROG_TYPE_EXT:
15277                 /* freplace program can return anything as its return value
15278                  * depends on the to-be-replaced kernel func or bpf program.
15279                  */
15280         default:
15281                 return 0;
15282         }
15283
15284         if (reg->type != SCALAR_VALUE) {
15285                 verbose(env, "At program exit the register R%d is not a known value (%s)\n",
15286                         regno, reg_type_str(env, reg->type));
15287                 return -EINVAL;
15288         }
15289
15290         if (!tnum_in(range, reg->var_off)) {
15291                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
15292                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
15293                     prog_type == BPF_PROG_TYPE_LSM &&
15294                     !prog->aux->attach_func_proto->type)
15295                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
15296                 return -EINVAL;
15297         }
15298
15299         if (!tnum_is_unknown(enforce_attach_type_range) &&
15300             tnum_in(enforce_attach_type_range, reg->var_off))
15301                 env->prog->enforce_expected_attach_type = 1;
15302         return 0;
15303 }
15304
15305 /* non-recursive DFS pseudo code
15306  * 1  procedure DFS-iterative(G,v):
15307  * 2      label v as discovered
15308  * 3      let S be a stack
15309  * 4      S.push(v)
15310  * 5      while S is not empty
15311  * 6            t <- S.peek()
15312  * 7            if t is what we're looking for:
15313  * 8                return t
15314  * 9            for all edges e in G.adjacentEdges(t) do
15315  * 10               if edge e is already labelled
15316  * 11                   continue with the next edge
15317  * 12               w <- G.adjacentVertex(t,e)
15318  * 13               if vertex w is not discovered and not explored
15319  * 14                   label e as tree-edge
15320  * 15                   label w as discovered
15321  * 16                   S.push(w)
15322  * 17                   continue at 5
15323  * 18               else if vertex w is discovered
15324  * 19                   label e as back-edge
15325  * 20               else
15326  * 21                   // vertex w is explored
15327  * 22                   label e as forward- or cross-edge
15328  * 23           label t as explored
15329  * 24           S.pop()
15330  *
15331  * convention:
15332  * 0x10 - discovered
15333  * 0x11 - discovered and fall-through edge labelled
15334  * 0x12 - discovered and fall-through and branch edges labelled
15335  * 0x20 - explored
15336  */
15337
15338 enum {
15339         DISCOVERED = 0x10,
15340         EXPLORED = 0x20,
15341         FALLTHROUGH = 1,
15342         BRANCH = 2,
15343 };
15344
15345 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
15346 {
15347         env->insn_aux_data[idx].prune_point = true;
15348 }
15349
15350 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
15351 {
15352         return env->insn_aux_data[insn_idx].prune_point;
15353 }
15354
15355 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
15356 {
15357         env->insn_aux_data[idx].force_checkpoint = true;
15358 }
15359
15360 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
15361 {
15362         return env->insn_aux_data[insn_idx].force_checkpoint;
15363 }
15364
15365
15366 enum {
15367         DONE_EXPLORING = 0,
15368         KEEP_EXPLORING = 1,
15369 };
15370
15371 /* t, w, e - match pseudo-code above:
15372  * t - index of current instruction
15373  * w - next instruction
15374  * e - edge
15375  */
15376 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
15377                      bool loop_ok)
15378 {
15379         int *insn_stack = env->cfg.insn_stack;
15380         int *insn_state = env->cfg.insn_state;
15381
15382         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
15383                 return DONE_EXPLORING;
15384
15385         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
15386                 return DONE_EXPLORING;
15387
15388         if (w < 0 || w >= env->prog->len) {
15389                 verbose_linfo(env, t, "%d: ", t);
15390                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
15391                 return -EINVAL;
15392         }
15393
15394         if (e == BRANCH) {
15395                 /* mark branch target for state pruning */
15396                 mark_prune_point(env, w);
15397                 mark_jmp_point(env, w);
15398         }
15399
15400         if (insn_state[w] == 0) {
15401                 /* tree-edge */
15402                 insn_state[t] = DISCOVERED | e;
15403                 insn_state[w] = DISCOVERED;
15404                 if (env->cfg.cur_stack >= env->prog->len)
15405                         return -E2BIG;
15406                 insn_stack[env->cfg.cur_stack++] = w;
15407                 return KEEP_EXPLORING;
15408         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
15409                 if (loop_ok && env->bpf_capable)
15410                         return DONE_EXPLORING;
15411                 verbose_linfo(env, t, "%d: ", t);
15412                 verbose_linfo(env, w, "%d: ", w);
15413                 verbose(env, "back-edge from insn %d to %d\n", t, w);
15414                 return -EINVAL;
15415         } else if (insn_state[w] == EXPLORED) {
15416                 /* forward- or cross-edge */
15417                 insn_state[t] = DISCOVERED | e;
15418         } else {
15419                 verbose(env, "insn state internal bug\n");
15420                 return -EFAULT;
15421         }
15422         return DONE_EXPLORING;
15423 }
15424
15425 static int visit_func_call_insn(int t, struct bpf_insn *insns,
15426                                 struct bpf_verifier_env *env,
15427                                 bool visit_callee)
15428 {
15429         int ret;
15430
15431         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
15432         if (ret)
15433                 return ret;
15434
15435         mark_prune_point(env, t + 1);
15436         /* when we exit from subprog, we need to record non-linear history */
15437         mark_jmp_point(env, t + 1);
15438
15439         if (visit_callee) {
15440                 mark_prune_point(env, t);
15441                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
15442                                 /* It's ok to allow recursion from CFG point of
15443                                  * view. __check_func_call() will do the actual
15444                                  * check.
15445                                  */
15446                                 bpf_pseudo_func(insns + t));
15447         }
15448         return ret;
15449 }
15450
15451 /* Visits the instruction at index t and returns one of the following:
15452  *  < 0 - an error occurred
15453  *  DONE_EXPLORING - the instruction was fully explored
15454  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
15455  */
15456 static int visit_insn(int t, struct bpf_verifier_env *env)
15457 {
15458         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
15459         int ret, off;
15460
15461         if (bpf_pseudo_func(insn))
15462                 return visit_func_call_insn(t, insns, env, true);
15463
15464         /* All non-branch instructions have a single fall-through edge. */
15465         if (BPF_CLASS(insn->code) != BPF_JMP &&
15466             BPF_CLASS(insn->code) != BPF_JMP32)
15467                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
15468
15469         switch (BPF_OP(insn->code)) {
15470         case BPF_EXIT:
15471                 return DONE_EXPLORING;
15472
15473         case BPF_CALL:
15474                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
15475                         /* Mark this call insn as a prune point to trigger
15476                          * is_state_visited() check before call itself is
15477                          * processed by __check_func_call(). Otherwise new
15478                          * async state will be pushed for further exploration.
15479                          */
15480                         mark_prune_point(env, t);
15481                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
15482                         struct bpf_kfunc_call_arg_meta meta;
15483
15484                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
15485                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
15486                                 mark_prune_point(env, t);
15487                                 /* Checking and saving state checkpoints at iter_next() call
15488                                  * is crucial for fast convergence of open-coded iterator loop
15489                                  * logic, so we need to force it. If we don't do that,
15490                                  * is_state_visited() might skip saving a checkpoint, causing
15491                                  * unnecessarily long sequence of not checkpointed
15492                                  * instructions and jumps, leading to exhaustion of jump
15493                                  * history buffer, and potentially other undesired outcomes.
15494                                  * It is expected that with correct open-coded iterators
15495                                  * convergence will happen quickly, so we don't run a risk of
15496                                  * exhausting memory.
15497                                  */
15498                                 mark_force_checkpoint(env, t);
15499                         }
15500                 }
15501                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
15502
15503         case BPF_JA:
15504                 if (BPF_SRC(insn->code) != BPF_K)
15505                         return -EINVAL;
15506
15507                 if (BPF_CLASS(insn->code) == BPF_JMP)
15508                         off = insn->off;
15509                 else
15510                         off = insn->imm;
15511
15512                 /* unconditional jump with single edge */
15513                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
15514                                 true);
15515                 if (ret)
15516                         return ret;
15517
15518                 mark_prune_point(env, t + off + 1);
15519                 mark_jmp_point(env, t + off + 1);
15520
15521                 return ret;
15522
15523         default:
15524                 /* conditional jump with two edges */
15525                 mark_prune_point(env, t);
15526
15527                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
15528                 if (ret)
15529                         return ret;
15530
15531                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
15532         }
15533 }
15534
15535 /* non-recursive depth-first-search to detect loops in BPF program
15536  * loop == back-edge in directed graph
15537  */
15538 static int check_cfg(struct bpf_verifier_env *env)
15539 {
15540         int insn_cnt = env->prog->len;
15541         int *insn_stack, *insn_state;
15542         int ex_insn_beg, i, ret = 0;
15543         bool ex_done = false;
15544
15545         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15546         if (!insn_state)
15547                 return -ENOMEM;
15548
15549         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
15550         if (!insn_stack) {
15551                 kvfree(insn_state);
15552                 return -ENOMEM;
15553         }
15554
15555         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
15556         insn_stack[0] = 0; /* 0 is the first instruction */
15557         env->cfg.cur_stack = 1;
15558
15559 walk_cfg:
15560         while (env->cfg.cur_stack > 0) {
15561                 int t = insn_stack[env->cfg.cur_stack - 1];
15562
15563                 ret = visit_insn(t, env);
15564                 switch (ret) {
15565                 case DONE_EXPLORING:
15566                         insn_state[t] = EXPLORED;
15567                         env->cfg.cur_stack--;
15568                         break;
15569                 case KEEP_EXPLORING:
15570                         break;
15571                 default:
15572                         if (ret > 0) {
15573                                 verbose(env, "visit_insn internal bug\n");
15574                                 ret = -EFAULT;
15575                         }
15576                         goto err_free;
15577                 }
15578         }
15579
15580         if (env->cfg.cur_stack < 0) {
15581                 verbose(env, "pop stack internal bug\n");
15582                 ret = -EFAULT;
15583                 goto err_free;
15584         }
15585
15586         if (env->exception_callback_subprog && !ex_done) {
15587                 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start;
15588
15589                 insn_state[ex_insn_beg] = DISCOVERED;
15590                 insn_stack[0] = ex_insn_beg;
15591                 env->cfg.cur_stack = 1;
15592                 ex_done = true;
15593                 goto walk_cfg;
15594         }
15595
15596         for (i = 0; i < insn_cnt; i++) {
15597                 if (insn_state[i] != EXPLORED) {
15598                         verbose(env, "unreachable insn %d\n", i);
15599                         ret = -EINVAL;
15600                         goto err_free;
15601                 }
15602         }
15603         ret = 0; /* cfg looks good */
15604
15605 err_free:
15606         kvfree(insn_state);
15607         kvfree(insn_stack);
15608         env->cfg.insn_state = env->cfg.insn_stack = NULL;
15609         return ret;
15610 }
15611
15612 static int check_abnormal_return(struct bpf_verifier_env *env)
15613 {
15614         int i;
15615
15616         for (i = 1; i < env->subprog_cnt; i++) {
15617                 if (env->subprog_info[i].has_ld_abs) {
15618                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15619                         return -EINVAL;
15620                 }
15621                 if (env->subprog_info[i].has_tail_call) {
15622                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15623                         return -EINVAL;
15624                 }
15625         }
15626         return 0;
15627 }
15628
15629 /* The minimum supported BTF func info size */
15630 #define MIN_BPF_FUNCINFO_SIZE   8
15631 #define MAX_FUNCINFO_REC_SIZE   252
15632
15633 static int check_btf_func_early(struct bpf_verifier_env *env,
15634                                 const union bpf_attr *attr,
15635                                 bpfptr_t uattr)
15636 {
15637         u32 krec_size = sizeof(struct bpf_func_info);
15638         const struct btf_type *type, *func_proto;
15639         u32 i, nfuncs, urec_size, min_size;
15640         struct bpf_func_info *krecord;
15641         struct bpf_prog *prog;
15642         const struct btf *btf;
15643         u32 prev_offset = 0;
15644         bpfptr_t urecord;
15645         int ret = -ENOMEM;
15646
15647         nfuncs = attr->func_info_cnt;
15648         if (!nfuncs) {
15649                 if (check_abnormal_return(env))
15650                         return -EINVAL;
15651                 return 0;
15652         }
15653
15654         urec_size = attr->func_info_rec_size;
15655         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15656             urec_size > MAX_FUNCINFO_REC_SIZE ||
15657             urec_size % sizeof(u32)) {
15658                 verbose(env, "invalid func info rec size %u\n", urec_size);
15659                 return -EINVAL;
15660         }
15661
15662         prog = env->prog;
15663         btf = prog->aux->btf;
15664
15665         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15666         min_size = min_t(u32, krec_size, urec_size);
15667
15668         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15669         if (!krecord)
15670                 return -ENOMEM;
15671
15672         for (i = 0; i < nfuncs; i++) {
15673                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15674                 if (ret) {
15675                         if (ret == -E2BIG) {
15676                                 verbose(env, "nonzero tailing record in func info");
15677                                 /* set the size kernel expects so loader can zero
15678                                  * out the rest of the record.
15679                                  */
15680                                 if (copy_to_bpfptr_offset(uattr,
15681                                                           offsetof(union bpf_attr, func_info_rec_size),
15682                                                           &min_size, sizeof(min_size)))
15683                                         ret = -EFAULT;
15684                         }
15685                         goto err_free;
15686                 }
15687
15688                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15689                         ret = -EFAULT;
15690                         goto err_free;
15691                 }
15692
15693                 /* check insn_off */
15694                 ret = -EINVAL;
15695                 if (i == 0) {
15696                         if (krecord[i].insn_off) {
15697                                 verbose(env,
15698                                         "nonzero insn_off %u for the first func info record",
15699                                         krecord[i].insn_off);
15700                                 goto err_free;
15701                         }
15702                 } else if (krecord[i].insn_off <= prev_offset) {
15703                         verbose(env,
15704                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15705                                 krecord[i].insn_off, prev_offset);
15706                         goto err_free;
15707                 }
15708
15709                 /* check type_id */
15710                 type = btf_type_by_id(btf, krecord[i].type_id);
15711                 if (!type || !btf_type_is_func(type)) {
15712                         verbose(env, "invalid type id %d in func info",
15713                                 krecord[i].type_id);
15714                         goto err_free;
15715                 }
15716
15717                 func_proto = btf_type_by_id(btf, type->type);
15718                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15719                         /* btf_func_check() already verified it during BTF load */
15720                         goto err_free;
15721
15722                 prev_offset = krecord[i].insn_off;
15723                 bpfptr_add(&urecord, urec_size);
15724         }
15725
15726         prog->aux->func_info = krecord;
15727         prog->aux->func_info_cnt = nfuncs;
15728         return 0;
15729
15730 err_free:
15731         kvfree(krecord);
15732         return ret;
15733 }
15734
15735 static int check_btf_func(struct bpf_verifier_env *env,
15736                           const union bpf_attr *attr,
15737                           bpfptr_t uattr)
15738 {
15739         const struct btf_type *type, *func_proto, *ret_type;
15740         u32 i, nfuncs, urec_size;
15741         struct bpf_func_info *krecord;
15742         struct bpf_func_info_aux *info_aux = NULL;
15743         struct bpf_prog *prog;
15744         const struct btf *btf;
15745         bpfptr_t urecord;
15746         bool scalar_return;
15747         int ret = -ENOMEM;
15748
15749         nfuncs = attr->func_info_cnt;
15750         if (!nfuncs) {
15751                 if (check_abnormal_return(env))
15752                         return -EINVAL;
15753                 return 0;
15754         }
15755         if (nfuncs != env->subprog_cnt) {
15756                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15757                 return -EINVAL;
15758         }
15759
15760         urec_size = attr->func_info_rec_size;
15761
15762         prog = env->prog;
15763         btf = prog->aux->btf;
15764
15765         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15766
15767         krecord = prog->aux->func_info;
15768         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15769         if (!info_aux)
15770                 return -ENOMEM;
15771
15772         for (i = 0; i < nfuncs; i++) {
15773                 /* check insn_off */
15774                 ret = -EINVAL;
15775
15776                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15777                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15778                         goto err_free;
15779                 }
15780
15781                 /* Already checked type_id */
15782                 type = btf_type_by_id(btf, krecord[i].type_id);
15783                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15784                 /* Already checked func_proto */
15785                 func_proto = btf_type_by_id(btf, type->type);
15786
15787                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15788                 scalar_return =
15789                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15790                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15791                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15792                         goto err_free;
15793                 }
15794                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15795                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15796                         goto err_free;
15797                 }
15798
15799                 bpfptr_add(&urecord, urec_size);
15800         }
15801
15802         prog->aux->func_info_aux = info_aux;
15803         return 0;
15804
15805 err_free:
15806         kfree(info_aux);
15807         return ret;
15808 }
15809
15810 static void adjust_btf_func(struct bpf_verifier_env *env)
15811 {
15812         struct bpf_prog_aux *aux = env->prog->aux;
15813         int i;
15814
15815         if (!aux->func_info)
15816                 return;
15817
15818         /* func_info is not available for hidden subprogs */
15819         for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
15820                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15821 }
15822
15823 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15824 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15825
15826 static int check_btf_line(struct bpf_verifier_env *env,
15827                           const union bpf_attr *attr,
15828                           bpfptr_t uattr)
15829 {
15830         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15831         struct bpf_subprog_info *sub;
15832         struct bpf_line_info *linfo;
15833         struct bpf_prog *prog;
15834         const struct btf *btf;
15835         bpfptr_t ulinfo;
15836         int err;
15837
15838         nr_linfo = attr->line_info_cnt;
15839         if (!nr_linfo)
15840                 return 0;
15841         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15842                 return -EINVAL;
15843
15844         rec_size = attr->line_info_rec_size;
15845         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15846             rec_size > MAX_LINEINFO_REC_SIZE ||
15847             rec_size & (sizeof(u32) - 1))
15848                 return -EINVAL;
15849
15850         /* Need to zero it in case the userspace may
15851          * pass in a smaller bpf_line_info object.
15852          */
15853         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15854                          GFP_KERNEL | __GFP_NOWARN);
15855         if (!linfo)
15856                 return -ENOMEM;
15857
15858         prog = env->prog;
15859         btf = prog->aux->btf;
15860
15861         s = 0;
15862         sub = env->subprog_info;
15863         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15864         expected_size = sizeof(struct bpf_line_info);
15865         ncopy = min_t(u32, expected_size, rec_size);
15866         for (i = 0; i < nr_linfo; i++) {
15867                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15868                 if (err) {
15869                         if (err == -E2BIG) {
15870                                 verbose(env, "nonzero tailing record in line_info");
15871                                 if (copy_to_bpfptr_offset(uattr,
15872                                                           offsetof(union bpf_attr, line_info_rec_size),
15873                                                           &expected_size, sizeof(expected_size)))
15874                                         err = -EFAULT;
15875                         }
15876                         goto err_free;
15877                 }
15878
15879                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15880                         err = -EFAULT;
15881                         goto err_free;
15882                 }
15883
15884                 /*
15885                  * Check insn_off to ensure
15886                  * 1) strictly increasing AND
15887                  * 2) bounded by prog->len
15888                  *
15889                  * The linfo[0].insn_off == 0 check logically falls into
15890                  * the later "missing bpf_line_info for func..." case
15891                  * because the first linfo[0].insn_off must be the
15892                  * first sub also and the first sub must have
15893                  * subprog_info[0].start == 0.
15894                  */
15895                 if ((i && linfo[i].insn_off <= prev_offset) ||
15896                     linfo[i].insn_off >= prog->len) {
15897                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15898                                 i, linfo[i].insn_off, prev_offset,
15899                                 prog->len);
15900                         err = -EINVAL;
15901                         goto err_free;
15902                 }
15903
15904                 if (!prog->insnsi[linfo[i].insn_off].code) {
15905                         verbose(env,
15906                                 "Invalid insn code at line_info[%u].insn_off\n",
15907                                 i);
15908                         err = -EINVAL;
15909                         goto err_free;
15910                 }
15911
15912                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15913                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15914                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15915                         err = -EINVAL;
15916                         goto err_free;
15917                 }
15918
15919                 if (s != env->subprog_cnt) {
15920                         if (linfo[i].insn_off == sub[s].start) {
15921                                 sub[s].linfo_idx = i;
15922                                 s++;
15923                         } else if (sub[s].start < linfo[i].insn_off) {
15924                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15925                                 err = -EINVAL;
15926                                 goto err_free;
15927                         }
15928                 }
15929
15930                 prev_offset = linfo[i].insn_off;
15931                 bpfptr_add(&ulinfo, rec_size);
15932         }
15933
15934         if (s != env->subprog_cnt) {
15935                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15936                         env->subprog_cnt - s, s);
15937                 err = -EINVAL;
15938                 goto err_free;
15939         }
15940
15941         prog->aux->linfo = linfo;
15942         prog->aux->nr_linfo = nr_linfo;
15943
15944         return 0;
15945
15946 err_free:
15947         kvfree(linfo);
15948         return err;
15949 }
15950
15951 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15952 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15953
15954 static int check_core_relo(struct bpf_verifier_env *env,
15955                            const union bpf_attr *attr,
15956                            bpfptr_t uattr)
15957 {
15958         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15959         struct bpf_core_relo core_relo = {};
15960         struct bpf_prog *prog = env->prog;
15961         const struct btf *btf = prog->aux->btf;
15962         struct bpf_core_ctx ctx = {
15963                 .log = &env->log,
15964                 .btf = btf,
15965         };
15966         bpfptr_t u_core_relo;
15967         int err;
15968
15969         nr_core_relo = attr->core_relo_cnt;
15970         if (!nr_core_relo)
15971                 return 0;
15972         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15973                 return -EINVAL;
15974
15975         rec_size = attr->core_relo_rec_size;
15976         if (rec_size < MIN_CORE_RELO_SIZE ||
15977             rec_size > MAX_CORE_RELO_SIZE ||
15978             rec_size % sizeof(u32))
15979                 return -EINVAL;
15980
15981         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15982         expected_size = sizeof(struct bpf_core_relo);
15983         ncopy = min_t(u32, expected_size, rec_size);
15984
15985         /* Unlike func_info and line_info, copy and apply each CO-RE
15986          * relocation record one at a time.
15987          */
15988         for (i = 0; i < nr_core_relo; i++) {
15989                 /* future proofing when sizeof(bpf_core_relo) changes */
15990                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15991                 if (err) {
15992                         if (err == -E2BIG) {
15993                                 verbose(env, "nonzero tailing record in core_relo");
15994                                 if (copy_to_bpfptr_offset(uattr,
15995                                                           offsetof(union bpf_attr, core_relo_rec_size),
15996                                                           &expected_size, sizeof(expected_size)))
15997                                         err = -EFAULT;
15998                         }
15999                         break;
16000                 }
16001
16002                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
16003                         err = -EFAULT;
16004                         break;
16005                 }
16006
16007                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
16008                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
16009                                 i, core_relo.insn_off, prog->len);
16010                         err = -EINVAL;
16011                         break;
16012                 }
16013
16014                 err = bpf_core_apply(&ctx, &core_relo, i,
16015                                      &prog->insnsi[core_relo.insn_off / 8]);
16016                 if (err)
16017                         break;
16018                 bpfptr_add(&u_core_relo, rec_size);
16019         }
16020         return err;
16021 }
16022
16023 static int check_btf_info_early(struct bpf_verifier_env *env,
16024                                 const union bpf_attr *attr,
16025                                 bpfptr_t uattr)
16026 {
16027         struct btf *btf;
16028         int err;
16029
16030         if (!attr->func_info_cnt && !attr->line_info_cnt) {
16031                 if (check_abnormal_return(env))
16032                         return -EINVAL;
16033                 return 0;
16034         }
16035
16036         btf = btf_get_by_fd(attr->prog_btf_fd);
16037         if (IS_ERR(btf))
16038                 return PTR_ERR(btf);
16039         if (btf_is_kernel(btf)) {
16040                 btf_put(btf);
16041                 return -EACCES;
16042         }
16043         env->prog->aux->btf = btf;
16044
16045         err = check_btf_func_early(env, attr, uattr);
16046         if (err)
16047                 return err;
16048         return 0;
16049 }
16050
16051 static int check_btf_info(struct bpf_verifier_env *env,
16052                           const union bpf_attr *attr,
16053                           bpfptr_t uattr)
16054 {
16055         int err;
16056
16057         if (!attr->func_info_cnt && !attr->line_info_cnt) {
16058                 if (check_abnormal_return(env))
16059                         return -EINVAL;
16060                 return 0;
16061         }
16062
16063         err = check_btf_func(env, attr, uattr);
16064         if (err)
16065                 return err;
16066
16067         err = check_btf_line(env, attr, uattr);
16068         if (err)
16069                 return err;
16070
16071         err = check_core_relo(env, attr, uattr);
16072         if (err)
16073                 return err;
16074
16075         return 0;
16076 }
16077
16078 /* check %cur's range satisfies %old's */
16079 static bool range_within(struct bpf_reg_state *old,
16080                          struct bpf_reg_state *cur)
16081 {
16082         return old->umin_value <= cur->umin_value &&
16083                old->umax_value >= cur->umax_value &&
16084                old->smin_value <= cur->smin_value &&
16085                old->smax_value >= cur->smax_value &&
16086                old->u32_min_value <= cur->u32_min_value &&
16087                old->u32_max_value >= cur->u32_max_value &&
16088                old->s32_min_value <= cur->s32_min_value &&
16089                old->s32_max_value >= cur->s32_max_value;
16090 }
16091
16092 /* If in the old state two registers had the same id, then they need to have
16093  * the same id in the new state as well.  But that id could be different from
16094  * the old state, so we need to track the mapping from old to new ids.
16095  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
16096  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
16097  * regs with a different old id could still have new id 9, we don't care about
16098  * that.
16099  * So we look through our idmap to see if this old id has been seen before.  If
16100  * so, we require the new id to match; otherwise, we add the id pair to the map.
16101  */
16102 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16103 {
16104         struct bpf_id_pair *map = idmap->map;
16105         unsigned int i;
16106
16107         /* either both IDs should be set or both should be zero */
16108         if (!!old_id != !!cur_id)
16109                 return false;
16110
16111         if (old_id == 0) /* cur_id == 0 as well */
16112                 return true;
16113
16114         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
16115                 if (!map[i].old) {
16116                         /* Reached an empty slot; haven't seen this id before */
16117                         map[i].old = old_id;
16118                         map[i].cur = cur_id;
16119                         return true;
16120                 }
16121                 if (map[i].old == old_id)
16122                         return map[i].cur == cur_id;
16123                 if (map[i].cur == cur_id)
16124                         return false;
16125         }
16126         /* We ran out of idmap slots, which should be impossible */
16127         WARN_ON_ONCE(1);
16128         return false;
16129 }
16130
16131 /* Similar to check_ids(), but allocate a unique temporary ID
16132  * for 'old_id' or 'cur_id' of zero.
16133  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
16134  */
16135 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
16136 {
16137         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
16138         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
16139
16140         return check_ids(old_id, cur_id, idmap);
16141 }
16142
16143 static void clean_func_state(struct bpf_verifier_env *env,
16144                              struct bpf_func_state *st)
16145 {
16146         enum bpf_reg_liveness live;
16147         int i, j;
16148
16149         for (i = 0; i < BPF_REG_FP; i++) {
16150                 live = st->regs[i].live;
16151                 /* liveness must not touch this register anymore */
16152                 st->regs[i].live |= REG_LIVE_DONE;
16153                 if (!(live & REG_LIVE_READ))
16154                         /* since the register is unused, clear its state
16155                          * to make further comparison simpler
16156                          */
16157                         __mark_reg_not_init(env, &st->regs[i]);
16158         }
16159
16160         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
16161                 live = st->stack[i].spilled_ptr.live;
16162                 /* liveness must not touch this stack slot anymore */
16163                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
16164                 if (!(live & REG_LIVE_READ)) {
16165                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
16166                         for (j = 0; j < BPF_REG_SIZE; j++)
16167                                 st->stack[i].slot_type[j] = STACK_INVALID;
16168                 }
16169         }
16170 }
16171
16172 static void clean_verifier_state(struct bpf_verifier_env *env,
16173                                  struct bpf_verifier_state *st)
16174 {
16175         int i;
16176
16177         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
16178                 /* all regs in this state in all frames were already marked */
16179                 return;
16180
16181         for (i = 0; i <= st->curframe; i++)
16182                 clean_func_state(env, st->frame[i]);
16183 }
16184
16185 /* the parentage chains form a tree.
16186  * the verifier states are added to state lists at given insn and
16187  * pushed into state stack for future exploration.
16188  * when the verifier reaches bpf_exit insn some of the verifer states
16189  * stored in the state lists have their final liveness state already,
16190  * but a lot of states will get revised from liveness point of view when
16191  * the verifier explores other branches.
16192  * Example:
16193  * 1: r0 = 1
16194  * 2: if r1 == 100 goto pc+1
16195  * 3: r0 = 2
16196  * 4: exit
16197  * when the verifier reaches exit insn the register r0 in the state list of
16198  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
16199  * of insn 2 and goes exploring further. At the insn 4 it will walk the
16200  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
16201  *
16202  * Since the verifier pushes the branch states as it sees them while exploring
16203  * the program the condition of walking the branch instruction for the second
16204  * time means that all states below this branch were already explored and
16205  * their final liveness marks are already propagated.
16206  * Hence when the verifier completes the search of state list in is_state_visited()
16207  * we can call this clean_live_states() function to mark all liveness states
16208  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
16209  * will not be used.
16210  * This function also clears the registers and stack for states that !READ
16211  * to simplify state merging.
16212  *
16213  * Important note here that walking the same branch instruction in the callee
16214  * doesn't meant that the states are DONE. The verifier has to compare
16215  * the callsites
16216  */
16217 static void clean_live_states(struct bpf_verifier_env *env, int insn,
16218                               struct bpf_verifier_state *cur)
16219 {
16220         struct bpf_verifier_state_list *sl;
16221
16222         sl = *explored_state(env, insn);
16223         while (sl) {
16224                 if (sl->state.branches)
16225                         goto next;
16226                 if (sl->state.insn_idx != insn ||
16227                     !same_callsites(&sl->state, cur))
16228                         goto next;
16229                 clean_verifier_state(env, &sl->state);
16230 next:
16231                 sl = sl->next;
16232         }
16233 }
16234
16235 static bool regs_exact(const struct bpf_reg_state *rold,
16236                        const struct bpf_reg_state *rcur,
16237                        struct bpf_idmap *idmap)
16238 {
16239         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16240                check_ids(rold->id, rcur->id, idmap) &&
16241                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16242 }
16243
16244 /* Returns true if (rold safe implies rcur safe) */
16245 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
16246                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap, bool exact)
16247 {
16248         if (exact)
16249                 return regs_exact(rold, rcur, idmap);
16250
16251         if (!(rold->live & REG_LIVE_READ))
16252                 /* explored state didn't use this */
16253                 return true;
16254         if (rold->type == NOT_INIT)
16255                 /* explored state can't have used this */
16256                 return true;
16257         if (rcur->type == NOT_INIT)
16258                 return false;
16259
16260         /* Enforce that register types have to match exactly, including their
16261          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
16262          * rule.
16263          *
16264          * One can make a point that using a pointer register as unbounded
16265          * SCALAR would be technically acceptable, but this could lead to
16266          * pointer leaks because scalars are allowed to leak while pointers
16267          * are not. We could make this safe in special cases if root is
16268          * calling us, but it's probably not worth the hassle.
16269          *
16270          * Also, register types that are *not* MAYBE_NULL could technically be
16271          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
16272          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
16273          * to the same map).
16274          * However, if the old MAYBE_NULL register then got NULL checked,
16275          * doing so could have affected others with the same id, and we can't
16276          * check for that because we lost the id when we converted to
16277          * a non-MAYBE_NULL variant.
16278          * So, as a general rule we don't allow mixing MAYBE_NULL and
16279          * non-MAYBE_NULL registers as well.
16280          */
16281         if (rold->type != rcur->type)
16282                 return false;
16283
16284         switch (base_type(rold->type)) {
16285         case SCALAR_VALUE:
16286                 if (env->explore_alu_limits) {
16287                         /* explore_alu_limits disables tnum_in() and range_within()
16288                          * logic and requires everything to be strict
16289                          */
16290                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
16291                                check_scalar_ids(rold->id, rcur->id, idmap);
16292                 }
16293                 if (!rold->precise)
16294                         return true;
16295                 /* Why check_ids() for scalar registers?
16296                  *
16297                  * Consider the following BPF code:
16298                  *   1: r6 = ... unbound scalar, ID=a ...
16299                  *   2: r7 = ... unbound scalar, ID=b ...
16300                  *   3: if (r6 > r7) goto +1
16301                  *   4: r6 = r7
16302                  *   5: if (r6 > X) goto ...
16303                  *   6: ... memory operation using r7 ...
16304                  *
16305                  * First verification path is [1-6]:
16306                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
16307                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
16308                  *   r7 <= X, because r6 and r7 share same id.
16309                  * Next verification path is [1-4, 6].
16310                  *
16311                  * Instruction (6) would be reached in two states:
16312                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
16313                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
16314                  *
16315                  * Use check_ids() to distinguish these states.
16316                  * ---
16317                  * Also verify that new value satisfies old value range knowledge.
16318                  */
16319                 return range_within(rold, rcur) &&
16320                        tnum_in(rold->var_off, rcur->var_off) &&
16321                        check_scalar_ids(rold->id, rcur->id, idmap);
16322         case PTR_TO_MAP_KEY:
16323         case PTR_TO_MAP_VALUE:
16324         case PTR_TO_MEM:
16325         case PTR_TO_BUF:
16326         case PTR_TO_TP_BUFFER:
16327                 /* If the new min/max/var_off satisfy the old ones and
16328                  * everything else matches, we are OK.
16329                  */
16330                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
16331                        range_within(rold, rcur) &&
16332                        tnum_in(rold->var_off, rcur->var_off) &&
16333                        check_ids(rold->id, rcur->id, idmap) &&
16334                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
16335         case PTR_TO_PACKET_META:
16336         case PTR_TO_PACKET:
16337                 /* We must have at least as much range as the old ptr
16338                  * did, so that any accesses which were safe before are
16339                  * still safe.  This is true even if old range < old off,
16340                  * since someone could have accessed through (ptr - k), or
16341                  * even done ptr -= k in a register, to get a safe access.
16342                  */
16343                 if (rold->range > rcur->range)
16344                         return false;
16345                 /* If the offsets don't match, we can't trust our alignment;
16346                  * nor can we be sure that we won't fall out of range.
16347                  */
16348                 if (rold->off != rcur->off)
16349                         return false;
16350                 /* id relations must be preserved */
16351                 if (!check_ids(rold->id, rcur->id, idmap))
16352                         return false;
16353                 /* new val must satisfy old val knowledge */
16354                 return range_within(rold, rcur) &&
16355                        tnum_in(rold->var_off, rcur->var_off);
16356         case PTR_TO_STACK:
16357                 /* two stack pointers are equal only if they're pointing to
16358                  * the same stack frame, since fp-8 in foo != fp-8 in bar
16359                  */
16360                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
16361         default:
16362                 return regs_exact(rold, rcur, idmap);
16363         }
16364 }
16365
16366 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
16367                       struct bpf_func_state *cur, struct bpf_idmap *idmap, bool exact)
16368 {
16369         int i, spi;
16370
16371         /* walk slots of the explored stack and ignore any additional
16372          * slots in the current stack, since explored(safe) state
16373          * didn't use them
16374          */
16375         for (i = 0; i < old->allocated_stack; i++) {
16376                 struct bpf_reg_state *old_reg, *cur_reg;
16377
16378                 spi = i / BPF_REG_SIZE;
16379
16380                 if (exact &&
16381                     old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16382                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16383                         return false;
16384
16385                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) && !exact) {
16386                         i += BPF_REG_SIZE - 1;
16387                         /* explored state didn't use this */
16388                         continue;
16389                 }
16390
16391                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
16392                         continue;
16393
16394                 if (env->allow_uninit_stack &&
16395                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
16396                         continue;
16397
16398                 /* explored stack has more populated slots than current stack
16399                  * and these slots were used
16400                  */
16401                 if (i >= cur->allocated_stack)
16402                         return false;
16403
16404                 /* if old state was safe with misc data in the stack
16405                  * it will be safe with zero-initialized stack.
16406                  * The opposite is not true
16407                  */
16408                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
16409                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
16410                         continue;
16411                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
16412                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
16413                         /* Ex: old explored (safe) state has STACK_SPILL in
16414                          * this stack slot, but current has STACK_MISC ->
16415                          * this verifier states are not equivalent,
16416                          * return false to continue verification of this path
16417                          */
16418                         return false;
16419                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
16420                         continue;
16421                 /* Both old and cur are having same slot_type */
16422                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
16423                 case STACK_SPILL:
16424                         /* when explored and current stack slot are both storing
16425                          * spilled registers, check that stored pointers types
16426                          * are the same as well.
16427                          * Ex: explored safe path could have stored
16428                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
16429                          * but current path has stored:
16430                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
16431                          * such verifier states are not equivalent.
16432                          * return false to continue verification of this path
16433                          */
16434                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
16435                                      &cur->stack[spi].spilled_ptr, idmap, exact))
16436                                 return false;
16437                         break;
16438                 case STACK_DYNPTR:
16439                         old_reg = &old->stack[spi].spilled_ptr;
16440                         cur_reg = &cur->stack[spi].spilled_ptr;
16441                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
16442                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
16443                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16444                                 return false;
16445                         break;
16446                 case STACK_ITER:
16447                         old_reg = &old->stack[spi].spilled_ptr;
16448                         cur_reg = &cur->stack[spi].spilled_ptr;
16449                         /* iter.depth is not compared between states as it
16450                          * doesn't matter for correctness and would otherwise
16451                          * prevent convergence; we maintain it only to prevent
16452                          * infinite loop check triggering, see
16453                          * iter_active_depths_differ()
16454                          */
16455                         if (old_reg->iter.btf != cur_reg->iter.btf ||
16456                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
16457                             old_reg->iter.state != cur_reg->iter.state ||
16458                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
16459                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
16460                                 return false;
16461                         break;
16462                 case STACK_MISC:
16463                 case STACK_ZERO:
16464                 case STACK_INVALID:
16465                         continue;
16466                 /* Ensure that new unhandled slot types return false by default */
16467                 default:
16468                         return false;
16469                 }
16470         }
16471         return true;
16472 }
16473
16474 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
16475                     struct bpf_idmap *idmap)
16476 {
16477         int i;
16478
16479         if (old->acquired_refs != cur->acquired_refs)
16480                 return false;
16481
16482         for (i = 0; i < old->acquired_refs; i++) {
16483                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
16484                         return false;
16485         }
16486
16487         return true;
16488 }
16489
16490 /* compare two verifier states
16491  *
16492  * all states stored in state_list are known to be valid, since
16493  * verifier reached 'bpf_exit' instruction through them
16494  *
16495  * this function is called when verifier exploring different branches of
16496  * execution popped from the state stack. If it sees an old state that has
16497  * more strict register state and more strict stack state then this execution
16498  * branch doesn't need to be explored further, since verifier already
16499  * concluded that more strict state leads to valid finish.
16500  *
16501  * Therefore two states are equivalent if register state is more conservative
16502  * and explored stack state is more conservative than the current one.
16503  * Example:
16504  *       explored                   current
16505  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
16506  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
16507  *
16508  * In other words if current stack state (one being explored) has more
16509  * valid slots than old one that already passed validation, it means
16510  * the verifier can stop exploring and conclude that current state is valid too
16511  *
16512  * Similarly with registers. If explored state has register type as invalid
16513  * whereas register type in current state is meaningful, it means that
16514  * the current state will reach 'bpf_exit' instruction safely
16515  */
16516 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
16517                               struct bpf_func_state *cur, bool exact)
16518 {
16519         int i;
16520
16521         for (i = 0; i < MAX_BPF_REG; i++)
16522                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
16523                              &env->idmap_scratch, exact))
16524                         return false;
16525
16526         if (!stacksafe(env, old, cur, &env->idmap_scratch, exact))
16527                 return false;
16528
16529         if (!refsafe(old, cur, &env->idmap_scratch))
16530                 return false;
16531
16532         return true;
16533 }
16534
16535 static void reset_idmap_scratch(struct bpf_verifier_env *env)
16536 {
16537         env->idmap_scratch.tmp_id_gen = env->id_gen;
16538         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
16539 }
16540
16541 static bool states_equal(struct bpf_verifier_env *env,
16542                          struct bpf_verifier_state *old,
16543                          struct bpf_verifier_state *cur,
16544                          bool exact)
16545 {
16546         int i;
16547
16548         if (old->curframe != cur->curframe)
16549                 return false;
16550
16551         reset_idmap_scratch(env);
16552
16553         /* Verification state from speculative execution simulation
16554          * must never prune a non-speculative execution one.
16555          */
16556         if (old->speculative && !cur->speculative)
16557                 return false;
16558
16559         if (old->active_lock.ptr != cur->active_lock.ptr)
16560                 return false;
16561
16562         /* Old and cur active_lock's have to be either both present
16563          * or both absent.
16564          */
16565         if (!!old->active_lock.id != !!cur->active_lock.id)
16566                 return false;
16567
16568         if (old->active_lock.id &&
16569             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
16570                 return false;
16571
16572         if (old->active_rcu_lock != cur->active_rcu_lock)
16573                 return false;
16574
16575         /* for states to be equal callsites have to be the same
16576          * and all frame states need to be equivalent
16577          */
16578         for (i = 0; i <= old->curframe; i++) {
16579                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
16580                         return false;
16581                 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact))
16582                         return false;
16583         }
16584         return true;
16585 }
16586
16587 /* Return 0 if no propagation happened. Return negative error code if error
16588  * happened. Otherwise, return the propagated bit.
16589  */
16590 static int propagate_liveness_reg(struct bpf_verifier_env *env,
16591                                   struct bpf_reg_state *reg,
16592                                   struct bpf_reg_state *parent_reg)
16593 {
16594         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
16595         u8 flag = reg->live & REG_LIVE_READ;
16596         int err;
16597
16598         /* When comes here, read flags of PARENT_REG or REG could be any of
16599          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
16600          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
16601          */
16602         if (parent_flag == REG_LIVE_READ64 ||
16603             /* Or if there is no read flag from REG. */
16604             !flag ||
16605             /* Or if the read flag from REG is the same as PARENT_REG. */
16606             parent_flag == flag)
16607                 return 0;
16608
16609         err = mark_reg_read(env, reg, parent_reg, flag);
16610         if (err)
16611                 return err;
16612
16613         return flag;
16614 }
16615
16616 /* A write screens off any subsequent reads; but write marks come from the
16617  * straight-line code between a state and its parent.  When we arrive at an
16618  * equivalent state (jump target or such) we didn't arrive by the straight-line
16619  * code, so read marks in the state must propagate to the parent regardless
16620  * of the state's write marks. That's what 'parent == state->parent' comparison
16621  * in mark_reg_read() is for.
16622  */
16623 static int propagate_liveness(struct bpf_verifier_env *env,
16624                               const struct bpf_verifier_state *vstate,
16625                               struct bpf_verifier_state *vparent)
16626 {
16627         struct bpf_reg_state *state_reg, *parent_reg;
16628         struct bpf_func_state *state, *parent;
16629         int i, frame, err = 0;
16630
16631         if (vparent->curframe != vstate->curframe) {
16632                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
16633                      vparent->curframe, vstate->curframe);
16634                 return -EFAULT;
16635         }
16636         /* Propagate read liveness of registers... */
16637         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
16638         for (frame = 0; frame <= vstate->curframe; frame++) {
16639                 parent = vparent->frame[frame];
16640                 state = vstate->frame[frame];
16641                 parent_reg = parent->regs;
16642                 state_reg = state->regs;
16643                 /* We don't need to worry about FP liveness, it's read-only */
16644                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
16645                         err = propagate_liveness_reg(env, &state_reg[i],
16646                                                      &parent_reg[i]);
16647                         if (err < 0)
16648                                 return err;
16649                         if (err == REG_LIVE_READ64)
16650                                 mark_insn_zext(env, &parent_reg[i]);
16651                 }
16652
16653                 /* Propagate stack slots. */
16654                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
16655                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
16656                         parent_reg = &parent->stack[i].spilled_ptr;
16657                         state_reg = &state->stack[i].spilled_ptr;
16658                         err = propagate_liveness_reg(env, state_reg,
16659                                                      parent_reg);
16660                         if (err < 0)
16661                                 return err;
16662                 }
16663         }
16664         return 0;
16665 }
16666
16667 /* find precise scalars in the previous equivalent state and
16668  * propagate them into the current state
16669  */
16670 static int propagate_precision(struct bpf_verifier_env *env,
16671                                const struct bpf_verifier_state *old)
16672 {
16673         struct bpf_reg_state *state_reg;
16674         struct bpf_func_state *state;
16675         int i, err = 0, fr;
16676         bool first;
16677
16678         for (fr = old->curframe; fr >= 0; fr--) {
16679                 state = old->frame[fr];
16680                 state_reg = state->regs;
16681                 first = true;
16682                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
16683                         if (state_reg->type != SCALAR_VALUE ||
16684                             !state_reg->precise ||
16685                             !(state_reg->live & REG_LIVE_READ))
16686                                 continue;
16687                         if (env->log.level & BPF_LOG_LEVEL2) {
16688                                 if (first)
16689                                         verbose(env, "frame %d: propagating r%d", fr, i);
16690                                 else
16691                                         verbose(env, ",r%d", i);
16692                         }
16693                         bt_set_frame_reg(&env->bt, fr, i);
16694                         first = false;
16695                 }
16696
16697                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16698                         if (!is_spilled_reg(&state->stack[i]))
16699                                 continue;
16700                         state_reg = &state->stack[i].spilled_ptr;
16701                         if (state_reg->type != SCALAR_VALUE ||
16702                             !state_reg->precise ||
16703                             !(state_reg->live & REG_LIVE_READ))
16704                                 continue;
16705                         if (env->log.level & BPF_LOG_LEVEL2) {
16706                                 if (first)
16707                                         verbose(env, "frame %d: propagating fp%d",
16708                                                 fr, (-i - 1) * BPF_REG_SIZE);
16709                                 else
16710                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16711                         }
16712                         bt_set_frame_slot(&env->bt, fr, i);
16713                         first = false;
16714                 }
16715                 if (!first)
16716                         verbose(env, "\n");
16717         }
16718
16719         err = mark_chain_precision_batch(env);
16720         if (err < 0)
16721                 return err;
16722
16723         return 0;
16724 }
16725
16726 static bool states_maybe_looping(struct bpf_verifier_state *old,
16727                                  struct bpf_verifier_state *cur)
16728 {
16729         struct bpf_func_state *fold, *fcur;
16730         int i, fr = cur->curframe;
16731
16732         if (old->curframe != fr)
16733                 return false;
16734
16735         fold = old->frame[fr];
16736         fcur = cur->frame[fr];
16737         for (i = 0; i < MAX_BPF_REG; i++)
16738                 if (memcmp(&fold->regs[i], &fcur->regs[i],
16739                            offsetof(struct bpf_reg_state, parent)))
16740                         return false;
16741         return true;
16742 }
16743
16744 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16745 {
16746         return env->insn_aux_data[insn_idx].is_iter_next;
16747 }
16748
16749 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16750  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16751  * states to match, which otherwise would look like an infinite loop. So while
16752  * iter_next() calls are taken care of, we still need to be careful and
16753  * prevent erroneous and too eager declaration of "ininite loop", when
16754  * iterators are involved.
16755  *
16756  * Here's a situation in pseudo-BPF assembly form:
16757  *
16758  *   0: again:                          ; set up iter_next() call args
16759  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16760  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16761  *   3:   if r0 == 0 goto done
16762  *   4:   ... something useful here ...
16763  *   5:   goto again                    ; another iteration
16764  *   6: done:
16765  *   7:   r1 = &it
16766  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16767  *   9:   exit
16768  *
16769  * This is a typical loop. Let's assume that we have a prune point at 1:,
16770  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16771  * again`, assuming other heuristics don't get in a way).
16772  *
16773  * When we first time come to 1:, let's say we have some state X. We proceed
16774  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16775  * Now we come back to validate that forked ACTIVE state. We proceed through
16776  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16777  * are converging. But the problem is that we don't know that yet, as this
16778  * convergence has to happen at iter_next() call site only. So if nothing is
16779  * done, at 1: verifier will use bounded loop logic and declare infinite
16780  * looping (and would be *technically* correct, if not for iterator's
16781  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16782  * don't want that. So what we do in process_iter_next_call() when we go on
16783  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16784  * a different iteration. So when we suspect an infinite loop, we additionally
16785  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16786  * pretend we are not looping and wait for next iter_next() call.
16787  *
16788  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16789  * loop, because that would actually mean infinite loop, as DRAINED state is
16790  * "sticky", and so we'll keep returning into the same instruction with the
16791  * same state (at least in one of possible code paths).
16792  *
16793  * This approach allows to keep infinite loop heuristic even in the face of
16794  * active iterator. E.g., C snippet below is and will be detected as
16795  * inifintely looping:
16796  *
16797  *   struct bpf_iter_num it;
16798  *   int *p, x;
16799  *
16800  *   bpf_iter_num_new(&it, 0, 10);
16801  *   while ((p = bpf_iter_num_next(&t))) {
16802  *       x = p;
16803  *       while (x--) {} // <<-- infinite loop here
16804  *   }
16805  *
16806  */
16807 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16808 {
16809         struct bpf_reg_state *slot, *cur_slot;
16810         struct bpf_func_state *state;
16811         int i, fr;
16812
16813         for (fr = old->curframe; fr >= 0; fr--) {
16814                 state = old->frame[fr];
16815                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16816                         if (state->stack[i].slot_type[0] != STACK_ITER)
16817                                 continue;
16818
16819                         slot = &state->stack[i].spilled_ptr;
16820                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16821                                 continue;
16822
16823                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16824                         if (cur_slot->iter.depth != slot->iter.depth)
16825                                 return true;
16826                 }
16827         }
16828         return false;
16829 }
16830
16831 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16832 {
16833         struct bpf_verifier_state_list *new_sl;
16834         struct bpf_verifier_state_list *sl, **pprev;
16835         struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry;
16836         int i, j, n, err, states_cnt = 0;
16837         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16838         bool add_new_state = force_new_state;
16839         bool force_exact;
16840
16841         /* bpf progs typically have pruning point every 4 instructions
16842          * http://vger.kernel.org/bpfconf2019.html#session-1
16843          * Do not add new state for future pruning if the verifier hasn't seen
16844          * at least 2 jumps and at least 8 instructions.
16845          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16846          * In tests that amounts to up to 50% reduction into total verifier
16847          * memory consumption and 20% verifier time speedup.
16848          */
16849         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16850             env->insn_processed - env->prev_insn_processed >= 8)
16851                 add_new_state = true;
16852
16853         pprev = explored_state(env, insn_idx);
16854         sl = *pprev;
16855
16856         clean_live_states(env, insn_idx, cur);
16857
16858         while (sl) {
16859                 states_cnt++;
16860                 if (sl->state.insn_idx != insn_idx)
16861                         goto next;
16862
16863                 if (sl->state.branches) {
16864                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16865
16866                         if (frame->in_async_callback_fn &&
16867                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16868                                 /* Different async_entry_cnt means that the verifier is
16869                                  * processing another entry into async callback.
16870                                  * Seeing the same state is not an indication of infinite
16871                                  * loop or infinite recursion.
16872                                  * But finding the same state doesn't mean that it's safe
16873                                  * to stop processing the current state. The previous state
16874                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16875                                  * Checking in_async_callback_fn alone is not enough either.
16876                                  * Since the verifier still needs to catch infinite loops
16877                                  * inside async callbacks.
16878                                  */
16879                                 goto skip_inf_loop_check;
16880                         }
16881                         /* BPF open-coded iterators loop detection is special.
16882                          * states_maybe_looping() logic is too simplistic in detecting
16883                          * states that *might* be equivalent, because it doesn't know
16884                          * about ID remapping, so don't even perform it.
16885                          * See process_iter_next_call() and iter_active_depths_differ()
16886                          * for overview of the logic. When current and one of parent
16887                          * states are detected as equivalent, it's a good thing: we prove
16888                          * convergence and can stop simulating further iterations.
16889                          * It's safe to assume that iterator loop will finish, taking into
16890                          * account iter_next() contract of eventually returning
16891                          * sticky NULL result.
16892                          *
16893                          * Note, that states have to be compared exactly in this case because
16894                          * read and precision marks might not be finalized inside the loop.
16895                          * E.g. as in the program below:
16896                          *
16897                          *     1. r7 = -16
16898                          *     2. r6 = bpf_get_prandom_u32()
16899                          *     3. while (bpf_iter_num_next(&fp[-8])) {
16900                          *     4.   if (r6 != 42) {
16901                          *     5.     r7 = -32
16902                          *     6.     r6 = bpf_get_prandom_u32()
16903                          *     7.     continue
16904                          *     8.   }
16905                          *     9.   r0 = r10
16906                          *    10.   r0 += r7
16907                          *    11.   r8 = *(u64 *)(r0 + 0)
16908                          *    12.   r6 = bpf_get_prandom_u32()
16909                          *    13. }
16910                          *
16911                          * Here verifier would first visit path 1-3, create a checkpoint at 3
16912                          * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does
16913                          * not have read or precision mark for r7 yet, thus inexact states
16914                          * comparison would discard current state with r7=-32
16915                          * => unsafe memory access at 11 would not be caught.
16916                          */
16917                         if (is_iter_next_insn(env, insn_idx)) {
16918                                 if (states_equal(env, &sl->state, cur, true)) {
16919                                         struct bpf_func_state *cur_frame;
16920                                         struct bpf_reg_state *iter_state, *iter_reg;
16921                                         int spi;
16922
16923                                         cur_frame = cur->frame[cur->curframe];
16924                                         /* btf_check_iter_kfuncs() enforces that
16925                                          * iter state pointer is always the first arg
16926                                          */
16927                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16928                                         /* current state is valid due to states_equal(),
16929                                          * so we can assume valid iter and reg state,
16930                                          * no need for extra (re-)validations
16931                                          */
16932                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16933                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16934                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) {
16935                                                 update_loop_entry(cur, &sl->state);
16936                                                 goto hit;
16937                                         }
16938                                 }
16939                                 goto skip_inf_loop_check;
16940                         }
16941                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16942                         if (states_maybe_looping(&sl->state, cur) &&
16943                             states_equal(env, &sl->state, cur, false) &&
16944                             !iter_active_depths_differ(&sl->state, cur)) {
16945                                 verbose_linfo(env, insn_idx, "; ");
16946                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16947                                 verbose(env, "cur state:");
16948                                 print_verifier_state(env, cur->frame[cur->curframe], true);
16949                                 verbose(env, "old state:");
16950                                 print_verifier_state(env, sl->state.frame[cur->curframe], true);
16951                                 return -EINVAL;
16952                         }
16953                         /* if the verifier is processing a loop, avoid adding new state
16954                          * too often, since different loop iterations have distinct
16955                          * states and may not help future pruning.
16956                          * This threshold shouldn't be too low to make sure that
16957                          * a loop with large bound will be rejected quickly.
16958                          * The most abusive loop will be:
16959                          * r1 += 1
16960                          * if r1 < 1000000 goto pc-2
16961                          * 1M insn_procssed limit / 100 == 10k peak states.
16962                          * This threshold shouldn't be too high either, since states
16963                          * at the end of the loop are likely to be useful in pruning.
16964                          */
16965 skip_inf_loop_check:
16966                         if (!force_new_state &&
16967                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16968                             env->insn_processed - env->prev_insn_processed < 100)
16969                                 add_new_state = false;
16970                         goto miss;
16971                 }
16972                 /* If sl->state is a part of a loop and this loop's entry is a part of
16973                  * current verification path then states have to be compared exactly.
16974                  * 'force_exact' is needed to catch the following case:
16975                  *
16976                  *                initial     Here state 'succ' was processed first,
16977                  *                  |         it was eventually tracked to produce a
16978                  *                  V         state identical to 'hdr'.
16979                  *     .---------> hdr        All branches from 'succ' had been explored
16980                  *     |            |         and thus 'succ' has its .branches == 0.
16981                  *     |            V
16982                  *     |    .------...        Suppose states 'cur' and 'succ' correspond
16983                  *     |    |       |         to the same instruction + callsites.
16984                  *     |    V       V         In such case it is necessary to check
16985                  *     |   ...     ...        if 'succ' and 'cur' are states_equal().
16986                  *     |    |       |         If 'succ' and 'cur' are a part of the
16987                  *     |    V       V         same loop exact flag has to be set.
16988                  *     |   succ <- cur        To check if that is the case, verify
16989                  *     |    |                 if loop entry of 'succ' is in current
16990                  *     |    V                 DFS path.
16991                  *     |   ...
16992                  *     |    |
16993                  *     '----'
16994                  *
16995                  * Additional details are in the comment before get_loop_entry().
16996                  */
16997                 loop_entry = get_loop_entry(&sl->state);
16998                 force_exact = loop_entry && loop_entry->branches > 0;
16999                 if (states_equal(env, &sl->state, cur, force_exact)) {
17000                         if (force_exact)
17001                                 update_loop_entry(cur, loop_entry);
17002 hit:
17003                         sl->hit_cnt++;
17004                         /* reached equivalent register/stack state,
17005                          * prune the search.
17006                          * Registers read by the continuation are read by us.
17007                          * If we have any write marks in env->cur_state, they
17008                          * will prevent corresponding reads in the continuation
17009                          * from reaching our parent (an explored_state).  Our
17010                          * own state will get the read marks recorded, but
17011                          * they'll be immediately forgotten as we're pruning
17012                          * this state and will pop a new one.
17013                          */
17014                         err = propagate_liveness(env, &sl->state, cur);
17015
17016                         /* if previous state reached the exit with precision and
17017                          * current state is equivalent to it (except precsion marks)
17018                          * the precision needs to be propagated back in
17019                          * the current state.
17020                          */
17021                         err = err ? : push_jmp_history(env, cur);
17022                         err = err ? : propagate_precision(env, &sl->state);
17023                         if (err)
17024                                 return err;
17025                         return 1;
17026                 }
17027 miss:
17028                 /* when new state is not going to be added do not increase miss count.
17029                  * Otherwise several loop iterations will remove the state
17030                  * recorded earlier. The goal of these heuristics is to have
17031                  * states from some iterations of the loop (some in the beginning
17032                  * and some at the end) to help pruning.
17033                  */
17034                 if (add_new_state)
17035                         sl->miss_cnt++;
17036                 /* heuristic to determine whether this state is beneficial
17037                  * to keep checking from state equivalence point of view.
17038                  * Higher numbers increase max_states_per_insn and verification time,
17039                  * but do not meaningfully decrease insn_processed.
17040                  * 'n' controls how many times state could miss before eviction.
17041                  * Use bigger 'n' for checkpoints because evicting checkpoint states
17042                  * too early would hinder iterator convergence.
17043                  */
17044                 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3;
17045                 if (sl->miss_cnt > sl->hit_cnt * n + n) {
17046                         /* the state is unlikely to be useful. Remove it to
17047                          * speed up verification
17048                          */
17049                         *pprev = sl->next;
17050                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE &&
17051                             !sl->state.used_as_loop_entry) {
17052                                 u32 br = sl->state.branches;
17053
17054                                 WARN_ONCE(br,
17055                                           "BUG live_done but branches_to_explore %d\n",
17056                                           br);
17057                                 free_verifier_state(&sl->state, false);
17058                                 kfree(sl);
17059                                 env->peak_states--;
17060                         } else {
17061                                 /* cannot free this state, since parentage chain may
17062                                  * walk it later. Add it for free_list instead to
17063                                  * be freed at the end of verification
17064                                  */
17065                                 sl->next = env->free_list;
17066                                 env->free_list = sl;
17067                         }
17068                         sl = *pprev;
17069                         continue;
17070                 }
17071 next:
17072                 pprev = &sl->next;
17073                 sl = *pprev;
17074         }
17075
17076         if (env->max_states_per_insn < states_cnt)
17077                 env->max_states_per_insn = states_cnt;
17078
17079         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
17080                 return 0;
17081
17082         if (!add_new_state)
17083                 return 0;
17084
17085         /* There were no equivalent states, remember the current one.
17086          * Technically the current state is not proven to be safe yet,
17087          * but it will either reach outer most bpf_exit (which means it's safe)
17088          * or it will be rejected. When there are no loops the verifier won't be
17089          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
17090          * again on the way to bpf_exit.
17091          * When looping the sl->state.branches will be > 0 and this state
17092          * will not be considered for equivalence until branches == 0.
17093          */
17094         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
17095         if (!new_sl)
17096                 return -ENOMEM;
17097         env->total_states++;
17098         env->peak_states++;
17099         env->prev_jmps_processed = env->jmps_processed;
17100         env->prev_insn_processed = env->insn_processed;
17101
17102         /* forget precise markings we inherited, see __mark_chain_precision */
17103         if (env->bpf_capable)
17104                 mark_all_scalars_imprecise(env, cur);
17105
17106         /* add new state to the head of linked list */
17107         new = &new_sl->state;
17108         err = copy_verifier_state(new, cur);
17109         if (err) {
17110                 free_verifier_state(new, false);
17111                 kfree(new_sl);
17112                 return err;
17113         }
17114         new->insn_idx = insn_idx;
17115         WARN_ONCE(new->branches != 1,
17116                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
17117
17118         cur->parent = new;
17119         cur->first_insn_idx = insn_idx;
17120         cur->dfs_depth = new->dfs_depth + 1;
17121         clear_jmp_history(cur);
17122         new_sl->next = *explored_state(env, insn_idx);
17123         *explored_state(env, insn_idx) = new_sl;
17124         /* connect new state to parentage chain. Current frame needs all
17125          * registers connected. Only r6 - r9 of the callers are alive (pushed
17126          * to the stack implicitly by JITs) so in callers' frames connect just
17127          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
17128          * the state of the call instruction (with WRITTEN set), and r0 comes
17129          * from callee with its full parentage chain, anyway.
17130          */
17131         /* clear write marks in current state: the writes we did are not writes
17132          * our child did, so they don't screen off its reads from us.
17133          * (There are no read marks in current state, because reads always mark
17134          * their parent and current state never has children yet.  Only
17135          * explored_states can get read marks.)
17136          */
17137         for (j = 0; j <= cur->curframe; j++) {
17138                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
17139                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
17140                 for (i = 0; i < BPF_REG_FP; i++)
17141                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
17142         }
17143
17144         /* all stack frames are accessible from callee, clear them all */
17145         for (j = 0; j <= cur->curframe; j++) {
17146                 struct bpf_func_state *frame = cur->frame[j];
17147                 struct bpf_func_state *newframe = new->frame[j];
17148
17149                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
17150                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
17151                         frame->stack[i].spilled_ptr.parent =
17152                                                 &newframe->stack[i].spilled_ptr;
17153                 }
17154         }
17155         return 0;
17156 }
17157
17158 /* Return true if it's OK to have the same insn return a different type. */
17159 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
17160 {
17161         switch (base_type(type)) {
17162         case PTR_TO_CTX:
17163         case PTR_TO_SOCKET:
17164         case PTR_TO_SOCK_COMMON:
17165         case PTR_TO_TCP_SOCK:
17166         case PTR_TO_XDP_SOCK:
17167         case PTR_TO_BTF_ID:
17168                 return false;
17169         default:
17170                 return true;
17171         }
17172 }
17173
17174 /* If an instruction was previously used with particular pointer types, then we
17175  * need to be careful to avoid cases such as the below, where it may be ok
17176  * for one branch accessing the pointer, but not ok for the other branch:
17177  *
17178  * R1 = sock_ptr
17179  * goto X;
17180  * ...
17181  * R1 = some_other_valid_ptr;
17182  * goto X;
17183  * ...
17184  * R2 = *(u32 *)(R1 + 0);
17185  */
17186 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
17187 {
17188         return src != prev && (!reg_type_mismatch_ok(src) ||
17189                                !reg_type_mismatch_ok(prev));
17190 }
17191
17192 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
17193                              bool allow_trust_missmatch)
17194 {
17195         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
17196
17197         if (*prev_type == NOT_INIT) {
17198                 /* Saw a valid insn
17199                  * dst_reg = *(u32 *)(src_reg + off)
17200                  * save type to validate intersecting paths
17201                  */
17202                 *prev_type = type;
17203         } else if (reg_type_mismatch(type, *prev_type)) {
17204                 /* Abuser program is trying to use the same insn
17205                  * dst_reg = *(u32*) (src_reg + off)
17206                  * with different pointer types:
17207                  * src_reg == ctx in one branch and
17208                  * src_reg == stack|map in some other branch.
17209                  * Reject it.
17210                  */
17211                 if (allow_trust_missmatch &&
17212                     base_type(type) == PTR_TO_BTF_ID &&
17213                     base_type(*prev_type) == PTR_TO_BTF_ID) {
17214                         /*
17215                          * Have to support a use case when one path through
17216                          * the program yields TRUSTED pointer while another
17217                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
17218                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
17219                          */
17220                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
17221                 } else {
17222                         verbose(env, "same insn cannot be used with different pointers\n");
17223                         return -EINVAL;
17224                 }
17225         }
17226
17227         return 0;
17228 }
17229
17230 static int do_check(struct bpf_verifier_env *env)
17231 {
17232         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
17233         struct bpf_verifier_state *state = env->cur_state;
17234         struct bpf_insn *insns = env->prog->insnsi;
17235         struct bpf_reg_state *regs;
17236         int insn_cnt = env->prog->len;
17237         bool do_print_state = false;
17238         int prev_insn_idx = -1;
17239
17240         for (;;) {
17241                 bool exception_exit = false;
17242                 struct bpf_insn *insn;
17243                 u8 class;
17244                 int err;
17245
17246                 env->prev_insn_idx = prev_insn_idx;
17247                 if (env->insn_idx >= insn_cnt) {
17248                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
17249                                 env->insn_idx, insn_cnt);
17250                         return -EFAULT;
17251                 }
17252
17253                 insn = &insns[env->insn_idx];
17254                 class = BPF_CLASS(insn->code);
17255
17256                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
17257                         verbose(env,
17258                                 "BPF program is too large. Processed %d insn\n",
17259                                 env->insn_processed);
17260                         return -E2BIG;
17261                 }
17262
17263                 state->last_insn_idx = env->prev_insn_idx;
17264
17265                 if (is_prune_point(env, env->insn_idx)) {
17266                         err = is_state_visited(env, env->insn_idx);
17267                         if (err < 0)
17268                                 return err;
17269                         if (err == 1) {
17270                                 /* found equivalent state, can prune the search */
17271                                 if (env->log.level & BPF_LOG_LEVEL) {
17272                                         if (do_print_state)
17273                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
17274                                                         env->prev_insn_idx, env->insn_idx,
17275                                                         env->cur_state->speculative ?
17276                                                         " (speculative execution)" : "");
17277                                         else
17278                                                 verbose(env, "%d: safe\n", env->insn_idx);
17279                                 }
17280                                 goto process_bpf_exit;
17281                         }
17282                 }
17283
17284                 if (is_jmp_point(env, env->insn_idx)) {
17285                         err = push_jmp_history(env, state);
17286                         if (err)
17287                                 return err;
17288                 }
17289
17290                 if (signal_pending(current))
17291                         return -EAGAIN;
17292
17293                 if (need_resched())
17294                         cond_resched();
17295
17296                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
17297                         verbose(env, "\nfrom %d to %d%s:",
17298                                 env->prev_insn_idx, env->insn_idx,
17299                                 env->cur_state->speculative ?
17300                                 " (speculative execution)" : "");
17301                         print_verifier_state(env, state->frame[state->curframe], true);
17302                         do_print_state = false;
17303                 }
17304
17305                 if (env->log.level & BPF_LOG_LEVEL) {
17306                         const struct bpf_insn_cbs cbs = {
17307                                 .cb_call        = disasm_kfunc_name,
17308                                 .cb_print       = verbose,
17309                                 .private_data   = env,
17310                         };
17311
17312                         if (verifier_state_scratched(env))
17313                                 print_insn_state(env, state->frame[state->curframe]);
17314
17315                         verbose_linfo(env, env->insn_idx, "; ");
17316                         env->prev_log_pos = env->log.end_pos;
17317                         verbose(env, "%d: ", env->insn_idx);
17318                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
17319                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
17320                         env->prev_log_pos = env->log.end_pos;
17321                 }
17322
17323                 if (bpf_prog_is_offloaded(env->prog->aux)) {
17324                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
17325                                                            env->prev_insn_idx);
17326                         if (err)
17327                                 return err;
17328                 }
17329
17330                 regs = cur_regs(env);
17331                 sanitize_mark_insn_seen(env);
17332                 prev_insn_idx = env->insn_idx;
17333
17334                 if (class == BPF_ALU || class == BPF_ALU64) {
17335                         err = check_alu_op(env, insn);
17336                         if (err)
17337                                 return err;
17338
17339                 } else if (class == BPF_LDX) {
17340                         enum bpf_reg_type src_reg_type;
17341
17342                         /* check for reserved fields is already done */
17343
17344                         /* check src operand */
17345                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
17346                         if (err)
17347                                 return err;
17348
17349                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
17350                         if (err)
17351                                 return err;
17352
17353                         src_reg_type = regs[insn->src_reg].type;
17354
17355                         /* check that memory (src_reg + off) is readable,
17356                          * the state of dst_reg will be updated by this func
17357                          */
17358                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
17359                                                insn->off, BPF_SIZE(insn->code),
17360                                                BPF_READ, insn->dst_reg, false,
17361                                                BPF_MODE(insn->code) == BPF_MEMSX);
17362                         if (err)
17363                                 return err;
17364
17365                         err = save_aux_ptr_type(env, src_reg_type, true);
17366                         if (err)
17367                                 return err;
17368                 } else if (class == BPF_STX) {
17369                         enum bpf_reg_type dst_reg_type;
17370
17371                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
17372                                 err = check_atomic(env, env->insn_idx, insn);
17373                                 if (err)
17374                                         return err;
17375                                 env->insn_idx++;
17376                                 continue;
17377                         }
17378
17379                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
17380                                 verbose(env, "BPF_STX uses reserved fields\n");
17381                                 return -EINVAL;
17382                         }
17383
17384                         /* check src1 operand */
17385                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
17386                         if (err)
17387                                 return err;
17388                         /* check src2 operand */
17389                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17390                         if (err)
17391                                 return err;
17392
17393                         dst_reg_type = regs[insn->dst_reg].type;
17394
17395                         /* check that memory (dst_reg + off) is writeable */
17396                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17397                                                insn->off, BPF_SIZE(insn->code),
17398                                                BPF_WRITE, insn->src_reg, false, false);
17399                         if (err)
17400                                 return err;
17401
17402                         err = save_aux_ptr_type(env, dst_reg_type, false);
17403                         if (err)
17404                                 return err;
17405                 } else if (class == BPF_ST) {
17406                         enum bpf_reg_type dst_reg_type;
17407
17408                         if (BPF_MODE(insn->code) != BPF_MEM ||
17409                             insn->src_reg != BPF_REG_0) {
17410                                 verbose(env, "BPF_ST uses reserved fields\n");
17411                                 return -EINVAL;
17412                         }
17413                         /* check src operand */
17414                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
17415                         if (err)
17416                                 return err;
17417
17418                         dst_reg_type = regs[insn->dst_reg].type;
17419
17420                         /* check that memory (dst_reg + off) is writeable */
17421                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
17422                                                insn->off, BPF_SIZE(insn->code),
17423                                                BPF_WRITE, -1, false, false);
17424                         if (err)
17425                                 return err;
17426
17427                         err = save_aux_ptr_type(env, dst_reg_type, false);
17428                         if (err)
17429                                 return err;
17430                 } else if (class == BPF_JMP || class == BPF_JMP32) {
17431                         u8 opcode = BPF_OP(insn->code);
17432
17433                         env->jmps_processed++;
17434                         if (opcode == BPF_CALL) {
17435                                 if (BPF_SRC(insn->code) != BPF_K ||
17436                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
17437                                      && insn->off != 0) ||
17438                                     (insn->src_reg != BPF_REG_0 &&
17439                                      insn->src_reg != BPF_PSEUDO_CALL &&
17440                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
17441                                     insn->dst_reg != BPF_REG_0 ||
17442                                     class == BPF_JMP32) {
17443                                         verbose(env, "BPF_CALL uses reserved fields\n");
17444                                         return -EINVAL;
17445                                 }
17446
17447                                 if (env->cur_state->active_lock.ptr) {
17448                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
17449                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
17450                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
17451                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
17452                                                 verbose(env, "function calls are not allowed while holding a lock\n");
17453                                                 return -EINVAL;
17454                                         }
17455                                 }
17456                                 if (insn->src_reg == BPF_PSEUDO_CALL) {
17457                                         err = check_func_call(env, insn, &env->insn_idx);
17458                                 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
17459                                         err = check_kfunc_call(env, insn, &env->insn_idx);
17460                                         if (!err && is_bpf_throw_kfunc(insn)) {
17461                                                 exception_exit = true;
17462                                                 goto process_bpf_exit_full;
17463                                         }
17464                                 } else {
17465                                         err = check_helper_call(env, insn, &env->insn_idx);
17466                                 }
17467                                 if (err)
17468                                         return err;
17469
17470                                 mark_reg_scratched(env, BPF_REG_0);
17471                         } else if (opcode == BPF_JA) {
17472                                 if (BPF_SRC(insn->code) != BPF_K ||
17473                                     insn->src_reg != BPF_REG_0 ||
17474                                     insn->dst_reg != BPF_REG_0 ||
17475                                     (class == BPF_JMP && insn->imm != 0) ||
17476                                     (class == BPF_JMP32 && insn->off != 0)) {
17477                                         verbose(env, "BPF_JA uses reserved fields\n");
17478                                         return -EINVAL;
17479                                 }
17480
17481                                 if (class == BPF_JMP)
17482                                         env->insn_idx += insn->off + 1;
17483                                 else
17484                                         env->insn_idx += insn->imm + 1;
17485                                 continue;
17486
17487                         } else if (opcode == BPF_EXIT) {
17488                                 if (BPF_SRC(insn->code) != BPF_K ||
17489                                     insn->imm != 0 ||
17490                                     insn->src_reg != BPF_REG_0 ||
17491                                     insn->dst_reg != BPF_REG_0 ||
17492                                     class == BPF_JMP32) {
17493                                         verbose(env, "BPF_EXIT uses reserved fields\n");
17494                                         return -EINVAL;
17495                                 }
17496 process_bpf_exit_full:
17497                                 if (env->cur_state->active_lock.ptr &&
17498                                     !in_rbtree_lock_required_cb(env)) {
17499                                         verbose(env, "bpf_spin_unlock is missing\n");
17500                                         return -EINVAL;
17501                                 }
17502
17503                                 if (env->cur_state->active_rcu_lock &&
17504                                     !in_rbtree_lock_required_cb(env)) {
17505                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
17506                                         return -EINVAL;
17507                                 }
17508
17509                                 /* We must do check_reference_leak here before
17510                                  * prepare_func_exit to handle the case when
17511                                  * state->curframe > 0, it may be a callback
17512                                  * function, for which reference_state must
17513                                  * match caller reference state when it exits.
17514                                  */
17515                                 err = check_reference_leak(env, exception_exit);
17516                                 if (err)
17517                                         return err;
17518
17519                                 /* The side effect of the prepare_func_exit
17520                                  * which is being skipped is that it frees
17521                                  * bpf_func_state. Typically, process_bpf_exit
17522                                  * will only be hit with outermost exit.
17523                                  * copy_verifier_state in pop_stack will handle
17524                                  * freeing of any extra bpf_func_state left over
17525                                  * from not processing all nested function
17526                                  * exits. We also skip return code checks as
17527                                  * they are not needed for exceptional exits.
17528                                  */
17529                                 if (exception_exit)
17530                                         goto process_bpf_exit;
17531
17532                                 if (state->curframe) {
17533                                         /* exit from nested function */
17534                                         err = prepare_func_exit(env, &env->insn_idx);
17535                                         if (err)
17536                                                 return err;
17537                                         do_print_state = true;
17538                                         continue;
17539                                 }
17540
17541                                 err = check_return_code(env, BPF_REG_0);
17542                                 if (err)
17543                                         return err;
17544 process_bpf_exit:
17545                                 mark_verifier_state_scratched(env);
17546                                 update_branch_counts(env, env->cur_state);
17547                                 err = pop_stack(env, &prev_insn_idx,
17548                                                 &env->insn_idx, pop_log);
17549                                 if (err < 0) {
17550                                         if (err != -ENOENT)
17551                                                 return err;
17552                                         break;
17553                                 } else {
17554                                         do_print_state = true;
17555                                         continue;
17556                                 }
17557                         } else {
17558                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
17559                                 if (err)
17560                                         return err;
17561                         }
17562                 } else if (class == BPF_LD) {
17563                         u8 mode = BPF_MODE(insn->code);
17564
17565                         if (mode == BPF_ABS || mode == BPF_IND) {
17566                                 err = check_ld_abs(env, insn);
17567                                 if (err)
17568                                         return err;
17569
17570                         } else if (mode == BPF_IMM) {
17571                                 err = check_ld_imm(env, insn);
17572                                 if (err)
17573                                         return err;
17574
17575                                 env->insn_idx++;
17576                                 sanitize_mark_insn_seen(env);
17577                         } else {
17578                                 verbose(env, "invalid BPF_LD mode\n");
17579                                 return -EINVAL;
17580                         }
17581                 } else {
17582                         verbose(env, "unknown insn class %d\n", class);
17583                         return -EINVAL;
17584                 }
17585
17586                 env->insn_idx++;
17587         }
17588
17589         return 0;
17590 }
17591
17592 static int find_btf_percpu_datasec(struct btf *btf)
17593 {
17594         const struct btf_type *t;
17595         const char *tname;
17596         int i, n;
17597
17598         /*
17599          * Both vmlinux and module each have their own ".data..percpu"
17600          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
17601          * types to look at only module's own BTF types.
17602          */
17603         n = btf_nr_types(btf);
17604         if (btf_is_module(btf))
17605                 i = btf_nr_types(btf_vmlinux);
17606         else
17607                 i = 1;
17608
17609         for(; i < n; i++) {
17610                 t = btf_type_by_id(btf, i);
17611                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
17612                         continue;
17613
17614                 tname = btf_name_by_offset(btf, t->name_off);
17615                 if (!strcmp(tname, ".data..percpu"))
17616                         return i;
17617         }
17618
17619         return -ENOENT;
17620 }
17621
17622 /* replace pseudo btf_id with kernel symbol address */
17623 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
17624                                struct bpf_insn *insn,
17625                                struct bpf_insn_aux_data *aux)
17626 {
17627         const struct btf_var_secinfo *vsi;
17628         const struct btf_type *datasec;
17629         struct btf_mod_pair *btf_mod;
17630         const struct btf_type *t;
17631         const char *sym_name;
17632         bool percpu = false;
17633         u32 type, id = insn->imm;
17634         struct btf *btf;
17635         s32 datasec_id;
17636         u64 addr;
17637         int i, btf_fd, err;
17638
17639         btf_fd = insn[1].imm;
17640         if (btf_fd) {
17641                 btf = btf_get_by_fd(btf_fd);
17642                 if (IS_ERR(btf)) {
17643                         verbose(env, "invalid module BTF object FD specified.\n");
17644                         return -EINVAL;
17645                 }
17646         } else {
17647                 if (!btf_vmlinux) {
17648                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
17649                         return -EINVAL;
17650                 }
17651                 btf = btf_vmlinux;
17652                 btf_get(btf);
17653         }
17654
17655         t = btf_type_by_id(btf, id);
17656         if (!t) {
17657                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
17658                 err = -ENOENT;
17659                 goto err_put;
17660         }
17661
17662         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
17663                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
17664                 err = -EINVAL;
17665                 goto err_put;
17666         }
17667
17668         sym_name = btf_name_by_offset(btf, t->name_off);
17669         addr = kallsyms_lookup_name(sym_name);
17670         if (!addr) {
17671                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
17672                         sym_name);
17673                 err = -ENOENT;
17674                 goto err_put;
17675         }
17676         insn[0].imm = (u32)addr;
17677         insn[1].imm = addr >> 32;
17678
17679         if (btf_type_is_func(t)) {
17680                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17681                 aux->btf_var.mem_size = 0;
17682                 goto check_btf;
17683         }
17684
17685         datasec_id = find_btf_percpu_datasec(btf);
17686         if (datasec_id > 0) {
17687                 datasec = btf_type_by_id(btf, datasec_id);
17688                 for_each_vsi(i, datasec, vsi) {
17689                         if (vsi->type == id) {
17690                                 percpu = true;
17691                                 break;
17692                         }
17693                 }
17694         }
17695
17696         type = t->type;
17697         t = btf_type_skip_modifiers(btf, type, NULL);
17698         if (percpu) {
17699                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
17700                 aux->btf_var.btf = btf;
17701                 aux->btf_var.btf_id = type;
17702         } else if (!btf_type_is_struct(t)) {
17703                 const struct btf_type *ret;
17704                 const char *tname;
17705                 u32 tsize;
17706
17707                 /* resolve the type size of ksym. */
17708                 ret = btf_resolve_size(btf, t, &tsize);
17709                 if (IS_ERR(ret)) {
17710                         tname = btf_name_by_offset(btf, t->name_off);
17711                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
17712                                 tname, PTR_ERR(ret));
17713                         err = -EINVAL;
17714                         goto err_put;
17715                 }
17716                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
17717                 aux->btf_var.mem_size = tsize;
17718         } else {
17719                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
17720                 aux->btf_var.btf = btf;
17721                 aux->btf_var.btf_id = type;
17722         }
17723 check_btf:
17724         /* check whether we recorded this BTF (and maybe module) already */
17725         for (i = 0; i < env->used_btf_cnt; i++) {
17726                 if (env->used_btfs[i].btf == btf) {
17727                         btf_put(btf);
17728                         return 0;
17729                 }
17730         }
17731
17732         if (env->used_btf_cnt >= MAX_USED_BTFS) {
17733                 err = -E2BIG;
17734                 goto err_put;
17735         }
17736
17737         btf_mod = &env->used_btfs[env->used_btf_cnt];
17738         btf_mod->btf = btf;
17739         btf_mod->module = NULL;
17740
17741         /* if we reference variables from kernel module, bump its refcount */
17742         if (btf_is_module(btf)) {
17743                 btf_mod->module = btf_try_get_module(btf);
17744                 if (!btf_mod->module) {
17745                         err = -ENXIO;
17746                         goto err_put;
17747                 }
17748         }
17749
17750         env->used_btf_cnt++;
17751
17752         return 0;
17753 err_put:
17754         btf_put(btf);
17755         return err;
17756 }
17757
17758 static bool is_tracing_prog_type(enum bpf_prog_type type)
17759 {
17760         switch (type) {
17761         case BPF_PROG_TYPE_KPROBE:
17762         case BPF_PROG_TYPE_TRACEPOINT:
17763         case BPF_PROG_TYPE_PERF_EVENT:
17764         case BPF_PROG_TYPE_RAW_TRACEPOINT:
17765         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
17766                 return true;
17767         default:
17768                 return false;
17769         }
17770 }
17771
17772 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
17773                                         struct bpf_map *map,
17774                                         struct bpf_prog *prog)
17775
17776 {
17777         enum bpf_prog_type prog_type = resolve_prog_type(prog);
17778
17779         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17780             btf_record_has_field(map->record, BPF_RB_ROOT)) {
17781                 if (is_tracing_prog_type(prog_type)) {
17782                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17783                         return -EINVAL;
17784                 }
17785         }
17786
17787         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17788                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17789                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17790                         return -EINVAL;
17791                 }
17792
17793                 if (is_tracing_prog_type(prog_type)) {
17794                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17795                         return -EINVAL;
17796                 }
17797         }
17798
17799         if (btf_record_has_field(map->record, BPF_TIMER)) {
17800                 if (is_tracing_prog_type(prog_type)) {
17801                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
17802                         return -EINVAL;
17803                 }
17804         }
17805
17806         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17807             !bpf_offload_prog_map_match(prog, map)) {
17808                 verbose(env, "offload device mismatch between prog and map\n");
17809                 return -EINVAL;
17810         }
17811
17812         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17813                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17814                 return -EINVAL;
17815         }
17816
17817         if (prog->aux->sleepable)
17818                 switch (map->map_type) {
17819                 case BPF_MAP_TYPE_HASH:
17820                 case BPF_MAP_TYPE_LRU_HASH:
17821                 case BPF_MAP_TYPE_ARRAY:
17822                 case BPF_MAP_TYPE_PERCPU_HASH:
17823                 case BPF_MAP_TYPE_PERCPU_ARRAY:
17824                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17825                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17826                 case BPF_MAP_TYPE_HASH_OF_MAPS:
17827                 case BPF_MAP_TYPE_RINGBUF:
17828                 case BPF_MAP_TYPE_USER_RINGBUF:
17829                 case BPF_MAP_TYPE_INODE_STORAGE:
17830                 case BPF_MAP_TYPE_SK_STORAGE:
17831                 case BPF_MAP_TYPE_TASK_STORAGE:
17832                 case BPF_MAP_TYPE_CGRP_STORAGE:
17833                         break;
17834                 default:
17835                         verbose(env,
17836                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17837                         return -EINVAL;
17838                 }
17839
17840         return 0;
17841 }
17842
17843 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17844 {
17845         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17846                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17847 }
17848
17849 /* find and rewrite pseudo imm in ld_imm64 instructions:
17850  *
17851  * 1. if it accesses map FD, replace it with actual map pointer.
17852  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17853  *
17854  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17855  */
17856 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17857 {
17858         struct bpf_insn *insn = env->prog->insnsi;
17859         int insn_cnt = env->prog->len;
17860         int i, j, err;
17861
17862         err = bpf_prog_calc_tag(env->prog);
17863         if (err)
17864                 return err;
17865
17866         for (i = 0; i < insn_cnt; i++, insn++) {
17867                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17868                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17869                     insn->imm != 0)) {
17870                         verbose(env, "BPF_LDX uses reserved fields\n");
17871                         return -EINVAL;
17872                 }
17873
17874                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17875                         struct bpf_insn_aux_data *aux;
17876                         struct bpf_map *map;
17877                         struct fd f;
17878                         u64 addr;
17879                         u32 fd;
17880
17881                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17882                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17883                             insn[1].off != 0) {
17884                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17885                                 return -EINVAL;
17886                         }
17887
17888                         if (insn[0].src_reg == 0)
17889                                 /* valid generic load 64-bit imm */
17890                                 goto next_insn;
17891
17892                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17893                                 aux = &env->insn_aux_data[i];
17894                                 err = check_pseudo_btf_id(env, insn, aux);
17895                                 if (err)
17896                                         return err;
17897                                 goto next_insn;
17898                         }
17899
17900                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17901                                 aux = &env->insn_aux_data[i];
17902                                 aux->ptr_type = PTR_TO_FUNC;
17903                                 goto next_insn;
17904                         }
17905
17906                         /* In final convert_pseudo_ld_imm64() step, this is
17907                          * converted into regular 64-bit imm load insn.
17908                          */
17909                         switch (insn[0].src_reg) {
17910                         case BPF_PSEUDO_MAP_VALUE:
17911                         case BPF_PSEUDO_MAP_IDX_VALUE:
17912                                 break;
17913                         case BPF_PSEUDO_MAP_FD:
17914                         case BPF_PSEUDO_MAP_IDX:
17915                                 if (insn[1].imm == 0)
17916                                         break;
17917                                 fallthrough;
17918                         default:
17919                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17920                                 return -EINVAL;
17921                         }
17922
17923                         switch (insn[0].src_reg) {
17924                         case BPF_PSEUDO_MAP_IDX_VALUE:
17925                         case BPF_PSEUDO_MAP_IDX:
17926                                 if (bpfptr_is_null(env->fd_array)) {
17927                                         verbose(env, "fd_idx without fd_array is invalid\n");
17928                                         return -EPROTO;
17929                                 }
17930                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17931                                                             insn[0].imm * sizeof(fd),
17932                                                             sizeof(fd)))
17933                                         return -EFAULT;
17934                                 break;
17935                         default:
17936                                 fd = insn[0].imm;
17937                                 break;
17938                         }
17939
17940                         f = fdget(fd);
17941                         map = __bpf_map_get(f);
17942                         if (IS_ERR(map)) {
17943                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17944                                         insn[0].imm);
17945                                 return PTR_ERR(map);
17946                         }
17947
17948                         err = check_map_prog_compatibility(env, map, env->prog);
17949                         if (err) {
17950                                 fdput(f);
17951                                 return err;
17952                         }
17953
17954                         aux = &env->insn_aux_data[i];
17955                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17956                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17957                                 addr = (unsigned long)map;
17958                         } else {
17959                                 u32 off = insn[1].imm;
17960
17961                                 if (off >= BPF_MAX_VAR_OFF) {
17962                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17963                                         fdput(f);
17964                                         return -EINVAL;
17965                                 }
17966
17967                                 if (!map->ops->map_direct_value_addr) {
17968                                         verbose(env, "no direct value access support for this map type\n");
17969                                         fdput(f);
17970                                         return -EINVAL;
17971                                 }
17972
17973                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17974                                 if (err) {
17975                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17976                                                 map->value_size, off);
17977                                         fdput(f);
17978                                         return err;
17979                                 }
17980
17981                                 aux->map_off = off;
17982                                 addr += off;
17983                         }
17984
17985                         insn[0].imm = (u32)addr;
17986                         insn[1].imm = addr >> 32;
17987
17988                         /* check whether we recorded this map already */
17989                         for (j = 0; j < env->used_map_cnt; j++) {
17990                                 if (env->used_maps[j] == map) {
17991                                         aux->map_index = j;
17992                                         fdput(f);
17993                                         goto next_insn;
17994                                 }
17995                         }
17996
17997                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17998                                 fdput(f);
17999                                 return -E2BIG;
18000                         }
18001
18002                         /* hold the map. If the program is rejected by verifier,
18003                          * the map will be released by release_maps() or it
18004                          * will be used by the valid program until it's unloaded
18005                          * and all maps are released in free_used_maps()
18006                          */
18007                         bpf_map_inc(map);
18008
18009                         aux->map_index = env->used_map_cnt;
18010                         env->used_maps[env->used_map_cnt++] = map;
18011
18012                         if (bpf_map_is_cgroup_storage(map) &&
18013                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
18014                                 verbose(env, "only one cgroup storage of each type is allowed\n");
18015                                 fdput(f);
18016                                 return -EBUSY;
18017                         }
18018
18019                         fdput(f);
18020 next_insn:
18021                         insn++;
18022                         i++;
18023                         continue;
18024                 }
18025
18026                 /* Basic sanity check before we invest more work here. */
18027                 if (!bpf_opcode_in_insntable(insn->code)) {
18028                         verbose(env, "unknown opcode %02x\n", insn->code);
18029                         return -EINVAL;
18030                 }
18031         }
18032
18033         /* now all pseudo BPF_LD_IMM64 instructions load valid
18034          * 'struct bpf_map *' into a register instead of user map_fd.
18035          * These pointers will be used later by verifier to validate map access.
18036          */
18037         return 0;
18038 }
18039
18040 /* drop refcnt of maps used by the rejected program */
18041 static void release_maps(struct bpf_verifier_env *env)
18042 {
18043         __bpf_free_used_maps(env->prog->aux, env->used_maps,
18044                              env->used_map_cnt);
18045 }
18046
18047 /* drop refcnt of maps used by the rejected program */
18048 static void release_btfs(struct bpf_verifier_env *env)
18049 {
18050         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
18051                              env->used_btf_cnt);
18052 }
18053
18054 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
18055 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
18056 {
18057         struct bpf_insn *insn = env->prog->insnsi;
18058         int insn_cnt = env->prog->len;
18059         int i;
18060
18061         for (i = 0; i < insn_cnt; i++, insn++) {
18062                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
18063                         continue;
18064                 if (insn->src_reg == BPF_PSEUDO_FUNC)
18065                         continue;
18066                 insn->src_reg = 0;
18067         }
18068 }
18069
18070 /* single env->prog->insni[off] instruction was replaced with the range
18071  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
18072  * [0, off) and [off, end) to new locations, so the patched range stays zero
18073  */
18074 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
18075                                  struct bpf_insn_aux_data *new_data,
18076                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
18077 {
18078         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
18079         struct bpf_insn *insn = new_prog->insnsi;
18080         u32 old_seen = old_data[off].seen;
18081         u32 prog_len;
18082         int i;
18083
18084         /* aux info at OFF always needs adjustment, no matter fast path
18085          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
18086          * original insn at old prog.
18087          */
18088         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
18089
18090         if (cnt == 1)
18091                 return;
18092         prog_len = new_prog->len;
18093
18094         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
18095         memcpy(new_data + off + cnt - 1, old_data + off,
18096                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
18097         for (i = off; i < off + cnt - 1; i++) {
18098                 /* Expand insni[off]'s seen count to the patched range. */
18099                 new_data[i].seen = old_seen;
18100                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
18101         }
18102         env->insn_aux_data = new_data;
18103         vfree(old_data);
18104 }
18105
18106 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
18107 {
18108         int i;
18109
18110         if (len == 1)
18111                 return;
18112         /* NOTE: fake 'exit' subprog should be updated as well. */
18113         for (i = 0; i <= env->subprog_cnt; i++) {
18114                 if (env->subprog_info[i].start <= off)
18115                         continue;
18116                 env->subprog_info[i].start += len - 1;
18117         }
18118 }
18119
18120 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
18121 {
18122         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
18123         int i, sz = prog->aux->size_poke_tab;
18124         struct bpf_jit_poke_descriptor *desc;
18125
18126         for (i = 0; i < sz; i++) {
18127                 desc = &tab[i];
18128                 if (desc->insn_idx <= off)
18129                         continue;
18130                 desc->insn_idx += len - 1;
18131         }
18132 }
18133
18134 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
18135                                             const struct bpf_insn *patch, u32 len)
18136 {
18137         struct bpf_prog *new_prog;
18138         struct bpf_insn_aux_data *new_data = NULL;
18139
18140         if (len > 1) {
18141                 new_data = vzalloc(array_size(env->prog->len + len - 1,
18142                                               sizeof(struct bpf_insn_aux_data)));
18143                 if (!new_data)
18144                         return NULL;
18145         }
18146
18147         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
18148         if (IS_ERR(new_prog)) {
18149                 if (PTR_ERR(new_prog) == -ERANGE)
18150                         verbose(env,
18151                                 "insn %d cannot be patched due to 16-bit range\n",
18152                                 env->insn_aux_data[off].orig_idx);
18153                 vfree(new_data);
18154                 return NULL;
18155         }
18156         adjust_insn_aux_data(env, new_data, new_prog, off, len);
18157         adjust_subprog_starts(env, off, len);
18158         adjust_poke_descs(new_prog, off, len);
18159         return new_prog;
18160 }
18161
18162 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
18163                                               u32 off, u32 cnt)
18164 {
18165         int i, j;
18166
18167         /* find first prog starting at or after off (first to remove) */
18168         for (i = 0; i < env->subprog_cnt; i++)
18169                 if (env->subprog_info[i].start >= off)
18170                         break;
18171         /* find first prog starting at or after off + cnt (first to stay) */
18172         for (j = i; j < env->subprog_cnt; j++)
18173                 if (env->subprog_info[j].start >= off + cnt)
18174                         break;
18175         /* if j doesn't start exactly at off + cnt, we are just removing
18176          * the front of previous prog
18177          */
18178         if (env->subprog_info[j].start != off + cnt)
18179                 j--;
18180
18181         if (j > i) {
18182                 struct bpf_prog_aux *aux = env->prog->aux;
18183                 int move;
18184
18185                 /* move fake 'exit' subprog as well */
18186                 move = env->subprog_cnt + 1 - j;
18187
18188                 memmove(env->subprog_info + i,
18189                         env->subprog_info + j,
18190                         sizeof(*env->subprog_info) * move);
18191                 env->subprog_cnt -= j - i;
18192
18193                 /* remove func_info */
18194                 if (aux->func_info) {
18195                         move = aux->func_info_cnt - j;
18196
18197                         memmove(aux->func_info + i,
18198                                 aux->func_info + j,
18199                                 sizeof(*aux->func_info) * move);
18200                         aux->func_info_cnt -= j - i;
18201                         /* func_info->insn_off is set after all code rewrites,
18202                          * in adjust_btf_func() - no need to adjust
18203                          */
18204                 }
18205         } else {
18206                 /* convert i from "first prog to remove" to "first to adjust" */
18207                 if (env->subprog_info[i].start == off)
18208                         i++;
18209         }
18210
18211         /* update fake 'exit' subprog as well */
18212         for (; i <= env->subprog_cnt; i++)
18213                 env->subprog_info[i].start -= cnt;
18214
18215         return 0;
18216 }
18217
18218 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
18219                                       u32 cnt)
18220 {
18221         struct bpf_prog *prog = env->prog;
18222         u32 i, l_off, l_cnt, nr_linfo;
18223         struct bpf_line_info *linfo;
18224
18225         nr_linfo = prog->aux->nr_linfo;
18226         if (!nr_linfo)
18227                 return 0;
18228
18229         linfo = prog->aux->linfo;
18230
18231         /* find first line info to remove, count lines to be removed */
18232         for (i = 0; i < nr_linfo; i++)
18233                 if (linfo[i].insn_off >= off)
18234                         break;
18235
18236         l_off = i;
18237         l_cnt = 0;
18238         for (; i < nr_linfo; i++)
18239                 if (linfo[i].insn_off < off + cnt)
18240                         l_cnt++;
18241                 else
18242                         break;
18243
18244         /* First live insn doesn't match first live linfo, it needs to "inherit"
18245          * last removed linfo.  prog is already modified, so prog->len == off
18246          * means no live instructions after (tail of the program was removed).
18247          */
18248         if (prog->len != off && l_cnt &&
18249             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
18250                 l_cnt--;
18251                 linfo[--i].insn_off = off + cnt;
18252         }
18253
18254         /* remove the line info which refer to the removed instructions */
18255         if (l_cnt) {
18256                 memmove(linfo + l_off, linfo + i,
18257                         sizeof(*linfo) * (nr_linfo - i));
18258
18259                 prog->aux->nr_linfo -= l_cnt;
18260                 nr_linfo = prog->aux->nr_linfo;
18261         }
18262
18263         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
18264         for (i = l_off; i < nr_linfo; i++)
18265                 linfo[i].insn_off -= cnt;
18266
18267         /* fix up all subprogs (incl. 'exit') which start >= off */
18268         for (i = 0; i <= env->subprog_cnt; i++)
18269                 if (env->subprog_info[i].linfo_idx > l_off) {
18270                         /* program may have started in the removed region but
18271                          * may not be fully removed
18272                          */
18273                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
18274                                 env->subprog_info[i].linfo_idx -= l_cnt;
18275                         else
18276                                 env->subprog_info[i].linfo_idx = l_off;
18277                 }
18278
18279         return 0;
18280 }
18281
18282 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
18283 {
18284         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18285         unsigned int orig_prog_len = env->prog->len;
18286         int err;
18287
18288         if (bpf_prog_is_offloaded(env->prog->aux))
18289                 bpf_prog_offload_remove_insns(env, off, cnt);
18290
18291         err = bpf_remove_insns(env->prog, off, cnt);
18292         if (err)
18293                 return err;
18294
18295         err = adjust_subprog_starts_after_remove(env, off, cnt);
18296         if (err)
18297                 return err;
18298
18299         err = bpf_adj_linfo_after_remove(env, off, cnt);
18300         if (err)
18301                 return err;
18302
18303         memmove(aux_data + off, aux_data + off + cnt,
18304                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
18305
18306         return 0;
18307 }
18308
18309 /* The verifier does more data flow analysis than llvm and will not
18310  * explore branches that are dead at run time. Malicious programs can
18311  * have dead code too. Therefore replace all dead at-run-time code
18312  * with 'ja -1'.
18313  *
18314  * Just nops are not optimal, e.g. if they would sit at the end of the
18315  * program and through another bug we would manage to jump there, then
18316  * we'd execute beyond program memory otherwise. Returning exception
18317  * code also wouldn't work since we can have subprogs where the dead
18318  * code could be located.
18319  */
18320 static void sanitize_dead_code(struct bpf_verifier_env *env)
18321 {
18322         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18323         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
18324         struct bpf_insn *insn = env->prog->insnsi;
18325         const int insn_cnt = env->prog->len;
18326         int i;
18327
18328         for (i = 0; i < insn_cnt; i++) {
18329                 if (aux_data[i].seen)
18330                         continue;
18331                 memcpy(insn + i, &trap, sizeof(trap));
18332                 aux_data[i].zext_dst = false;
18333         }
18334 }
18335
18336 static bool insn_is_cond_jump(u8 code)
18337 {
18338         u8 op;
18339
18340         op = BPF_OP(code);
18341         if (BPF_CLASS(code) == BPF_JMP32)
18342                 return op != BPF_JA;
18343
18344         if (BPF_CLASS(code) != BPF_JMP)
18345                 return false;
18346
18347         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
18348 }
18349
18350 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
18351 {
18352         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18353         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18354         struct bpf_insn *insn = env->prog->insnsi;
18355         const int insn_cnt = env->prog->len;
18356         int i;
18357
18358         for (i = 0; i < insn_cnt; i++, insn++) {
18359                 if (!insn_is_cond_jump(insn->code))
18360                         continue;
18361
18362                 if (!aux_data[i + 1].seen)
18363                         ja.off = insn->off;
18364                 else if (!aux_data[i + 1 + insn->off].seen)
18365                         ja.off = 0;
18366                 else
18367                         continue;
18368
18369                 if (bpf_prog_is_offloaded(env->prog->aux))
18370                         bpf_prog_offload_replace_insn(env, i, &ja);
18371
18372                 memcpy(insn, &ja, sizeof(ja));
18373         }
18374 }
18375
18376 static int opt_remove_dead_code(struct bpf_verifier_env *env)
18377 {
18378         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
18379         int insn_cnt = env->prog->len;
18380         int i, err;
18381
18382         for (i = 0; i < insn_cnt; i++) {
18383                 int j;
18384
18385                 j = 0;
18386                 while (i + j < insn_cnt && !aux_data[i + j].seen)
18387                         j++;
18388                 if (!j)
18389                         continue;
18390
18391                 err = verifier_remove_insns(env, i, j);
18392                 if (err)
18393                         return err;
18394                 insn_cnt = env->prog->len;
18395         }
18396
18397         return 0;
18398 }
18399
18400 static int opt_remove_nops(struct bpf_verifier_env *env)
18401 {
18402         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
18403         struct bpf_insn *insn = env->prog->insnsi;
18404         int insn_cnt = env->prog->len;
18405         int i, err;
18406
18407         for (i = 0; i < insn_cnt; i++) {
18408                 if (memcmp(&insn[i], &ja, sizeof(ja)))
18409                         continue;
18410
18411                 err = verifier_remove_insns(env, i, 1);
18412                 if (err)
18413                         return err;
18414                 insn_cnt--;
18415                 i--;
18416         }
18417
18418         return 0;
18419 }
18420
18421 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
18422                                          const union bpf_attr *attr)
18423 {
18424         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
18425         struct bpf_insn_aux_data *aux = env->insn_aux_data;
18426         int i, patch_len, delta = 0, len = env->prog->len;
18427         struct bpf_insn *insns = env->prog->insnsi;
18428         struct bpf_prog *new_prog;
18429         bool rnd_hi32;
18430
18431         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
18432         zext_patch[1] = BPF_ZEXT_REG(0);
18433         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
18434         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
18435         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
18436         for (i = 0; i < len; i++) {
18437                 int adj_idx = i + delta;
18438                 struct bpf_insn insn;
18439                 int load_reg;
18440
18441                 insn = insns[adj_idx];
18442                 load_reg = insn_def_regno(&insn);
18443                 if (!aux[adj_idx].zext_dst) {
18444                         u8 code, class;
18445                         u32 imm_rnd;
18446
18447                         if (!rnd_hi32)
18448                                 continue;
18449
18450                         code = insn.code;
18451                         class = BPF_CLASS(code);
18452                         if (load_reg == -1)
18453                                 continue;
18454
18455                         /* NOTE: arg "reg" (the fourth one) is only used for
18456                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
18457                          *       here.
18458                          */
18459                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
18460                                 if (class == BPF_LD &&
18461                                     BPF_MODE(code) == BPF_IMM)
18462                                         i++;
18463                                 continue;
18464                         }
18465
18466                         /* ctx load could be transformed into wider load. */
18467                         if (class == BPF_LDX &&
18468                             aux[adj_idx].ptr_type == PTR_TO_CTX)
18469                                 continue;
18470
18471                         imm_rnd = get_random_u32();
18472                         rnd_hi32_patch[0] = insn;
18473                         rnd_hi32_patch[1].imm = imm_rnd;
18474                         rnd_hi32_patch[3].dst_reg = load_reg;
18475                         patch = rnd_hi32_patch;
18476                         patch_len = 4;
18477                         goto apply_patch_buffer;
18478                 }
18479
18480                 /* Add in an zero-extend instruction if a) the JIT has requested
18481                  * it or b) it's a CMPXCHG.
18482                  *
18483                  * The latter is because: BPF_CMPXCHG always loads a value into
18484                  * R0, therefore always zero-extends. However some archs'
18485                  * equivalent instruction only does this load when the
18486                  * comparison is successful. This detail of CMPXCHG is
18487                  * orthogonal to the general zero-extension behaviour of the
18488                  * CPU, so it's treated independently of bpf_jit_needs_zext.
18489                  */
18490                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
18491                         continue;
18492
18493                 /* Zero-extension is done by the caller. */
18494                 if (bpf_pseudo_kfunc_call(&insn))
18495                         continue;
18496
18497                 if (WARN_ON(load_reg == -1)) {
18498                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
18499                         return -EFAULT;
18500                 }
18501
18502                 zext_patch[0] = insn;
18503                 zext_patch[1].dst_reg = load_reg;
18504                 zext_patch[1].src_reg = load_reg;
18505                 patch = zext_patch;
18506                 patch_len = 2;
18507 apply_patch_buffer:
18508                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
18509                 if (!new_prog)
18510                         return -ENOMEM;
18511                 env->prog = new_prog;
18512                 insns = new_prog->insnsi;
18513                 aux = env->insn_aux_data;
18514                 delta += patch_len - 1;
18515         }
18516
18517         return 0;
18518 }
18519
18520 /* convert load instructions that access fields of a context type into a
18521  * sequence of instructions that access fields of the underlying structure:
18522  *     struct __sk_buff    -> struct sk_buff
18523  *     struct bpf_sock_ops -> struct sock
18524  */
18525 static int convert_ctx_accesses(struct bpf_verifier_env *env)
18526 {
18527         const struct bpf_verifier_ops *ops = env->ops;
18528         int i, cnt, size, ctx_field_size, delta = 0;
18529         const int insn_cnt = env->prog->len;
18530         struct bpf_insn insn_buf[16], *insn;
18531         u32 target_size, size_default, off;
18532         struct bpf_prog *new_prog;
18533         enum bpf_access_type type;
18534         bool is_narrower_load;
18535
18536         if (ops->gen_prologue || env->seen_direct_write) {
18537                 if (!ops->gen_prologue) {
18538                         verbose(env, "bpf verifier is misconfigured\n");
18539                         return -EINVAL;
18540                 }
18541                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
18542                                         env->prog);
18543                 if (cnt >= ARRAY_SIZE(insn_buf)) {
18544                         verbose(env, "bpf verifier is misconfigured\n");
18545                         return -EINVAL;
18546                 } else if (cnt) {
18547                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
18548                         if (!new_prog)
18549                                 return -ENOMEM;
18550
18551                         env->prog = new_prog;
18552                         delta += cnt - 1;
18553                 }
18554         }
18555
18556         if (bpf_prog_is_offloaded(env->prog->aux))
18557                 return 0;
18558
18559         insn = env->prog->insnsi + delta;
18560
18561         for (i = 0; i < insn_cnt; i++, insn++) {
18562                 bpf_convert_ctx_access_t convert_ctx_access;
18563                 u8 mode;
18564
18565                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
18566                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
18567                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
18568                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
18569                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
18570                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
18571                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
18572                         type = BPF_READ;
18573                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
18574                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
18575                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
18576                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
18577                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
18578                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
18579                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
18580                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
18581                         type = BPF_WRITE;
18582                 } else {
18583                         continue;
18584                 }
18585
18586                 if (type == BPF_WRITE &&
18587                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
18588                         struct bpf_insn patch[] = {
18589                                 *insn,
18590                                 BPF_ST_NOSPEC(),
18591                         };
18592
18593                         cnt = ARRAY_SIZE(patch);
18594                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
18595                         if (!new_prog)
18596                                 return -ENOMEM;
18597
18598                         delta    += cnt - 1;
18599                         env->prog = new_prog;
18600                         insn      = new_prog->insnsi + i + delta;
18601                         continue;
18602                 }
18603
18604                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
18605                 case PTR_TO_CTX:
18606                         if (!ops->convert_ctx_access)
18607                                 continue;
18608                         convert_ctx_access = ops->convert_ctx_access;
18609                         break;
18610                 case PTR_TO_SOCKET:
18611                 case PTR_TO_SOCK_COMMON:
18612                         convert_ctx_access = bpf_sock_convert_ctx_access;
18613                         break;
18614                 case PTR_TO_TCP_SOCK:
18615                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
18616                         break;
18617                 case PTR_TO_XDP_SOCK:
18618                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
18619                         break;
18620                 case PTR_TO_BTF_ID:
18621                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
18622                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
18623                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
18624                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
18625                  * any faults for loads into such types. BPF_WRITE is disallowed
18626                  * for this case.
18627                  */
18628                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
18629                         if (type == BPF_READ) {
18630                                 if (BPF_MODE(insn->code) == BPF_MEM)
18631                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
18632                                                      BPF_SIZE((insn)->code);
18633                                 else
18634                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
18635                                                      BPF_SIZE((insn)->code);
18636                                 env->prog->aux->num_exentries++;
18637                         }
18638                         continue;
18639                 default:
18640                         continue;
18641                 }
18642
18643                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
18644                 size = BPF_LDST_BYTES(insn);
18645                 mode = BPF_MODE(insn->code);
18646
18647                 /* If the read access is a narrower load of the field,
18648                  * convert to a 4/8-byte load, to minimum program type specific
18649                  * convert_ctx_access changes. If conversion is successful,
18650                  * we will apply proper mask to the result.
18651                  */
18652                 is_narrower_load = size < ctx_field_size;
18653                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
18654                 off = insn->off;
18655                 if (is_narrower_load) {
18656                         u8 size_code;
18657
18658                         if (type == BPF_WRITE) {
18659                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
18660                                 return -EINVAL;
18661                         }
18662
18663                         size_code = BPF_H;
18664                         if (ctx_field_size == 4)
18665                                 size_code = BPF_W;
18666                         else if (ctx_field_size == 8)
18667                                 size_code = BPF_DW;
18668
18669                         insn->off = off & ~(size_default - 1);
18670                         insn->code = BPF_LDX | BPF_MEM | size_code;
18671                 }
18672
18673                 target_size = 0;
18674                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
18675                                          &target_size);
18676                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
18677                     (ctx_field_size && !target_size)) {
18678                         verbose(env, "bpf verifier is misconfigured\n");
18679                         return -EINVAL;
18680                 }
18681
18682                 if (is_narrower_load && size < target_size) {
18683                         u8 shift = bpf_ctx_narrow_access_offset(
18684                                 off, size, size_default) * 8;
18685                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
18686                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
18687                                 return -EINVAL;
18688                         }
18689                         if (ctx_field_size <= 4) {
18690                                 if (shift)
18691                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
18692                                                                         insn->dst_reg,
18693                                                                         shift);
18694                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18695                                                                 (1 << size * 8) - 1);
18696                         } else {
18697                                 if (shift)
18698                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
18699                                                                         insn->dst_reg,
18700                                                                         shift);
18701                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
18702                                                                 (1ULL << size * 8) - 1);
18703                         }
18704                 }
18705                 if (mode == BPF_MEMSX)
18706                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
18707                                                        insn->dst_reg, insn->dst_reg,
18708                                                        size * 8, 0);
18709
18710                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18711                 if (!new_prog)
18712                         return -ENOMEM;
18713
18714                 delta += cnt - 1;
18715
18716                 /* keep walking new program and skip insns we just inserted */
18717                 env->prog = new_prog;
18718                 insn      = new_prog->insnsi + i + delta;
18719         }
18720
18721         return 0;
18722 }
18723
18724 static int jit_subprogs(struct bpf_verifier_env *env)
18725 {
18726         struct bpf_prog *prog = env->prog, **func, *tmp;
18727         int i, j, subprog_start, subprog_end = 0, len, subprog;
18728         struct bpf_map *map_ptr;
18729         struct bpf_insn *insn;
18730         void *old_bpf_func;
18731         int err, num_exentries;
18732
18733         if (env->subprog_cnt <= 1)
18734                 return 0;
18735
18736         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18737                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
18738                         continue;
18739
18740                 /* Upon error here we cannot fall back to interpreter but
18741                  * need a hard reject of the program. Thus -EFAULT is
18742                  * propagated in any case.
18743                  */
18744                 subprog = find_subprog(env, i + insn->imm + 1);
18745                 if (subprog < 0) {
18746                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
18747                                   i + insn->imm + 1);
18748                         return -EFAULT;
18749                 }
18750                 /* temporarily remember subprog id inside insn instead of
18751                  * aux_data, since next loop will split up all insns into funcs
18752                  */
18753                 insn->off = subprog;
18754                 /* remember original imm in case JIT fails and fallback
18755                  * to interpreter will be needed
18756                  */
18757                 env->insn_aux_data[i].call_imm = insn->imm;
18758                 /* point imm to __bpf_call_base+1 from JITs point of view */
18759                 insn->imm = 1;
18760                 if (bpf_pseudo_func(insn))
18761                         /* jit (e.g. x86_64) may emit fewer instructions
18762                          * if it learns a u32 imm is the same as a u64 imm.
18763                          * Force a non zero here.
18764                          */
18765                         insn[1].imm = 1;
18766         }
18767
18768         err = bpf_prog_alloc_jited_linfo(prog);
18769         if (err)
18770                 goto out_undo_insn;
18771
18772         err = -ENOMEM;
18773         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
18774         if (!func)
18775                 goto out_undo_insn;
18776
18777         for (i = 0; i < env->subprog_cnt; i++) {
18778                 subprog_start = subprog_end;
18779                 subprog_end = env->subprog_info[i + 1].start;
18780
18781                 len = subprog_end - subprog_start;
18782                 /* bpf_prog_run() doesn't call subprogs directly,
18783                  * hence main prog stats include the runtime of subprogs.
18784                  * subprogs don't have IDs and not reachable via prog_get_next_id
18785                  * func[i]->stats will never be accessed and stays NULL
18786                  */
18787                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18788                 if (!func[i])
18789                         goto out_free;
18790                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18791                        len * sizeof(struct bpf_insn));
18792                 func[i]->type = prog->type;
18793                 func[i]->len = len;
18794                 if (bpf_prog_calc_tag(func[i]))
18795                         goto out_free;
18796                 func[i]->is_func = 1;
18797                 func[i]->aux->func_idx = i;
18798                 /* Below members will be freed only at prog->aux */
18799                 func[i]->aux->btf = prog->aux->btf;
18800                 func[i]->aux->func_info = prog->aux->func_info;
18801                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18802                 func[i]->aux->poke_tab = prog->aux->poke_tab;
18803                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18804
18805                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18806                         struct bpf_jit_poke_descriptor *poke;
18807
18808                         poke = &prog->aux->poke_tab[j];
18809                         if (poke->insn_idx < subprog_end &&
18810                             poke->insn_idx >= subprog_start)
18811                                 poke->aux = func[i]->aux;
18812                 }
18813
18814                 func[i]->aux->name[0] = 'F';
18815                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18816                 func[i]->jit_requested = 1;
18817                 func[i]->blinding_requested = prog->blinding_requested;
18818                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18819                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18820                 func[i]->aux->linfo = prog->aux->linfo;
18821                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18822                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18823                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18824                 num_exentries = 0;
18825                 insn = func[i]->insnsi;
18826                 for (j = 0; j < func[i]->len; j++, insn++) {
18827                         if (BPF_CLASS(insn->code) == BPF_LDX &&
18828                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18829                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18830                                 num_exentries++;
18831                 }
18832                 func[i]->aux->num_exentries = num_exentries;
18833                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18834                 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
18835                 if (!i)
18836                         func[i]->aux->exception_boundary = env->seen_exception;
18837                 func[i] = bpf_int_jit_compile(func[i]);
18838                 if (!func[i]->jited) {
18839                         err = -ENOTSUPP;
18840                         goto out_free;
18841                 }
18842                 cond_resched();
18843         }
18844
18845         /* at this point all bpf functions were successfully JITed
18846          * now populate all bpf_calls with correct addresses and
18847          * run last pass of JIT
18848          */
18849         for (i = 0; i < env->subprog_cnt; i++) {
18850                 insn = func[i]->insnsi;
18851                 for (j = 0; j < func[i]->len; j++, insn++) {
18852                         if (bpf_pseudo_func(insn)) {
18853                                 subprog = insn->off;
18854                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18855                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18856                                 continue;
18857                         }
18858                         if (!bpf_pseudo_call(insn))
18859                                 continue;
18860                         subprog = insn->off;
18861                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18862                 }
18863
18864                 /* we use the aux data to keep a list of the start addresses
18865                  * of the JITed images for each function in the program
18866                  *
18867                  * for some architectures, such as powerpc64, the imm field
18868                  * might not be large enough to hold the offset of the start
18869                  * address of the callee's JITed image from __bpf_call_base
18870                  *
18871                  * in such cases, we can lookup the start address of a callee
18872                  * by using its subprog id, available from the off field of
18873                  * the call instruction, as an index for this list
18874                  */
18875                 func[i]->aux->func = func;
18876                 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18877                 func[i]->aux->real_func_cnt = env->subprog_cnt;
18878         }
18879         for (i = 0; i < env->subprog_cnt; i++) {
18880                 old_bpf_func = func[i]->bpf_func;
18881                 tmp = bpf_int_jit_compile(func[i]);
18882                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18883                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18884                         err = -ENOTSUPP;
18885                         goto out_free;
18886                 }
18887                 cond_resched();
18888         }
18889
18890         /* finally lock prog and jit images for all functions and
18891          * populate kallsysm. Begin at the first subprogram, since
18892          * bpf_prog_load will add the kallsyms for the main program.
18893          */
18894         for (i = 1; i < env->subprog_cnt; i++) {
18895                 bpf_prog_lock_ro(func[i]);
18896                 bpf_prog_kallsyms_add(func[i]);
18897         }
18898
18899         /* Last step: make now unused interpreter insns from main
18900          * prog consistent for later dump requests, so they can
18901          * later look the same as if they were interpreted only.
18902          */
18903         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18904                 if (bpf_pseudo_func(insn)) {
18905                         insn[0].imm = env->insn_aux_data[i].call_imm;
18906                         insn[1].imm = insn->off;
18907                         insn->off = 0;
18908                         continue;
18909                 }
18910                 if (!bpf_pseudo_call(insn))
18911                         continue;
18912                 insn->off = env->insn_aux_data[i].call_imm;
18913                 subprog = find_subprog(env, i + insn->off + 1);
18914                 insn->imm = subprog;
18915         }
18916
18917         prog->jited = 1;
18918         prog->bpf_func = func[0]->bpf_func;
18919         prog->jited_len = func[0]->jited_len;
18920         prog->aux->extable = func[0]->aux->extable;
18921         prog->aux->num_exentries = func[0]->aux->num_exentries;
18922         prog->aux->func = func;
18923         prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
18924         prog->aux->real_func_cnt = env->subprog_cnt;
18925         prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
18926         prog->aux->exception_boundary = func[0]->aux->exception_boundary;
18927         bpf_prog_jit_attempt_done(prog);
18928         return 0;
18929 out_free:
18930         /* We failed JIT'ing, so at this point we need to unregister poke
18931          * descriptors from subprogs, so that kernel is not attempting to
18932          * patch it anymore as we're freeing the subprog JIT memory.
18933          */
18934         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18935                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18936                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18937         }
18938         /* At this point we're guaranteed that poke descriptors are not
18939          * live anymore. We can just unlink its descriptor table as it's
18940          * released with the main prog.
18941          */
18942         for (i = 0; i < env->subprog_cnt; i++) {
18943                 if (!func[i])
18944                         continue;
18945                 func[i]->aux->poke_tab = NULL;
18946                 bpf_jit_free(func[i]);
18947         }
18948         kfree(func);
18949 out_undo_insn:
18950         /* cleanup main prog to be interpreted */
18951         prog->jit_requested = 0;
18952         prog->blinding_requested = 0;
18953         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18954                 if (!bpf_pseudo_call(insn))
18955                         continue;
18956                 insn->off = 0;
18957                 insn->imm = env->insn_aux_data[i].call_imm;
18958         }
18959         bpf_prog_jit_attempt_done(prog);
18960         return err;
18961 }
18962
18963 static int fixup_call_args(struct bpf_verifier_env *env)
18964 {
18965 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18966         struct bpf_prog *prog = env->prog;
18967         struct bpf_insn *insn = prog->insnsi;
18968         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18969         int i, depth;
18970 #endif
18971         int err = 0;
18972
18973         if (env->prog->jit_requested &&
18974             !bpf_prog_is_offloaded(env->prog->aux)) {
18975                 err = jit_subprogs(env);
18976                 if (err == 0)
18977                         return 0;
18978                 if (err == -EFAULT)
18979                         return err;
18980         }
18981 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18982         if (has_kfunc_call) {
18983                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18984                 return -EINVAL;
18985         }
18986         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18987                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18988                  * have to be rejected, since interpreter doesn't support them yet.
18989                  */
18990                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18991                 return -EINVAL;
18992         }
18993         for (i = 0; i < prog->len; i++, insn++) {
18994                 if (bpf_pseudo_func(insn)) {
18995                         /* When JIT fails the progs with callback calls
18996                          * have to be rejected, since interpreter doesn't support them yet.
18997                          */
18998                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18999                         return -EINVAL;
19000                 }
19001
19002                 if (!bpf_pseudo_call(insn))
19003                         continue;
19004                 depth = get_callee_stack_depth(env, insn, i);
19005                 if (depth < 0)
19006                         return depth;
19007                 bpf_patch_call_args(insn, depth);
19008         }
19009         err = 0;
19010 #endif
19011         return err;
19012 }
19013
19014 /* replace a generic kfunc with a specialized version if necessary */
19015 static void specialize_kfunc(struct bpf_verifier_env *env,
19016                              u32 func_id, u16 offset, unsigned long *addr)
19017 {
19018         struct bpf_prog *prog = env->prog;
19019         bool seen_direct_write;
19020         void *xdp_kfunc;
19021         bool is_rdonly;
19022
19023         if (bpf_dev_bound_kfunc_id(func_id)) {
19024                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
19025                 if (xdp_kfunc) {
19026                         *addr = (unsigned long)xdp_kfunc;
19027                         return;
19028                 }
19029                 /* fallback to default kfunc when not supported by netdev */
19030         }
19031
19032         if (offset)
19033                 return;
19034
19035         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
19036                 seen_direct_write = env->seen_direct_write;
19037                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
19038
19039                 if (is_rdonly)
19040                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
19041
19042                 /* restore env->seen_direct_write to its original value, since
19043                  * may_access_direct_pkt_data mutates it
19044                  */
19045                 env->seen_direct_write = seen_direct_write;
19046         }
19047 }
19048
19049 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
19050                                             u16 struct_meta_reg,
19051                                             u16 node_offset_reg,
19052                                             struct bpf_insn *insn,
19053                                             struct bpf_insn *insn_buf,
19054                                             int *cnt)
19055 {
19056         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
19057         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
19058
19059         insn_buf[0] = addr[0];
19060         insn_buf[1] = addr[1];
19061         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
19062         insn_buf[3] = *insn;
19063         *cnt = 4;
19064 }
19065
19066 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
19067                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
19068 {
19069         const struct bpf_kfunc_desc *desc;
19070
19071         if (!insn->imm) {
19072                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
19073                 return -EINVAL;
19074         }
19075
19076         *cnt = 0;
19077
19078         /* insn->imm has the btf func_id. Replace it with an offset relative to
19079          * __bpf_call_base, unless the JIT needs to call functions that are
19080          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
19081          */
19082         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
19083         if (!desc) {
19084                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
19085                         insn->imm);
19086                 return -EFAULT;
19087         }
19088
19089         if (!bpf_jit_supports_far_kfunc_call())
19090                 insn->imm = BPF_CALL_IMM(desc->addr);
19091         if (insn->off)
19092                 return 0;
19093         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] ||
19094             desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) {
19095                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19096                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19097                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
19098
19099                 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) {
19100                         verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19101                                 insn_idx);
19102                         return -EFAULT;
19103                 }
19104
19105                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
19106                 insn_buf[1] = addr[0];
19107                 insn_buf[2] = addr[1];
19108                 insn_buf[3] = *insn;
19109                 *cnt = 4;
19110         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
19111                    desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] ||
19112                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
19113                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19114                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
19115
19116                 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) {
19117                         verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n",
19118                                 insn_idx);
19119                         return -EFAULT;
19120                 }
19121
19122                 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
19123                     !kptr_struct_meta) {
19124                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19125                                 insn_idx);
19126                         return -EFAULT;
19127                 }
19128
19129                 insn_buf[0] = addr[0];
19130                 insn_buf[1] = addr[1];
19131                 insn_buf[2] = *insn;
19132                 *cnt = 3;
19133         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
19134                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
19135                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19136                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
19137                 int struct_meta_reg = BPF_REG_3;
19138                 int node_offset_reg = BPF_REG_4;
19139
19140                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
19141                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
19142                         struct_meta_reg = BPF_REG_4;
19143                         node_offset_reg = BPF_REG_5;
19144                 }
19145
19146                 if (!kptr_struct_meta) {
19147                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
19148                                 insn_idx);
19149                         return -EFAULT;
19150                 }
19151
19152                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
19153                                                 node_offset_reg, insn, insn_buf, cnt);
19154         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
19155                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
19156                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
19157                 *cnt = 1;
19158         }
19159         return 0;
19160 }
19161
19162 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
19163 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
19164 {
19165         struct bpf_subprog_info *info = env->subprog_info;
19166         int cnt = env->subprog_cnt;
19167         struct bpf_prog *prog;
19168
19169         /* We only reserve one slot for hidden subprogs in subprog_info. */
19170         if (env->hidden_subprog_cnt) {
19171                 verbose(env, "verifier internal error: only one hidden subprog supported\n");
19172                 return -EFAULT;
19173         }
19174         /* We're not patching any existing instruction, just appending the new
19175          * ones for the hidden subprog. Hence all of the adjustment operations
19176          * in bpf_patch_insn_data are no-ops.
19177          */
19178         prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
19179         if (!prog)
19180                 return -ENOMEM;
19181         env->prog = prog;
19182         info[cnt + 1].start = info[cnt].start;
19183         info[cnt].start = prog->len - len + 1;
19184         env->subprog_cnt++;
19185         env->hidden_subprog_cnt++;
19186         return 0;
19187 }
19188
19189 /* Do various post-verification rewrites in a single program pass.
19190  * These rewrites simplify JIT and interpreter implementations.
19191  */
19192 static int do_misc_fixups(struct bpf_verifier_env *env)
19193 {
19194         struct bpf_prog *prog = env->prog;
19195         enum bpf_attach_type eatype = prog->expected_attach_type;
19196         enum bpf_prog_type prog_type = resolve_prog_type(prog);
19197         struct bpf_insn *insn = prog->insnsi;
19198         const struct bpf_func_proto *fn;
19199         const int insn_cnt = prog->len;
19200         const struct bpf_map_ops *ops;
19201         struct bpf_insn_aux_data *aux;
19202         struct bpf_insn insn_buf[16];
19203         struct bpf_prog *new_prog;
19204         struct bpf_map *map_ptr;
19205         int i, ret, cnt, delta = 0;
19206
19207         if (env->seen_exception && !env->exception_callback_subprog) {
19208                 struct bpf_insn patch[] = {
19209                         env->prog->insnsi[insn_cnt - 1],
19210                         BPF_MOV64_REG(BPF_REG_0, BPF_REG_1),
19211                         BPF_EXIT_INSN(),
19212                 };
19213
19214                 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch));
19215                 if (ret < 0)
19216                         return ret;
19217                 prog = env->prog;
19218                 insn = prog->insnsi;
19219
19220                 env->exception_callback_subprog = env->subprog_cnt - 1;
19221                 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */
19222                 env->subprog_info[env->exception_callback_subprog].is_cb = true;
19223                 env->subprog_info[env->exception_callback_subprog].is_async_cb = true;
19224                 env->subprog_info[env->exception_callback_subprog].is_exception_cb = true;
19225         }
19226
19227         for (i = 0; i < insn_cnt; i++, insn++) {
19228                 /* Make divide-by-zero exceptions impossible. */
19229                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
19230                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
19231                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
19232                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
19233                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
19234                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
19235                         struct bpf_insn *patchlet;
19236                         struct bpf_insn chk_and_div[] = {
19237                                 /* [R,W]x div 0 -> 0 */
19238                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19239                                              BPF_JNE | BPF_K, insn->src_reg,
19240                                              0, 2, 0),
19241                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
19242                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19243                                 *insn,
19244                         };
19245                         struct bpf_insn chk_and_mod[] = {
19246                                 /* [R,W]x mod 0 -> [R,W]x */
19247                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
19248                                              BPF_JEQ | BPF_K, insn->src_reg,
19249                                              0, 1 + (is64 ? 0 : 1), 0),
19250                                 *insn,
19251                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
19252                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
19253                         };
19254
19255                         patchlet = isdiv ? chk_and_div : chk_and_mod;
19256                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
19257                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
19258
19259                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
19260                         if (!new_prog)
19261                                 return -ENOMEM;
19262
19263                         delta    += cnt - 1;
19264                         env->prog = prog = new_prog;
19265                         insn      = new_prog->insnsi + i + delta;
19266                         continue;
19267                 }
19268
19269                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
19270                 if (BPF_CLASS(insn->code) == BPF_LD &&
19271                     (BPF_MODE(insn->code) == BPF_ABS ||
19272                      BPF_MODE(insn->code) == BPF_IND)) {
19273                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
19274                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19275                                 verbose(env, "bpf verifier is misconfigured\n");
19276                                 return -EINVAL;
19277                         }
19278
19279                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19280                         if (!new_prog)
19281                                 return -ENOMEM;
19282
19283                         delta    += cnt - 1;
19284                         env->prog = prog = new_prog;
19285                         insn      = new_prog->insnsi + i + delta;
19286                         continue;
19287                 }
19288
19289                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
19290                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
19291                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
19292                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
19293                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
19294                         struct bpf_insn *patch = &insn_buf[0];
19295                         bool issrc, isneg, isimm;
19296                         u32 off_reg;
19297
19298                         aux = &env->insn_aux_data[i + delta];
19299                         if (!aux->alu_state ||
19300                             aux->alu_state == BPF_ALU_NON_POINTER)
19301                                 continue;
19302
19303                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
19304                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
19305                                 BPF_ALU_SANITIZE_SRC;
19306                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
19307
19308                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
19309                         if (isimm) {
19310                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19311                         } else {
19312                                 if (isneg)
19313                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19314                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
19315                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
19316                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
19317                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
19318                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
19319                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
19320                         }
19321                         if (!issrc)
19322                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
19323                         insn->src_reg = BPF_REG_AX;
19324                         if (isneg)
19325                                 insn->code = insn->code == code_add ?
19326                                              code_sub : code_add;
19327                         *patch++ = *insn;
19328                         if (issrc && isneg && !isimm)
19329                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
19330                         cnt = patch - insn_buf;
19331
19332                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19333                         if (!new_prog)
19334                                 return -ENOMEM;
19335
19336                         delta    += cnt - 1;
19337                         env->prog = prog = new_prog;
19338                         insn      = new_prog->insnsi + i + delta;
19339                         continue;
19340                 }
19341
19342                 if (insn->code != (BPF_JMP | BPF_CALL))
19343                         continue;
19344                 if (insn->src_reg == BPF_PSEUDO_CALL)
19345                         continue;
19346                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
19347                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
19348                         if (ret)
19349                                 return ret;
19350                         if (cnt == 0)
19351                                 continue;
19352
19353                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19354                         if (!new_prog)
19355                                 return -ENOMEM;
19356
19357                         delta    += cnt - 1;
19358                         env->prog = prog = new_prog;
19359                         insn      = new_prog->insnsi + i + delta;
19360                         continue;
19361                 }
19362
19363                 if (insn->imm == BPF_FUNC_get_route_realm)
19364                         prog->dst_needed = 1;
19365                 if (insn->imm == BPF_FUNC_get_prandom_u32)
19366                         bpf_user_rnd_init_once();
19367                 if (insn->imm == BPF_FUNC_override_return)
19368                         prog->kprobe_override = 1;
19369                 if (insn->imm == BPF_FUNC_tail_call) {
19370                         /* If we tail call into other programs, we
19371                          * cannot make any assumptions since they can
19372                          * be replaced dynamically during runtime in
19373                          * the program array.
19374                          */
19375                         prog->cb_access = 1;
19376                         if (!allow_tail_call_in_subprogs(env))
19377                                 prog->aux->stack_depth = MAX_BPF_STACK;
19378                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
19379
19380                         /* mark bpf_tail_call as different opcode to avoid
19381                          * conditional branch in the interpreter for every normal
19382                          * call and to prevent accidental JITing by JIT compiler
19383                          * that doesn't support bpf_tail_call yet
19384                          */
19385                         insn->imm = 0;
19386                         insn->code = BPF_JMP | BPF_TAIL_CALL;
19387
19388                         aux = &env->insn_aux_data[i + delta];
19389                         if (env->bpf_capable && !prog->blinding_requested &&
19390                             prog->jit_requested &&
19391                             !bpf_map_key_poisoned(aux) &&
19392                             !bpf_map_ptr_poisoned(aux) &&
19393                             !bpf_map_ptr_unpriv(aux)) {
19394                                 struct bpf_jit_poke_descriptor desc = {
19395                                         .reason = BPF_POKE_REASON_TAIL_CALL,
19396                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
19397                                         .tail_call.key = bpf_map_key_immediate(aux),
19398                                         .insn_idx = i + delta,
19399                                 };
19400
19401                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
19402                                 if (ret < 0) {
19403                                         verbose(env, "adding tail call poke descriptor failed\n");
19404                                         return ret;
19405                                 }
19406
19407                                 insn->imm = ret + 1;
19408                                 continue;
19409                         }
19410
19411                         if (!bpf_map_ptr_unpriv(aux))
19412                                 continue;
19413
19414                         /* instead of changing every JIT dealing with tail_call
19415                          * emit two extra insns:
19416                          * if (index >= max_entries) goto out;
19417                          * index &= array->index_mask;
19418                          * to avoid out-of-bounds cpu speculation
19419                          */
19420                         if (bpf_map_ptr_poisoned(aux)) {
19421                                 verbose(env, "tail_call abusing map_ptr\n");
19422                                 return -EINVAL;
19423                         }
19424
19425                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19426                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
19427                                                   map_ptr->max_entries, 2);
19428                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
19429                                                     container_of(map_ptr,
19430                                                                  struct bpf_array,
19431                                                                  map)->index_mask);
19432                         insn_buf[2] = *insn;
19433                         cnt = 3;
19434                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19435                         if (!new_prog)
19436                                 return -ENOMEM;
19437
19438                         delta    += cnt - 1;
19439                         env->prog = prog = new_prog;
19440                         insn      = new_prog->insnsi + i + delta;
19441                         continue;
19442                 }
19443
19444                 if (insn->imm == BPF_FUNC_timer_set_callback) {
19445                         /* The verifier will process callback_fn as many times as necessary
19446                          * with different maps and the register states prepared by
19447                          * set_timer_callback_state will be accurate.
19448                          *
19449                          * The following use case is valid:
19450                          *   map1 is shared by prog1, prog2, prog3.
19451                          *   prog1 calls bpf_timer_init for some map1 elements
19452                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
19453                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
19454                          *   prog3 calls bpf_timer_start for some map1 elements.
19455                          *     Those that were not both bpf_timer_init-ed and
19456                          *     bpf_timer_set_callback-ed will return -EINVAL.
19457                          */
19458                         struct bpf_insn ld_addrs[2] = {
19459                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
19460                         };
19461
19462                         insn_buf[0] = ld_addrs[0];
19463                         insn_buf[1] = ld_addrs[1];
19464                         insn_buf[2] = *insn;
19465                         cnt = 3;
19466
19467                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19468                         if (!new_prog)
19469                                 return -ENOMEM;
19470
19471                         delta    += cnt - 1;
19472                         env->prog = prog = new_prog;
19473                         insn      = new_prog->insnsi + i + delta;
19474                         goto patch_call_imm;
19475                 }
19476
19477                 if (is_storage_get_function(insn->imm)) {
19478                         if (!env->prog->aux->sleepable ||
19479                             env->insn_aux_data[i + delta].storage_get_func_atomic)
19480                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
19481                         else
19482                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
19483                         insn_buf[1] = *insn;
19484                         cnt = 2;
19485
19486                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19487                         if (!new_prog)
19488                                 return -ENOMEM;
19489
19490                         delta += cnt - 1;
19491                         env->prog = prog = new_prog;
19492                         insn = new_prog->insnsi + i + delta;
19493                         goto patch_call_imm;
19494                 }
19495
19496                 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
19497                 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
19498                         /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
19499                          * bpf_mem_alloc() returns a ptr to the percpu data ptr.
19500                          */
19501                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
19502                         insn_buf[1] = *insn;
19503                         cnt = 2;
19504
19505                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19506                         if (!new_prog)
19507                                 return -ENOMEM;
19508
19509                         delta += cnt - 1;
19510                         env->prog = prog = new_prog;
19511                         insn = new_prog->insnsi + i + delta;
19512                         goto patch_call_imm;
19513                 }
19514
19515                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
19516                  * and other inlining handlers are currently limited to 64 bit
19517                  * only.
19518                  */
19519                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19520                     (insn->imm == BPF_FUNC_map_lookup_elem ||
19521                      insn->imm == BPF_FUNC_map_update_elem ||
19522                      insn->imm == BPF_FUNC_map_delete_elem ||
19523                      insn->imm == BPF_FUNC_map_push_elem   ||
19524                      insn->imm == BPF_FUNC_map_pop_elem    ||
19525                      insn->imm == BPF_FUNC_map_peek_elem   ||
19526                      insn->imm == BPF_FUNC_redirect_map    ||
19527                      insn->imm == BPF_FUNC_for_each_map_elem ||
19528                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
19529                         aux = &env->insn_aux_data[i + delta];
19530                         if (bpf_map_ptr_poisoned(aux))
19531                                 goto patch_call_imm;
19532
19533                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
19534                         ops = map_ptr->ops;
19535                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
19536                             ops->map_gen_lookup) {
19537                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
19538                                 if (cnt == -EOPNOTSUPP)
19539                                         goto patch_map_ops_generic;
19540                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
19541                                         verbose(env, "bpf verifier is misconfigured\n");
19542                                         return -EINVAL;
19543                                 }
19544
19545                                 new_prog = bpf_patch_insn_data(env, i + delta,
19546                                                                insn_buf, cnt);
19547                                 if (!new_prog)
19548                                         return -ENOMEM;
19549
19550                                 delta    += cnt - 1;
19551                                 env->prog = prog = new_prog;
19552                                 insn      = new_prog->insnsi + i + delta;
19553                                 continue;
19554                         }
19555
19556                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
19557                                      (void *(*)(struct bpf_map *map, void *key))NULL));
19558                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
19559                                      (long (*)(struct bpf_map *map, void *key))NULL));
19560                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
19561                                      (long (*)(struct bpf_map *map, void *key, void *value,
19562                                               u64 flags))NULL));
19563                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
19564                                      (long (*)(struct bpf_map *map, void *value,
19565                                               u64 flags))NULL));
19566                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
19567                                      (long (*)(struct bpf_map *map, void *value))NULL));
19568                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
19569                                      (long (*)(struct bpf_map *map, void *value))NULL));
19570                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
19571                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
19572                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
19573                                      (long (*)(struct bpf_map *map,
19574                                               bpf_callback_t callback_fn,
19575                                               void *callback_ctx,
19576                                               u64 flags))NULL));
19577                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
19578                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
19579
19580 patch_map_ops_generic:
19581                         switch (insn->imm) {
19582                         case BPF_FUNC_map_lookup_elem:
19583                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
19584                                 continue;
19585                         case BPF_FUNC_map_update_elem:
19586                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
19587                                 continue;
19588                         case BPF_FUNC_map_delete_elem:
19589                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
19590                                 continue;
19591                         case BPF_FUNC_map_push_elem:
19592                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
19593                                 continue;
19594                         case BPF_FUNC_map_pop_elem:
19595                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
19596                                 continue;
19597                         case BPF_FUNC_map_peek_elem:
19598                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
19599                                 continue;
19600                         case BPF_FUNC_redirect_map:
19601                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
19602                                 continue;
19603                         case BPF_FUNC_for_each_map_elem:
19604                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
19605                                 continue;
19606                         case BPF_FUNC_map_lookup_percpu_elem:
19607                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
19608                                 continue;
19609                         }
19610
19611                         goto patch_call_imm;
19612                 }
19613
19614                 /* Implement bpf_jiffies64 inline. */
19615                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
19616                     insn->imm == BPF_FUNC_jiffies64) {
19617                         struct bpf_insn ld_jiffies_addr[2] = {
19618                                 BPF_LD_IMM64(BPF_REG_0,
19619                                              (unsigned long)&jiffies),
19620                         };
19621
19622                         insn_buf[0] = ld_jiffies_addr[0];
19623                         insn_buf[1] = ld_jiffies_addr[1];
19624                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
19625                                                   BPF_REG_0, 0);
19626                         cnt = 3;
19627
19628                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
19629                                                        cnt);
19630                         if (!new_prog)
19631                                 return -ENOMEM;
19632
19633                         delta    += cnt - 1;
19634                         env->prog = prog = new_prog;
19635                         insn      = new_prog->insnsi + i + delta;
19636                         continue;
19637                 }
19638
19639                 /* Implement bpf_get_func_arg inline. */
19640                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19641                     insn->imm == BPF_FUNC_get_func_arg) {
19642                         /* Load nr_args from ctx - 8 */
19643                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19644                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
19645                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
19646                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
19647                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
19648                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19649                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
19650                         insn_buf[7] = BPF_JMP_A(1);
19651                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
19652                         cnt = 9;
19653
19654                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19655                         if (!new_prog)
19656                                 return -ENOMEM;
19657
19658                         delta    += cnt - 1;
19659                         env->prog = prog = new_prog;
19660                         insn      = new_prog->insnsi + i + delta;
19661                         continue;
19662                 }
19663
19664                 /* Implement bpf_get_func_ret inline. */
19665                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19666                     insn->imm == BPF_FUNC_get_func_ret) {
19667                         if (eatype == BPF_TRACE_FEXIT ||
19668                             eatype == BPF_MODIFY_RETURN) {
19669                                 /* Load nr_args from ctx - 8 */
19670                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19671                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
19672                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
19673                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
19674                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
19675                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
19676                                 cnt = 6;
19677                         } else {
19678                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
19679                                 cnt = 1;
19680                         }
19681
19682                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
19683                         if (!new_prog)
19684                                 return -ENOMEM;
19685
19686                         delta    += cnt - 1;
19687                         env->prog = prog = new_prog;
19688                         insn      = new_prog->insnsi + i + delta;
19689                         continue;
19690                 }
19691
19692                 /* Implement get_func_arg_cnt inline. */
19693                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19694                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
19695                         /* Load nr_args from ctx - 8 */
19696                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
19697
19698                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19699                         if (!new_prog)
19700                                 return -ENOMEM;
19701
19702                         env->prog = prog = new_prog;
19703                         insn      = new_prog->insnsi + i + delta;
19704                         continue;
19705                 }
19706
19707                 /* Implement bpf_get_func_ip inline. */
19708                 if (prog_type == BPF_PROG_TYPE_TRACING &&
19709                     insn->imm == BPF_FUNC_get_func_ip) {
19710                         /* Load IP address from ctx - 16 */
19711                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
19712
19713                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
19714                         if (!new_prog)
19715                                 return -ENOMEM;
19716
19717                         env->prog = prog = new_prog;
19718                         insn      = new_prog->insnsi + i + delta;
19719                         continue;
19720                 }
19721
19722 patch_call_imm:
19723                 fn = env->ops->get_func_proto(insn->imm, env->prog);
19724                 /* all functions that have prototype and verifier allowed
19725                  * programs to call them, must be real in-kernel functions
19726                  */
19727                 if (!fn->func) {
19728                         verbose(env,
19729                                 "kernel subsystem misconfigured func %s#%d\n",
19730                                 func_id_name(insn->imm), insn->imm);
19731                         return -EFAULT;
19732                 }
19733                 insn->imm = fn->func - __bpf_call_base;
19734         }
19735
19736         /* Since poke tab is now finalized, publish aux to tracker. */
19737         for (i = 0; i < prog->aux->size_poke_tab; i++) {
19738                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
19739                 if (!map_ptr->ops->map_poke_track ||
19740                     !map_ptr->ops->map_poke_untrack ||
19741                     !map_ptr->ops->map_poke_run) {
19742                         verbose(env, "bpf verifier is misconfigured\n");
19743                         return -EINVAL;
19744                 }
19745
19746                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
19747                 if (ret < 0) {
19748                         verbose(env, "tracking tail call prog failed\n");
19749                         return ret;
19750                 }
19751         }
19752
19753         sort_kfunc_descs_by_imm_off(env->prog);
19754
19755         return 0;
19756 }
19757
19758 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
19759                                         int position,
19760                                         s32 stack_base,
19761                                         u32 callback_subprogno,
19762                                         u32 *cnt)
19763 {
19764         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
19765         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
19766         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
19767         int reg_loop_max = BPF_REG_6;
19768         int reg_loop_cnt = BPF_REG_7;
19769         int reg_loop_ctx = BPF_REG_8;
19770
19771         struct bpf_prog *new_prog;
19772         u32 callback_start;
19773         u32 call_insn_offset;
19774         s32 callback_offset;
19775
19776         /* This represents an inlined version of bpf_iter.c:bpf_loop,
19777          * be careful to modify this code in sync.
19778          */
19779         struct bpf_insn insn_buf[] = {
19780                 /* Return error and jump to the end of the patch if
19781                  * expected number of iterations is too big.
19782                  */
19783                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
19784                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
19785                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
19786                 /* spill R6, R7, R8 to use these as loop vars */
19787                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
19788                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
19789                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
19790                 /* initialize loop vars */
19791                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
19792                 BPF_MOV32_IMM(reg_loop_cnt, 0),
19793                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
19794                 /* loop header,
19795                  * if reg_loop_cnt >= reg_loop_max skip the loop body
19796                  */
19797                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
19798                 /* callback call,
19799                  * correct callback offset would be set after patching
19800                  */
19801                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
19802                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
19803                 BPF_CALL_REL(0),
19804                 /* increment loop counter */
19805                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
19806                 /* jump to loop header if callback returned 0 */
19807                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
19808                 /* return value of bpf_loop,
19809                  * set R0 to the number of iterations
19810                  */
19811                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
19812                 /* restore original values of R6, R7, R8 */
19813                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
19814                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
19815                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
19816         };
19817
19818         *cnt = ARRAY_SIZE(insn_buf);
19819         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
19820         if (!new_prog)
19821                 return new_prog;
19822
19823         /* callback start is known only after patching */
19824         callback_start = env->subprog_info[callback_subprogno].start;
19825         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
19826         call_insn_offset = position + 12;
19827         callback_offset = callback_start - call_insn_offset - 1;
19828         new_prog->insnsi[call_insn_offset].imm = callback_offset;
19829
19830         return new_prog;
19831 }
19832
19833 static bool is_bpf_loop_call(struct bpf_insn *insn)
19834 {
19835         return insn->code == (BPF_JMP | BPF_CALL) &&
19836                 insn->src_reg == 0 &&
19837                 insn->imm == BPF_FUNC_loop;
19838 }
19839
19840 /* For all sub-programs in the program (including main) check
19841  * insn_aux_data to see if there are bpf_loop calls that require
19842  * inlining. If such calls are found the calls are replaced with a
19843  * sequence of instructions produced by `inline_bpf_loop` function and
19844  * subprog stack_depth is increased by the size of 3 registers.
19845  * This stack space is used to spill values of the R6, R7, R8.  These
19846  * registers are used to store the loop bound, counter and context
19847  * variables.
19848  */
19849 static int optimize_bpf_loop(struct bpf_verifier_env *env)
19850 {
19851         struct bpf_subprog_info *subprogs = env->subprog_info;
19852         int i, cur_subprog = 0, cnt, delta = 0;
19853         struct bpf_insn *insn = env->prog->insnsi;
19854         int insn_cnt = env->prog->len;
19855         u16 stack_depth = subprogs[cur_subprog].stack_depth;
19856         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19857         u16 stack_depth_extra = 0;
19858
19859         for (i = 0; i < insn_cnt; i++, insn++) {
19860                 struct bpf_loop_inline_state *inline_state =
19861                         &env->insn_aux_data[i + delta].loop_inline_state;
19862
19863                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19864                         struct bpf_prog *new_prog;
19865
19866                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19867                         new_prog = inline_bpf_loop(env,
19868                                                    i + delta,
19869                                                    -(stack_depth + stack_depth_extra),
19870                                                    inline_state->callback_subprogno,
19871                                                    &cnt);
19872                         if (!new_prog)
19873                                 return -ENOMEM;
19874
19875                         delta     += cnt - 1;
19876                         env->prog  = new_prog;
19877                         insn       = new_prog->insnsi + i + delta;
19878                 }
19879
19880                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19881                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
19882                         cur_subprog++;
19883                         stack_depth = subprogs[cur_subprog].stack_depth;
19884                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19885                         stack_depth_extra = 0;
19886                 }
19887         }
19888
19889         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19890
19891         return 0;
19892 }
19893
19894 static void free_states(struct bpf_verifier_env *env)
19895 {
19896         struct bpf_verifier_state_list *sl, *sln;
19897         int i;
19898
19899         sl = env->free_list;
19900         while (sl) {
19901                 sln = sl->next;
19902                 free_verifier_state(&sl->state, false);
19903                 kfree(sl);
19904                 sl = sln;
19905         }
19906         env->free_list = NULL;
19907
19908         if (!env->explored_states)
19909                 return;
19910
19911         for (i = 0; i < state_htab_size(env); i++) {
19912                 sl = env->explored_states[i];
19913
19914                 while (sl) {
19915                         sln = sl->next;
19916                         free_verifier_state(&sl->state, false);
19917                         kfree(sl);
19918                         sl = sln;
19919                 }
19920                 env->explored_states[i] = NULL;
19921         }
19922 }
19923
19924 static int do_check_common(struct bpf_verifier_env *env, int subprog, bool is_ex_cb)
19925 {
19926         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19927         struct bpf_verifier_state *state;
19928         struct bpf_reg_state *regs;
19929         int ret, i;
19930
19931         env->prev_linfo = NULL;
19932         env->pass_cnt++;
19933
19934         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19935         if (!state)
19936                 return -ENOMEM;
19937         state->curframe = 0;
19938         state->speculative = false;
19939         state->branches = 1;
19940         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19941         if (!state->frame[0]) {
19942                 kfree(state);
19943                 return -ENOMEM;
19944         }
19945         env->cur_state = state;
19946         init_func_state(env, state->frame[0],
19947                         BPF_MAIN_FUNC /* callsite */,
19948                         0 /* frameno */,
19949                         subprog);
19950         state->first_insn_idx = env->subprog_info[subprog].start;
19951         state->last_insn_idx = -1;
19952
19953         regs = state->frame[state->curframe]->regs;
19954         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19955                 ret = btf_prepare_func_args(env, subprog, regs, is_ex_cb);
19956                 if (ret)
19957                         goto out;
19958                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19959                         if (regs[i].type == PTR_TO_CTX)
19960                                 mark_reg_known_zero(env, regs, i);
19961                         else if (regs[i].type == SCALAR_VALUE)
19962                                 mark_reg_unknown(env, regs, i);
19963                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19964                                 const u32 mem_size = regs[i].mem_size;
19965
19966                                 mark_reg_known_zero(env, regs, i);
19967                                 regs[i].mem_size = mem_size;
19968                                 regs[i].id = ++env->id_gen;
19969                         }
19970                 }
19971                 if (is_ex_cb) {
19972                         state->frame[0]->in_exception_callback_fn = true;
19973                         env->subprog_info[subprog].is_cb = true;
19974                         env->subprog_info[subprog].is_async_cb = true;
19975                         env->subprog_info[subprog].is_exception_cb = true;
19976                 }
19977         } else {
19978                 /* 1st arg to a function */
19979                 regs[BPF_REG_1].type = PTR_TO_CTX;
19980                 mark_reg_known_zero(env, regs, BPF_REG_1);
19981                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19982                 if (ret == -EFAULT)
19983                         /* unlikely verifier bug. abort.
19984                          * ret == 0 and ret < 0 are sadly acceptable for
19985                          * main() function due to backward compatibility.
19986                          * Like socket filter program may be written as:
19987                          * int bpf_prog(struct pt_regs *ctx)
19988                          * and never dereference that ctx in the program.
19989                          * 'struct pt_regs' is a type mismatch for socket
19990                          * filter that should be using 'struct __sk_buff'.
19991                          */
19992                         goto out;
19993         }
19994
19995         ret = do_check(env);
19996 out:
19997         /* check for NULL is necessary, since cur_state can be freed inside
19998          * do_check() under memory pressure.
19999          */
20000         if (env->cur_state) {
20001                 free_verifier_state(env->cur_state, true);
20002                 env->cur_state = NULL;
20003         }
20004         while (!pop_stack(env, NULL, NULL, false));
20005         if (!ret && pop_log)
20006                 bpf_vlog_reset(&env->log, 0);
20007         free_states(env);
20008         return ret;
20009 }
20010
20011 /* Verify all global functions in a BPF program one by one based on their BTF.
20012  * All global functions must pass verification. Otherwise the whole program is rejected.
20013  * Consider:
20014  * int bar(int);
20015  * int foo(int f)
20016  * {
20017  *    return bar(f);
20018  * }
20019  * int bar(int b)
20020  * {
20021  *    ...
20022  * }
20023  * foo() will be verified first for R1=any_scalar_value. During verification it
20024  * will be assumed that bar() already verified successfully and call to bar()
20025  * from foo() will be checked for type match only. Later bar() will be verified
20026  * independently to check that it's safe for R1=any_scalar_value.
20027  */
20028 static int do_check_subprogs(struct bpf_verifier_env *env)
20029 {
20030         struct bpf_prog_aux *aux = env->prog->aux;
20031         int i, ret;
20032
20033         if (!aux->func_info)
20034                 return 0;
20035
20036         for (i = 1; i < env->subprog_cnt; i++) {
20037                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
20038                         continue;
20039                 env->insn_idx = env->subprog_info[i].start;
20040                 WARN_ON_ONCE(env->insn_idx == 0);
20041                 ret = do_check_common(env, i, env->exception_callback_subprog == i);
20042                 if (ret) {
20043                         return ret;
20044                 } else if (env->log.level & BPF_LOG_LEVEL) {
20045                         verbose(env,
20046                                 "Func#%d is safe for any args that match its prototype\n",
20047                                 i);
20048                 }
20049         }
20050         return 0;
20051 }
20052
20053 static int do_check_main(struct bpf_verifier_env *env)
20054 {
20055         int ret;
20056
20057         env->insn_idx = 0;
20058         ret = do_check_common(env, 0, false);
20059         if (!ret)
20060                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
20061         return ret;
20062 }
20063
20064
20065 static void print_verification_stats(struct bpf_verifier_env *env)
20066 {
20067         int i;
20068
20069         if (env->log.level & BPF_LOG_STATS) {
20070                 verbose(env, "verification time %lld usec\n",
20071                         div_u64(env->verification_time, 1000));
20072                 verbose(env, "stack depth ");
20073                 for (i = 0; i < env->subprog_cnt; i++) {
20074                         u32 depth = env->subprog_info[i].stack_depth;
20075
20076                         verbose(env, "%d", depth);
20077                         if (i + 1 < env->subprog_cnt)
20078                                 verbose(env, "+");
20079                 }
20080                 verbose(env, "\n");
20081         }
20082         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
20083                 "total_states %d peak_states %d mark_read %d\n",
20084                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
20085                 env->max_states_per_insn, env->total_states,
20086                 env->peak_states, env->longest_mark_read_walk);
20087 }
20088
20089 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
20090 {
20091         const struct btf_type *t, *func_proto;
20092         const struct bpf_struct_ops *st_ops;
20093         const struct btf_member *member;
20094         struct bpf_prog *prog = env->prog;
20095         u32 btf_id, member_idx;
20096         const char *mname;
20097
20098         if (!prog->gpl_compatible) {
20099                 verbose(env, "struct ops programs must have a GPL compatible license\n");
20100                 return -EINVAL;
20101         }
20102
20103         btf_id = prog->aux->attach_btf_id;
20104         st_ops = bpf_struct_ops_find(btf_id);
20105         if (!st_ops) {
20106                 verbose(env, "attach_btf_id %u is not a supported struct\n",
20107                         btf_id);
20108                 return -ENOTSUPP;
20109         }
20110
20111         t = st_ops->type;
20112         member_idx = prog->expected_attach_type;
20113         if (member_idx >= btf_type_vlen(t)) {
20114                 verbose(env, "attach to invalid member idx %u of struct %s\n",
20115                         member_idx, st_ops->name);
20116                 return -EINVAL;
20117         }
20118
20119         member = &btf_type_member(t)[member_idx];
20120         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
20121         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
20122                                                NULL);
20123         if (!func_proto) {
20124                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
20125                         mname, member_idx, st_ops->name);
20126                 return -EINVAL;
20127         }
20128
20129         if (st_ops->check_member) {
20130                 int err = st_ops->check_member(t, member, prog);
20131
20132                 if (err) {
20133                         verbose(env, "attach to unsupported member %s of struct %s\n",
20134                                 mname, st_ops->name);
20135                         return err;
20136                 }
20137         }
20138
20139         prog->aux->attach_func_proto = func_proto;
20140         prog->aux->attach_func_name = mname;
20141         env->ops = st_ops->verifier_ops;
20142
20143         return 0;
20144 }
20145 #define SECURITY_PREFIX "security_"
20146
20147 static int check_attach_modify_return(unsigned long addr, const char *func_name)
20148 {
20149         if (within_error_injection_list(addr) ||
20150             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
20151                 return 0;
20152
20153         return -EINVAL;
20154 }
20155
20156 /* list of non-sleepable functions that are otherwise on
20157  * ALLOW_ERROR_INJECTION list
20158  */
20159 BTF_SET_START(btf_non_sleepable_error_inject)
20160 /* Three functions below can be called from sleepable and non-sleepable context.
20161  * Assume non-sleepable from bpf safety point of view.
20162  */
20163 BTF_ID(func, __filemap_add_folio)
20164 BTF_ID(func, should_fail_alloc_page)
20165 BTF_ID(func, should_failslab)
20166 BTF_SET_END(btf_non_sleepable_error_inject)
20167
20168 static int check_non_sleepable_error_inject(u32 btf_id)
20169 {
20170         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
20171 }
20172
20173 int bpf_check_attach_target(struct bpf_verifier_log *log,
20174                             const struct bpf_prog *prog,
20175                             const struct bpf_prog *tgt_prog,
20176                             u32 btf_id,
20177                             struct bpf_attach_target_info *tgt_info)
20178 {
20179         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
20180         const char prefix[] = "btf_trace_";
20181         int ret = 0, subprog = -1, i;
20182         const struct btf_type *t;
20183         bool conservative = true;
20184         const char *tname;
20185         struct btf *btf;
20186         long addr = 0;
20187         struct module *mod = NULL;
20188
20189         if (!btf_id) {
20190                 bpf_log(log, "Tracing programs must provide btf_id\n");
20191                 return -EINVAL;
20192         }
20193         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
20194         if (!btf) {
20195                 bpf_log(log,
20196                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
20197                 return -EINVAL;
20198         }
20199         t = btf_type_by_id(btf, btf_id);
20200         if (!t) {
20201                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
20202                 return -EINVAL;
20203         }
20204         tname = btf_name_by_offset(btf, t->name_off);
20205         if (!tname) {
20206                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
20207                 return -EINVAL;
20208         }
20209         if (tgt_prog) {
20210                 struct bpf_prog_aux *aux = tgt_prog->aux;
20211
20212                 if (bpf_prog_is_dev_bound(prog->aux) &&
20213                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
20214                         bpf_log(log, "Target program bound device mismatch");
20215                         return -EINVAL;
20216                 }
20217
20218                 for (i = 0; i < aux->func_info_cnt; i++)
20219                         if (aux->func_info[i].type_id == btf_id) {
20220                                 subprog = i;
20221                                 break;
20222                         }
20223                 if (subprog == -1) {
20224                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
20225                         return -EINVAL;
20226                 }
20227                 if (aux->func && aux->func[subprog]->aux->exception_cb) {
20228                         bpf_log(log,
20229                                 "%s programs cannot attach to exception callback\n",
20230                                 prog_extension ? "Extension" : "FENTRY/FEXIT");
20231                         return -EINVAL;
20232                 }
20233                 conservative = aux->func_info_aux[subprog].unreliable;
20234                 if (prog_extension) {
20235                         if (conservative) {
20236                                 bpf_log(log,
20237                                         "Cannot replace static functions\n");
20238                                 return -EINVAL;
20239                         }
20240                         if (!prog->jit_requested) {
20241                                 bpf_log(log,
20242                                         "Extension programs should be JITed\n");
20243                                 return -EINVAL;
20244                         }
20245                 }
20246                 if (!tgt_prog->jited) {
20247                         bpf_log(log, "Can attach to only JITed progs\n");
20248                         return -EINVAL;
20249                 }
20250                 if (tgt_prog->type == prog->type) {
20251                         /* Cannot fentry/fexit another fentry/fexit program.
20252                          * Cannot attach program extension to another extension.
20253                          * It's ok to attach fentry/fexit to extension program.
20254                          */
20255                         bpf_log(log, "Cannot recursively attach\n");
20256                         return -EINVAL;
20257                 }
20258                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
20259                     prog_extension &&
20260                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
20261                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
20262                         /* Program extensions can extend all program types
20263                          * except fentry/fexit. The reason is the following.
20264                          * The fentry/fexit programs are used for performance
20265                          * analysis, stats and can be attached to any program
20266                          * type except themselves. When extension program is
20267                          * replacing XDP function it is necessary to allow
20268                          * performance analysis of all functions. Both original
20269                          * XDP program and its program extension. Hence
20270                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
20271                          * allowed. If extending of fentry/fexit was allowed it
20272                          * would be possible to create long call chain
20273                          * fentry->extension->fentry->extension beyond
20274                          * reasonable stack size. Hence extending fentry is not
20275                          * allowed.
20276                          */
20277                         bpf_log(log, "Cannot extend fentry/fexit\n");
20278                         return -EINVAL;
20279                 }
20280         } else {
20281                 if (prog_extension) {
20282                         bpf_log(log, "Cannot replace kernel functions\n");
20283                         return -EINVAL;
20284                 }
20285         }
20286
20287         switch (prog->expected_attach_type) {
20288         case BPF_TRACE_RAW_TP:
20289                 if (tgt_prog) {
20290                         bpf_log(log,
20291                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
20292                         return -EINVAL;
20293                 }
20294                 if (!btf_type_is_typedef(t)) {
20295                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
20296                                 btf_id);
20297                         return -EINVAL;
20298                 }
20299                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
20300                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
20301                                 btf_id, tname);
20302                         return -EINVAL;
20303                 }
20304                 tname += sizeof(prefix) - 1;
20305                 t = btf_type_by_id(btf, t->type);
20306                 if (!btf_type_is_ptr(t))
20307                         /* should never happen in valid vmlinux build */
20308                         return -EINVAL;
20309                 t = btf_type_by_id(btf, t->type);
20310                 if (!btf_type_is_func_proto(t))
20311                         /* should never happen in valid vmlinux build */
20312                         return -EINVAL;
20313
20314                 break;
20315         case BPF_TRACE_ITER:
20316                 if (!btf_type_is_func(t)) {
20317                         bpf_log(log, "attach_btf_id %u is not a function\n",
20318                                 btf_id);
20319                         return -EINVAL;
20320                 }
20321                 t = btf_type_by_id(btf, t->type);
20322                 if (!btf_type_is_func_proto(t))
20323                         return -EINVAL;
20324                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20325                 if (ret)
20326                         return ret;
20327                 break;
20328         default:
20329                 if (!prog_extension)
20330                         return -EINVAL;
20331                 fallthrough;
20332         case BPF_MODIFY_RETURN:
20333         case BPF_LSM_MAC:
20334         case BPF_LSM_CGROUP:
20335         case BPF_TRACE_FENTRY:
20336         case BPF_TRACE_FEXIT:
20337                 if (!btf_type_is_func(t)) {
20338                         bpf_log(log, "attach_btf_id %u is not a function\n",
20339                                 btf_id);
20340                         return -EINVAL;
20341                 }
20342                 if (prog_extension &&
20343                     btf_check_type_match(log, prog, btf, t))
20344                         return -EINVAL;
20345                 t = btf_type_by_id(btf, t->type);
20346                 if (!btf_type_is_func_proto(t))
20347                         return -EINVAL;
20348
20349                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
20350                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
20351                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
20352                         return -EINVAL;
20353
20354                 if (tgt_prog && conservative)
20355                         t = NULL;
20356
20357                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
20358                 if (ret < 0)
20359                         return ret;
20360
20361                 if (tgt_prog) {
20362                         if (subprog == 0)
20363                                 addr = (long) tgt_prog->bpf_func;
20364                         else
20365                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
20366                 } else {
20367                         if (btf_is_module(btf)) {
20368                                 mod = btf_try_get_module(btf);
20369                                 if (mod)
20370                                         addr = find_kallsyms_symbol_value(mod, tname);
20371                                 else
20372                                         addr = 0;
20373                         } else {
20374                                 addr = kallsyms_lookup_name(tname);
20375                         }
20376                         if (!addr) {
20377                                 module_put(mod);
20378                                 bpf_log(log,
20379                                         "The address of function %s cannot be found\n",
20380                                         tname);
20381                                 return -ENOENT;
20382                         }
20383                 }
20384
20385                 if (prog->aux->sleepable) {
20386                         ret = -EINVAL;
20387                         switch (prog->type) {
20388                         case BPF_PROG_TYPE_TRACING:
20389
20390                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
20391                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
20392                                  */
20393                                 if (!check_non_sleepable_error_inject(btf_id) &&
20394                                     within_error_injection_list(addr))
20395                                         ret = 0;
20396                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
20397                                  * in the fmodret id set with the KF_SLEEPABLE flag.
20398                                  */
20399                                 else {
20400                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
20401                                                                                 prog);
20402
20403                                         if (flags && (*flags & KF_SLEEPABLE))
20404                                                 ret = 0;
20405                                 }
20406                                 break;
20407                         case BPF_PROG_TYPE_LSM:
20408                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
20409                                  * Only some of them are sleepable.
20410                                  */
20411                                 if (bpf_lsm_is_sleepable_hook(btf_id))
20412                                         ret = 0;
20413                                 break;
20414                         default:
20415                                 break;
20416                         }
20417                         if (ret) {
20418                                 module_put(mod);
20419                                 bpf_log(log, "%s is not sleepable\n", tname);
20420                                 return ret;
20421                         }
20422                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
20423                         if (tgt_prog) {
20424                                 module_put(mod);
20425                                 bpf_log(log, "can't modify return codes of BPF programs\n");
20426                                 return -EINVAL;
20427                         }
20428                         ret = -EINVAL;
20429                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
20430                             !check_attach_modify_return(addr, tname))
20431                                 ret = 0;
20432                         if (ret) {
20433                                 module_put(mod);
20434                                 bpf_log(log, "%s() is not modifiable\n", tname);
20435                                 return ret;
20436                         }
20437                 }
20438
20439                 break;
20440         }
20441         tgt_info->tgt_addr = addr;
20442         tgt_info->tgt_name = tname;
20443         tgt_info->tgt_type = t;
20444         tgt_info->tgt_mod = mod;
20445         return 0;
20446 }
20447
20448 BTF_SET_START(btf_id_deny)
20449 BTF_ID_UNUSED
20450 #ifdef CONFIG_SMP
20451 BTF_ID(func, migrate_disable)
20452 BTF_ID(func, migrate_enable)
20453 #endif
20454 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
20455 BTF_ID(func, rcu_read_unlock_strict)
20456 #endif
20457 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
20458 BTF_ID(func, preempt_count_add)
20459 BTF_ID(func, preempt_count_sub)
20460 #endif
20461 #ifdef CONFIG_PREEMPT_RCU
20462 BTF_ID(func, __rcu_read_lock)
20463 BTF_ID(func, __rcu_read_unlock)
20464 #endif
20465 BTF_SET_END(btf_id_deny)
20466
20467 static bool can_be_sleepable(struct bpf_prog *prog)
20468 {
20469         if (prog->type == BPF_PROG_TYPE_TRACING) {
20470                 switch (prog->expected_attach_type) {
20471                 case BPF_TRACE_FENTRY:
20472                 case BPF_TRACE_FEXIT:
20473                 case BPF_MODIFY_RETURN:
20474                 case BPF_TRACE_ITER:
20475                         return true;
20476                 default:
20477                         return false;
20478                 }
20479         }
20480         return prog->type == BPF_PROG_TYPE_LSM ||
20481                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
20482                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
20483 }
20484
20485 static int check_attach_btf_id(struct bpf_verifier_env *env)
20486 {
20487         struct bpf_prog *prog = env->prog;
20488         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
20489         struct bpf_attach_target_info tgt_info = {};
20490         u32 btf_id = prog->aux->attach_btf_id;
20491         struct bpf_trampoline *tr;
20492         int ret;
20493         u64 key;
20494
20495         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
20496                 if (prog->aux->sleepable)
20497                         /* attach_btf_id checked to be zero already */
20498                         return 0;
20499                 verbose(env, "Syscall programs can only be sleepable\n");
20500                 return -EINVAL;
20501         }
20502
20503         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
20504                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
20505                 return -EINVAL;
20506         }
20507
20508         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
20509                 return check_struct_ops_btf_id(env);
20510
20511         if (prog->type != BPF_PROG_TYPE_TRACING &&
20512             prog->type != BPF_PROG_TYPE_LSM &&
20513             prog->type != BPF_PROG_TYPE_EXT)
20514                 return 0;
20515
20516         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
20517         if (ret)
20518                 return ret;
20519
20520         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
20521                 /* to make freplace equivalent to their targets, they need to
20522                  * inherit env->ops and expected_attach_type for the rest of the
20523                  * verification
20524                  */
20525                 env->ops = bpf_verifier_ops[tgt_prog->type];
20526                 prog->expected_attach_type = tgt_prog->expected_attach_type;
20527         }
20528
20529         /* store info about the attachment target that will be used later */
20530         prog->aux->attach_func_proto = tgt_info.tgt_type;
20531         prog->aux->attach_func_name = tgt_info.tgt_name;
20532         prog->aux->mod = tgt_info.tgt_mod;
20533
20534         if (tgt_prog) {
20535                 prog->aux->saved_dst_prog_type = tgt_prog->type;
20536                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
20537         }
20538
20539         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
20540                 prog->aux->attach_btf_trace = true;
20541                 return 0;
20542         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
20543                 if (!bpf_iter_prog_supported(prog))
20544                         return -EINVAL;
20545                 return 0;
20546         }
20547
20548         if (prog->type == BPF_PROG_TYPE_LSM) {
20549                 ret = bpf_lsm_verify_prog(&env->log, prog);
20550                 if (ret < 0)
20551                         return ret;
20552         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
20553                    btf_id_set_contains(&btf_id_deny, btf_id)) {
20554                 return -EINVAL;
20555         }
20556
20557         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
20558         tr = bpf_trampoline_get(key, &tgt_info);
20559         if (!tr)
20560                 return -ENOMEM;
20561
20562         if (tgt_prog && tgt_prog->aux->tail_call_reachable)
20563                 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
20564
20565         prog->aux->dst_trampoline = tr;
20566         return 0;
20567 }
20568
20569 struct btf *bpf_get_btf_vmlinux(void)
20570 {
20571         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
20572                 mutex_lock(&bpf_verifier_lock);
20573                 if (!btf_vmlinux)
20574                         btf_vmlinux = btf_parse_vmlinux();
20575                 mutex_unlock(&bpf_verifier_lock);
20576         }
20577         return btf_vmlinux;
20578 }
20579
20580 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
20581 {
20582         u64 start_time = ktime_get_ns();
20583         struct bpf_verifier_env *env;
20584         int i, len, ret = -EINVAL, err;
20585         u32 log_true_size;
20586         bool is_priv;
20587
20588         /* no program is valid */
20589         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
20590                 return -EINVAL;
20591
20592         /* 'struct bpf_verifier_env' can be global, but since it's not small,
20593          * allocate/free it every time bpf_check() is called
20594          */
20595         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
20596         if (!env)
20597                 return -ENOMEM;
20598
20599         env->bt.env = env;
20600
20601         len = (*prog)->len;
20602         env->insn_aux_data =
20603                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
20604         ret = -ENOMEM;
20605         if (!env->insn_aux_data)
20606                 goto err_free_env;
20607         for (i = 0; i < len; i++)
20608                 env->insn_aux_data[i].orig_idx = i;
20609         env->prog = *prog;
20610         env->ops = bpf_verifier_ops[env->prog->type];
20611         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
20612         is_priv = bpf_capable();
20613
20614         bpf_get_btf_vmlinux();
20615
20616         /* grab the mutex to protect few globals used by verifier */
20617         if (!is_priv)
20618                 mutex_lock(&bpf_verifier_lock);
20619
20620         /* user could have requested verbose verifier output
20621          * and supplied buffer to store the verification trace
20622          */
20623         ret = bpf_vlog_init(&env->log, attr->log_level,
20624                             (char __user *) (unsigned long) attr->log_buf,
20625                             attr->log_size);
20626         if (ret)
20627                 goto err_unlock;
20628
20629         mark_verifier_state_clean(env);
20630
20631         if (IS_ERR(btf_vmlinux)) {
20632                 /* Either gcc or pahole or kernel are broken. */
20633                 verbose(env, "in-kernel BTF is malformed\n");
20634                 ret = PTR_ERR(btf_vmlinux);
20635                 goto skip_full_check;
20636         }
20637
20638         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
20639         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
20640                 env->strict_alignment = true;
20641         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
20642                 env->strict_alignment = false;
20643
20644         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
20645         env->allow_uninit_stack = bpf_allow_uninit_stack();
20646         env->bypass_spec_v1 = bpf_bypass_spec_v1();
20647         env->bypass_spec_v4 = bpf_bypass_spec_v4();
20648         env->bpf_capable = bpf_capable();
20649
20650         if (is_priv)
20651                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
20652
20653         env->explored_states = kvcalloc(state_htab_size(env),
20654                                        sizeof(struct bpf_verifier_state_list *),
20655                                        GFP_USER);
20656         ret = -ENOMEM;
20657         if (!env->explored_states)
20658                 goto skip_full_check;
20659
20660         ret = check_btf_info_early(env, attr, uattr);
20661         if (ret < 0)
20662                 goto skip_full_check;
20663
20664         ret = add_subprog_and_kfunc(env);
20665         if (ret < 0)
20666                 goto skip_full_check;
20667
20668         ret = check_subprogs(env);
20669         if (ret < 0)
20670                 goto skip_full_check;
20671
20672         ret = check_btf_info(env, attr, uattr);
20673         if (ret < 0)
20674                 goto skip_full_check;
20675
20676         ret = check_attach_btf_id(env);
20677         if (ret)
20678                 goto skip_full_check;
20679
20680         ret = resolve_pseudo_ldimm64(env);
20681         if (ret < 0)
20682                 goto skip_full_check;
20683
20684         if (bpf_prog_is_offloaded(env->prog->aux)) {
20685                 ret = bpf_prog_offload_verifier_prep(env->prog);
20686                 if (ret)
20687                         goto skip_full_check;
20688         }
20689
20690         ret = check_cfg(env);
20691         if (ret < 0)
20692                 goto skip_full_check;
20693
20694         ret = do_check_subprogs(env);
20695         ret = ret ?: do_check_main(env);
20696
20697         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
20698                 ret = bpf_prog_offload_finalize(env);
20699
20700 skip_full_check:
20701         kvfree(env->explored_states);
20702
20703         if (ret == 0)
20704                 ret = check_max_stack_depth(env);
20705
20706         /* instruction rewrites happen after this point */
20707         if (ret == 0)
20708                 ret = optimize_bpf_loop(env);
20709
20710         if (is_priv) {
20711                 if (ret == 0)
20712                         opt_hard_wire_dead_code_branches(env);
20713                 if (ret == 0)
20714                         ret = opt_remove_dead_code(env);
20715                 if (ret == 0)
20716                         ret = opt_remove_nops(env);
20717         } else {
20718                 if (ret == 0)
20719                         sanitize_dead_code(env);
20720         }
20721
20722         if (ret == 0)
20723                 /* program is valid, convert *(u32*)(ctx + off) accesses */
20724                 ret = convert_ctx_accesses(env);
20725
20726         if (ret == 0)
20727                 ret = do_misc_fixups(env);
20728
20729         /* do 32-bit optimization after insn patching has done so those patched
20730          * insns could be handled correctly.
20731          */
20732         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
20733                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
20734                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
20735                                                                      : false;
20736         }
20737
20738         if (ret == 0)
20739                 ret = fixup_call_args(env);
20740
20741         env->verification_time = ktime_get_ns() - start_time;
20742         print_verification_stats(env);
20743         env->prog->aux->verified_insns = env->insn_processed;
20744
20745         /* preserve original error even if log finalization is successful */
20746         err = bpf_vlog_finalize(&env->log, &log_true_size);
20747         if (err)
20748                 ret = err;
20749
20750         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
20751             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
20752                                   &log_true_size, sizeof(log_true_size))) {
20753                 ret = -EFAULT;
20754                 goto err_release_maps;
20755         }
20756
20757         if (ret)
20758                 goto err_release_maps;
20759
20760         if (env->used_map_cnt) {
20761                 /* if program passed verifier, update used_maps in bpf_prog_info */
20762                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
20763                                                           sizeof(env->used_maps[0]),
20764                                                           GFP_KERNEL);
20765
20766                 if (!env->prog->aux->used_maps) {
20767                         ret = -ENOMEM;
20768                         goto err_release_maps;
20769                 }
20770
20771                 memcpy(env->prog->aux->used_maps, env->used_maps,
20772                        sizeof(env->used_maps[0]) * env->used_map_cnt);
20773                 env->prog->aux->used_map_cnt = env->used_map_cnt;
20774         }
20775         if (env->used_btf_cnt) {
20776                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
20777                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
20778                                                           sizeof(env->used_btfs[0]),
20779                                                           GFP_KERNEL);
20780                 if (!env->prog->aux->used_btfs) {
20781                         ret = -ENOMEM;
20782                         goto err_release_maps;
20783                 }
20784
20785                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
20786                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
20787                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
20788         }
20789         if (env->used_map_cnt || env->used_btf_cnt) {
20790                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
20791                  * bpf_ld_imm64 instructions
20792                  */
20793                 convert_pseudo_ld_imm64(env);
20794         }
20795
20796         adjust_btf_func(env);
20797
20798 err_release_maps:
20799         if (!env->prog->aux->used_maps)
20800                 /* if we didn't copy map pointers into bpf_prog_info, release
20801                  * them now. Otherwise free_used_maps() will release them.
20802                  */
20803                 release_maps(env);
20804         if (!env->prog->aux->used_btfs)
20805                 release_btfs(env);
20806
20807         /* extension progs temporarily inherit the attach_type of their targets
20808            for verification purposes, so set it back to zero before returning
20809          */
20810         if (env->prog->type == BPF_PROG_TYPE_EXT)
20811                 env->prog->expected_attach_type = 0;
20812
20813         *prog = env->prog;
20814 err_unlock:
20815         if (!is_priv)
20816                 mutex_unlock(&bpf_verifier_lock);
20817         vfree(env->insn_aux_data);
20818 err_free_env:
20819         kfree(env);
20820         return ret;
20821 }