bpf: Support new 32bit offset jmp instruction
[platform/kernel/linux-rpi.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
30 #include "disasm.h"
31
32 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
33 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
34         [_id] = & _name ## _verifier_ops,
35 #define BPF_MAP_TYPE(_id, _ops)
36 #define BPF_LINK_TYPE(_id, _name)
37 #include <linux/bpf_types.h>
38 #undef BPF_PROG_TYPE
39 #undef BPF_MAP_TYPE
40 #undef BPF_LINK_TYPE
41 };
42
43 /* bpf_check() is a static code analyzer that walks eBPF program
44  * instruction by instruction and updates register/stack state.
45  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
46  *
47  * The first pass is depth-first-search to check that the program is a DAG.
48  * It rejects the following programs:
49  * - larger than BPF_MAXINSNS insns
50  * - if loop is present (detected via back-edge)
51  * - unreachable insns exist (shouldn't be a forest. program = one function)
52  * - out of bounds or malformed jumps
53  * The second pass is all possible path descent from the 1st insn.
54  * Since it's analyzing all paths through the program, the length of the
55  * analysis is limited to 64k insn, which may be hit even if total number of
56  * insn is less then 4K, but there are too many branches that change stack/regs.
57  * Number of 'branches to be analyzed' is limited to 1k
58  *
59  * On entry to each instruction, each register has a type, and the instruction
60  * changes the types of the registers depending on instruction semantics.
61  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
62  * copied to R1.
63  *
64  * All registers are 64-bit.
65  * R0 - return register
66  * R1-R5 argument passing registers
67  * R6-R9 callee saved registers
68  * R10 - frame pointer read-only
69  *
70  * At the start of BPF program the register R1 contains a pointer to bpf_context
71  * and has type PTR_TO_CTX.
72  *
73  * Verifier tracks arithmetic operations on pointers in case:
74  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
75  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
76  * 1st insn copies R10 (which has FRAME_PTR) type into R1
77  * and 2nd arithmetic instruction is pattern matched to recognize
78  * that it wants to construct a pointer to some element within stack.
79  * So after 2nd insn, the register R1 has type PTR_TO_STACK
80  * (and -20 constant is saved for further stack bounds checking).
81  * Meaning that this reg is a pointer to stack plus known immediate constant.
82  *
83  * Most of the time the registers have SCALAR_VALUE type, which
84  * means the register has some value, but it's not a valid pointer.
85  * (like pointer plus pointer becomes SCALAR_VALUE type)
86  *
87  * When verifier sees load or store instructions the type of base register
88  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
89  * four pointer types recognized by check_mem_access() function.
90  *
91  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
92  * and the range of [ptr, ptr + map's value_size) is accessible.
93  *
94  * registers used to pass values to function calls are checked against
95  * function argument constraints.
96  *
97  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
98  * It means that the register type passed to this function must be
99  * PTR_TO_STACK and it will be used inside the function as
100  * 'pointer to map element key'
101  *
102  * For example the argument constraints for bpf_map_lookup_elem():
103  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
104  *   .arg1_type = ARG_CONST_MAP_PTR,
105  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
106  *
107  * ret_type says that this function returns 'pointer to map elem value or null'
108  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
109  * 2nd argument should be a pointer to stack, which will be used inside
110  * the helper function as a pointer to map element key.
111  *
112  * On the kernel side the helper function looks like:
113  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
114  * {
115  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
116  *    void *key = (void *) (unsigned long) r2;
117  *    void *value;
118  *
119  *    here kernel can access 'key' and 'map' pointers safely, knowing that
120  *    [key, key + map->key_size) bytes are valid and were initialized on
121  *    the stack of eBPF program.
122  * }
123  *
124  * Corresponding eBPF program may look like:
125  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
126  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
127  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
128  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
129  * here verifier looks at prototype of map_lookup_elem() and sees:
130  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
131  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
132  *
133  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
134  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
135  * and were initialized prior to this call.
136  * If it's ok, then verifier allows this BPF_CALL insn and looks at
137  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
138  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
139  * returns either pointer to map value or NULL.
140  *
141  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
142  * insn, the register holding that pointer in the true branch changes state to
143  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
144  * branch. See check_cond_jmp_op().
145  *
146  * After the call R0 is set to return type of the function and registers R1-R5
147  * are set to NOT_INIT to indicate that they are no longer readable.
148  *
149  * The following reference types represent a potential reference to a kernel
150  * resource which, after first being allocated, must be checked and freed by
151  * the BPF program:
152  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
153  *
154  * When the verifier sees a helper call return a reference type, it allocates a
155  * pointer id for the reference and stores it in the current function state.
156  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
157  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
158  * passes through a NULL-check conditional. For the branch wherein the state is
159  * changed to CONST_IMM, the verifier releases the reference.
160  *
161  * For each helper function that allocates a reference, such as
162  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
163  * bpf_sk_release(). When a reference type passes into the release function,
164  * the verifier also releases the reference. If any unchecked or unreleased
165  * reference remains at the end of the program, the verifier rejects it.
166  */
167
168 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
169 struct bpf_verifier_stack_elem {
170         /* verifer state is 'st'
171          * before processing instruction 'insn_idx'
172          * and after processing instruction 'prev_insn_idx'
173          */
174         struct bpf_verifier_state st;
175         int insn_idx;
176         int prev_insn_idx;
177         struct bpf_verifier_stack_elem *next;
178         /* length of verifier log at the time this state was pushed on stack */
179         u32 log_pos;
180 };
181
182 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
183 #define BPF_COMPLEXITY_LIMIT_STATES     64
184
185 #define BPF_MAP_KEY_POISON      (1ULL << 63)
186 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
187
188 #define BPF_MAP_PTR_UNPRIV      1UL
189 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
190                                           POISON_POINTER_DELTA))
191 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
192
193 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
194 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
195 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
196 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
197 static int ref_set_non_owning(struct bpf_verifier_env *env,
198                               struct bpf_reg_state *reg);
199 static void specialize_kfunc(struct bpf_verifier_env *env,
200                              u32 func_id, u16 offset, unsigned long *addr);
201 static bool is_trusted_reg(const struct bpf_reg_state *reg);
202
203 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
204 {
205         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
206 }
207
208 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
209 {
210         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
211 }
212
213 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
214                               const struct bpf_map *map, bool unpriv)
215 {
216         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
217         unpriv |= bpf_map_ptr_unpriv(aux);
218         aux->map_ptr_state = (unsigned long)map |
219                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
220 }
221
222 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
223 {
224         return aux->map_key_state & BPF_MAP_KEY_POISON;
225 }
226
227 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
228 {
229         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
230 }
231
232 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
233 {
234         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
235 }
236
237 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
238 {
239         bool poisoned = bpf_map_key_poisoned(aux);
240
241         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
242                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
243 }
244
245 static bool bpf_helper_call(const struct bpf_insn *insn)
246 {
247         return insn->code == (BPF_JMP | BPF_CALL) &&
248                insn->src_reg == 0;
249 }
250
251 static bool bpf_pseudo_call(const struct bpf_insn *insn)
252 {
253         return insn->code == (BPF_JMP | BPF_CALL) &&
254                insn->src_reg == BPF_PSEUDO_CALL;
255 }
256
257 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
258 {
259         return insn->code == (BPF_JMP | BPF_CALL) &&
260                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
261 }
262
263 struct bpf_call_arg_meta {
264         struct bpf_map *map_ptr;
265         bool raw_mode;
266         bool pkt_access;
267         u8 release_regno;
268         int regno;
269         int access_size;
270         int mem_size;
271         u64 msize_max_value;
272         int ref_obj_id;
273         int dynptr_id;
274         int map_uid;
275         int func_id;
276         struct btf *btf;
277         u32 btf_id;
278         struct btf *ret_btf;
279         u32 ret_btf_id;
280         u32 subprogno;
281         struct btf_field *kptr_field;
282 };
283
284 struct bpf_kfunc_call_arg_meta {
285         /* In parameters */
286         struct btf *btf;
287         u32 func_id;
288         u32 kfunc_flags;
289         const struct btf_type *func_proto;
290         const char *func_name;
291         /* Out parameters */
292         u32 ref_obj_id;
293         u8 release_regno;
294         bool r0_rdonly;
295         u32 ret_btf_id;
296         u64 r0_size;
297         u32 subprogno;
298         struct {
299                 u64 value;
300                 bool found;
301         } arg_constant;
302
303         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
304          * generally to pass info about user-defined local kptr types to later
305          * verification logic
306          *   bpf_obj_drop
307          *     Record the local kptr type to be drop'd
308          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
309          *     Record the local kptr type to be refcount_incr'd and use
310          *     arg_owning_ref to determine whether refcount_acquire should be
311          *     fallible
312          */
313         struct btf *arg_btf;
314         u32 arg_btf_id;
315         bool arg_owning_ref;
316
317         struct {
318                 struct btf_field *field;
319         } arg_list_head;
320         struct {
321                 struct btf_field *field;
322         } arg_rbtree_root;
323         struct {
324                 enum bpf_dynptr_type type;
325                 u32 id;
326                 u32 ref_obj_id;
327         } initialized_dynptr;
328         struct {
329                 u8 spi;
330                 u8 frameno;
331         } iter;
332         u64 mem_size;
333 };
334
335 struct btf *btf_vmlinux;
336
337 static DEFINE_MUTEX(bpf_verifier_lock);
338
339 static const struct bpf_line_info *
340 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
341 {
342         const struct bpf_line_info *linfo;
343         const struct bpf_prog *prog;
344         u32 i, nr_linfo;
345
346         prog = env->prog;
347         nr_linfo = prog->aux->nr_linfo;
348
349         if (!nr_linfo || insn_off >= prog->len)
350                 return NULL;
351
352         linfo = prog->aux->linfo;
353         for (i = 1; i < nr_linfo; i++)
354                 if (insn_off < linfo[i].insn_off)
355                         break;
356
357         return &linfo[i - 1];
358 }
359
360 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
361 {
362         struct bpf_verifier_env *env = private_data;
363         va_list args;
364
365         if (!bpf_verifier_log_needed(&env->log))
366                 return;
367
368         va_start(args, fmt);
369         bpf_verifier_vlog(&env->log, fmt, args);
370         va_end(args);
371 }
372
373 static const char *ltrim(const char *s)
374 {
375         while (isspace(*s))
376                 s++;
377
378         return s;
379 }
380
381 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
382                                          u32 insn_off,
383                                          const char *prefix_fmt, ...)
384 {
385         const struct bpf_line_info *linfo;
386
387         if (!bpf_verifier_log_needed(&env->log))
388                 return;
389
390         linfo = find_linfo(env, insn_off);
391         if (!linfo || linfo == env->prev_linfo)
392                 return;
393
394         if (prefix_fmt) {
395                 va_list args;
396
397                 va_start(args, prefix_fmt);
398                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
399                 va_end(args);
400         }
401
402         verbose(env, "%s\n",
403                 ltrim(btf_name_by_offset(env->prog->aux->btf,
404                                          linfo->line_off)));
405
406         env->prev_linfo = linfo;
407 }
408
409 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
410                                    struct bpf_reg_state *reg,
411                                    struct tnum *range, const char *ctx,
412                                    const char *reg_name)
413 {
414         char tn_buf[48];
415
416         verbose(env, "At %s the register %s ", ctx, reg_name);
417         if (!tnum_is_unknown(reg->var_off)) {
418                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
419                 verbose(env, "has value %s", tn_buf);
420         } else {
421                 verbose(env, "has unknown scalar value");
422         }
423         tnum_strn(tn_buf, sizeof(tn_buf), *range);
424         verbose(env, " should have been in %s\n", tn_buf);
425 }
426
427 static bool type_is_pkt_pointer(enum bpf_reg_type type)
428 {
429         type = base_type(type);
430         return type == PTR_TO_PACKET ||
431                type == PTR_TO_PACKET_META;
432 }
433
434 static bool type_is_sk_pointer(enum bpf_reg_type type)
435 {
436         return type == PTR_TO_SOCKET ||
437                 type == PTR_TO_SOCK_COMMON ||
438                 type == PTR_TO_TCP_SOCK ||
439                 type == PTR_TO_XDP_SOCK;
440 }
441
442 static bool type_may_be_null(u32 type)
443 {
444         return type & PTR_MAYBE_NULL;
445 }
446
447 static bool reg_not_null(const struct bpf_reg_state *reg)
448 {
449         enum bpf_reg_type type;
450
451         type = reg->type;
452         if (type_may_be_null(type))
453                 return false;
454
455         type = base_type(type);
456         return type == PTR_TO_SOCKET ||
457                 type == PTR_TO_TCP_SOCK ||
458                 type == PTR_TO_MAP_VALUE ||
459                 type == PTR_TO_MAP_KEY ||
460                 type == PTR_TO_SOCK_COMMON ||
461                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
462                 type == PTR_TO_MEM;
463 }
464
465 static bool type_is_ptr_alloc_obj(u32 type)
466 {
467         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
468 }
469
470 static bool type_is_non_owning_ref(u32 type)
471 {
472         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
473 }
474
475 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
476 {
477         struct btf_record *rec = NULL;
478         struct btf_struct_meta *meta;
479
480         if (reg->type == PTR_TO_MAP_VALUE) {
481                 rec = reg->map_ptr->record;
482         } else if (type_is_ptr_alloc_obj(reg->type)) {
483                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
484                 if (meta)
485                         rec = meta->record;
486         }
487         return rec;
488 }
489
490 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
491 {
492         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
493
494         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
495 }
496
497 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
498 {
499         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
500 }
501
502 static bool type_is_rdonly_mem(u32 type)
503 {
504         return type & MEM_RDONLY;
505 }
506
507 static bool is_acquire_function(enum bpf_func_id func_id,
508                                 const struct bpf_map *map)
509 {
510         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
511
512         if (func_id == BPF_FUNC_sk_lookup_tcp ||
513             func_id == BPF_FUNC_sk_lookup_udp ||
514             func_id == BPF_FUNC_skc_lookup_tcp ||
515             func_id == BPF_FUNC_ringbuf_reserve ||
516             func_id == BPF_FUNC_kptr_xchg)
517                 return true;
518
519         if (func_id == BPF_FUNC_map_lookup_elem &&
520             (map_type == BPF_MAP_TYPE_SOCKMAP ||
521              map_type == BPF_MAP_TYPE_SOCKHASH))
522                 return true;
523
524         return false;
525 }
526
527 static bool is_ptr_cast_function(enum bpf_func_id func_id)
528 {
529         return func_id == BPF_FUNC_tcp_sock ||
530                 func_id == BPF_FUNC_sk_fullsock ||
531                 func_id == BPF_FUNC_skc_to_tcp_sock ||
532                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
533                 func_id == BPF_FUNC_skc_to_udp6_sock ||
534                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
535                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
537 }
538
539 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
540 {
541         return func_id == BPF_FUNC_dynptr_data;
542 }
543
544 static bool is_callback_calling_kfunc(u32 btf_id);
545
546 static bool is_callback_calling_function(enum bpf_func_id func_id)
547 {
548         return func_id == BPF_FUNC_for_each_map_elem ||
549                func_id == BPF_FUNC_timer_set_callback ||
550                func_id == BPF_FUNC_find_vma ||
551                func_id == BPF_FUNC_loop ||
552                func_id == BPF_FUNC_user_ringbuf_drain;
553 }
554
555 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
556 {
557         return func_id == BPF_FUNC_timer_set_callback;
558 }
559
560 static bool is_storage_get_function(enum bpf_func_id func_id)
561 {
562         return func_id == BPF_FUNC_sk_storage_get ||
563                func_id == BPF_FUNC_inode_storage_get ||
564                func_id == BPF_FUNC_task_storage_get ||
565                func_id == BPF_FUNC_cgrp_storage_get;
566 }
567
568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
569                                         const struct bpf_map *map)
570 {
571         int ref_obj_uses = 0;
572
573         if (is_ptr_cast_function(func_id))
574                 ref_obj_uses++;
575         if (is_acquire_function(func_id, map))
576                 ref_obj_uses++;
577         if (is_dynptr_ref_function(func_id))
578                 ref_obj_uses++;
579
580         return ref_obj_uses > 1;
581 }
582
583 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
584 {
585         return BPF_CLASS(insn->code) == BPF_STX &&
586                BPF_MODE(insn->code) == BPF_ATOMIC &&
587                insn->imm == BPF_CMPXCHG;
588 }
589
590 /* string representation of 'enum bpf_reg_type'
591  *
592  * Note that reg_type_str() can not appear more than once in a single verbose()
593  * statement.
594  */
595 static const char *reg_type_str(struct bpf_verifier_env *env,
596                                 enum bpf_reg_type type)
597 {
598         char postfix[16] = {0}, prefix[64] = {0};
599         static const char * const str[] = {
600                 [NOT_INIT]              = "?",
601                 [SCALAR_VALUE]          = "scalar",
602                 [PTR_TO_CTX]            = "ctx",
603                 [CONST_PTR_TO_MAP]      = "map_ptr",
604                 [PTR_TO_MAP_VALUE]      = "map_value",
605                 [PTR_TO_STACK]          = "fp",
606                 [PTR_TO_PACKET]         = "pkt",
607                 [PTR_TO_PACKET_META]    = "pkt_meta",
608                 [PTR_TO_PACKET_END]     = "pkt_end",
609                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
610                 [PTR_TO_SOCKET]         = "sock",
611                 [PTR_TO_SOCK_COMMON]    = "sock_common",
612                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
613                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
614                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
615                 [PTR_TO_BTF_ID]         = "ptr_",
616                 [PTR_TO_MEM]            = "mem",
617                 [PTR_TO_BUF]            = "buf",
618                 [PTR_TO_FUNC]           = "func",
619                 [PTR_TO_MAP_KEY]        = "map_key",
620                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
621         };
622
623         if (type & PTR_MAYBE_NULL) {
624                 if (base_type(type) == PTR_TO_BTF_ID)
625                         strncpy(postfix, "or_null_", 16);
626                 else
627                         strncpy(postfix, "_or_null", 16);
628         }
629
630         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
631                  type & MEM_RDONLY ? "rdonly_" : "",
632                  type & MEM_RINGBUF ? "ringbuf_" : "",
633                  type & MEM_USER ? "user_" : "",
634                  type & MEM_PERCPU ? "percpu_" : "",
635                  type & MEM_RCU ? "rcu_" : "",
636                  type & PTR_UNTRUSTED ? "untrusted_" : "",
637                  type & PTR_TRUSTED ? "trusted_" : ""
638         );
639
640         snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
641                  prefix, str[base_type(type)], postfix);
642         return env->tmp_str_buf;
643 }
644
645 static char slot_type_char[] = {
646         [STACK_INVALID] = '?',
647         [STACK_SPILL]   = 'r',
648         [STACK_MISC]    = 'm',
649         [STACK_ZERO]    = '0',
650         [STACK_DYNPTR]  = 'd',
651         [STACK_ITER]    = 'i',
652 };
653
654 static void print_liveness(struct bpf_verifier_env *env,
655                            enum bpf_reg_liveness live)
656 {
657         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
658             verbose(env, "_");
659         if (live & REG_LIVE_READ)
660                 verbose(env, "r");
661         if (live & REG_LIVE_WRITTEN)
662                 verbose(env, "w");
663         if (live & REG_LIVE_DONE)
664                 verbose(env, "D");
665 }
666
667 static int __get_spi(s32 off)
668 {
669         return (-off - 1) / BPF_REG_SIZE;
670 }
671
672 static struct bpf_func_state *func(struct bpf_verifier_env *env,
673                                    const struct bpf_reg_state *reg)
674 {
675         struct bpf_verifier_state *cur = env->cur_state;
676
677         return cur->frame[reg->frameno];
678 }
679
680 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
681 {
682        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
683
684        /* We need to check that slots between [spi - nr_slots + 1, spi] are
685         * within [0, allocated_stack).
686         *
687         * Please note that the spi grows downwards. For example, a dynptr
688         * takes the size of two stack slots; the first slot will be at
689         * spi and the second slot will be at spi - 1.
690         */
691        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
692 }
693
694 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
695                                   const char *obj_kind, int nr_slots)
696 {
697         int off, spi;
698
699         if (!tnum_is_const(reg->var_off)) {
700                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
701                 return -EINVAL;
702         }
703
704         off = reg->off + reg->var_off.value;
705         if (off % BPF_REG_SIZE) {
706                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
707                 return -EINVAL;
708         }
709
710         spi = __get_spi(off);
711         if (spi + 1 < nr_slots) {
712                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
713                 return -EINVAL;
714         }
715
716         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
717                 return -ERANGE;
718         return spi;
719 }
720
721 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
722 {
723         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
724 }
725
726 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
727 {
728         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
729 }
730
731 static const char *btf_type_name(const struct btf *btf, u32 id)
732 {
733         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
734 }
735
736 static const char *dynptr_type_str(enum bpf_dynptr_type type)
737 {
738         switch (type) {
739         case BPF_DYNPTR_TYPE_LOCAL:
740                 return "local";
741         case BPF_DYNPTR_TYPE_RINGBUF:
742                 return "ringbuf";
743         case BPF_DYNPTR_TYPE_SKB:
744                 return "skb";
745         case BPF_DYNPTR_TYPE_XDP:
746                 return "xdp";
747         case BPF_DYNPTR_TYPE_INVALID:
748                 return "<invalid>";
749         default:
750                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
751                 return "<unknown>";
752         }
753 }
754
755 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
756 {
757         if (!btf || btf_id == 0)
758                 return "<invalid>";
759
760         /* we already validated that type is valid and has conforming name */
761         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
762 }
763
764 static const char *iter_state_str(enum bpf_iter_state state)
765 {
766         switch (state) {
767         case BPF_ITER_STATE_ACTIVE:
768                 return "active";
769         case BPF_ITER_STATE_DRAINED:
770                 return "drained";
771         case BPF_ITER_STATE_INVALID:
772                 return "<invalid>";
773         default:
774                 WARN_ONCE(1, "unknown iter state %d\n", state);
775                 return "<unknown>";
776         }
777 }
778
779 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
780 {
781         env->scratched_regs |= 1U << regno;
782 }
783
784 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
785 {
786         env->scratched_stack_slots |= 1ULL << spi;
787 }
788
789 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
790 {
791         return (env->scratched_regs >> regno) & 1;
792 }
793
794 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
795 {
796         return (env->scratched_stack_slots >> regno) & 1;
797 }
798
799 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
800 {
801         return env->scratched_regs || env->scratched_stack_slots;
802 }
803
804 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
805 {
806         env->scratched_regs = 0U;
807         env->scratched_stack_slots = 0ULL;
808 }
809
810 /* Used for printing the entire verifier state. */
811 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
812 {
813         env->scratched_regs = ~0U;
814         env->scratched_stack_slots = ~0ULL;
815 }
816
817 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
818 {
819         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
820         case DYNPTR_TYPE_LOCAL:
821                 return BPF_DYNPTR_TYPE_LOCAL;
822         case DYNPTR_TYPE_RINGBUF:
823                 return BPF_DYNPTR_TYPE_RINGBUF;
824         case DYNPTR_TYPE_SKB:
825                 return BPF_DYNPTR_TYPE_SKB;
826         case DYNPTR_TYPE_XDP:
827                 return BPF_DYNPTR_TYPE_XDP;
828         default:
829                 return BPF_DYNPTR_TYPE_INVALID;
830         }
831 }
832
833 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
834 {
835         switch (type) {
836         case BPF_DYNPTR_TYPE_LOCAL:
837                 return DYNPTR_TYPE_LOCAL;
838         case BPF_DYNPTR_TYPE_RINGBUF:
839                 return DYNPTR_TYPE_RINGBUF;
840         case BPF_DYNPTR_TYPE_SKB:
841                 return DYNPTR_TYPE_SKB;
842         case BPF_DYNPTR_TYPE_XDP:
843                 return DYNPTR_TYPE_XDP;
844         default:
845                 return 0;
846         }
847 }
848
849 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
850 {
851         return type == BPF_DYNPTR_TYPE_RINGBUF;
852 }
853
854 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
855                               enum bpf_dynptr_type type,
856                               bool first_slot, int dynptr_id);
857
858 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
859                                 struct bpf_reg_state *reg);
860
861 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
862                                    struct bpf_reg_state *sreg1,
863                                    struct bpf_reg_state *sreg2,
864                                    enum bpf_dynptr_type type)
865 {
866         int id = ++env->id_gen;
867
868         __mark_dynptr_reg(sreg1, type, true, id);
869         __mark_dynptr_reg(sreg2, type, false, id);
870 }
871
872 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
873                                struct bpf_reg_state *reg,
874                                enum bpf_dynptr_type type)
875 {
876         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
877 }
878
879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
880                                         struct bpf_func_state *state, int spi);
881
882 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
883                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
884 {
885         struct bpf_func_state *state = func(env, reg);
886         enum bpf_dynptr_type type;
887         int spi, i, err;
888
889         spi = dynptr_get_spi(env, reg);
890         if (spi < 0)
891                 return spi;
892
893         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
894          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
895          * to ensure that for the following example:
896          *      [d1][d1][d2][d2]
897          * spi    3   2   1   0
898          * So marking spi = 2 should lead to destruction of both d1 and d2. In
899          * case they do belong to same dynptr, second call won't see slot_type
900          * as STACK_DYNPTR and will simply skip destruction.
901          */
902         err = destroy_if_dynptr_stack_slot(env, state, spi);
903         if (err)
904                 return err;
905         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
906         if (err)
907                 return err;
908
909         for (i = 0; i < BPF_REG_SIZE; i++) {
910                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
911                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
912         }
913
914         type = arg_to_dynptr_type(arg_type);
915         if (type == BPF_DYNPTR_TYPE_INVALID)
916                 return -EINVAL;
917
918         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
919                                &state->stack[spi - 1].spilled_ptr, type);
920
921         if (dynptr_type_refcounted(type)) {
922                 /* The id is used to track proper releasing */
923                 int id;
924
925                 if (clone_ref_obj_id)
926                         id = clone_ref_obj_id;
927                 else
928                         id = acquire_reference_state(env, insn_idx);
929
930                 if (id < 0)
931                         return id;
932
933                 state->stack[spi].spilled_ptr.ref_obj_id = id;
934                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
935         }
936
937         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
938         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
939
940         return 0;
941 }
942
943 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
944 {
945         int i;
946
947         for (i = 0; i < BPF_REG_SIZE; i++) {
948                 state->stack[spi].slot_type[i] = STACK_INVALID;
949                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
950         }
951
952         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
953         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
954
955         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
956          *
957          * While we don't allow reading STACK_INVALID, it is still possible to
958          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
959          * helpers or insns can do partial read of that part without failing,
960          * but check_stack_range_initialized, check_stack_read_var_off, and
961          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
962          * the slot conservatively. Hence we need to prevent those liveness
963          * marking walks.
964          *
965          * This was not a problem before because STACK_INVALID is only set by
966          * default (where the default reg state has its reg->parent as NULL), or
967          * in clean_live_states after REG_LIVE_DONE (at which point
968          * mark_reg_read won't walk reg->parent chain), but not randomly during
969          * verifier state exploration (like we did above). Hence, for our case
970          * parentage chain will still be live (i.e. reg->parent may be
971          * non-NULL), while earlier reg->parent was NULL, so we need
972          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
973          * done later on reads or by mark_dynptr_read as well to unnecessary
974          * mark registers in verifier state.
975          */
976         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
977         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
978 }
979
980 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
981 {
982         struct bpf_func_state *state = func(env, reg);
983         int spi, ref_obj_id, i;
984
985         spi = dynptr_get_spi(env, reg);
986         if (spi < 0)
987                 return spi;
988
989         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
990                 invalidate_dynptr(env, state, spi);
991                 return 0;
992         }
993
994         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
995
996         /* If the dynptr has a ref_obj_id, then we need to invalidate
997          * two things:
998          *
999          * 1) Any dynptrs with a matching ref_obj_id (clones)
1000          * 2) Any slices derived from this dynptr.
1001          */
1002
1003         /* Invalidate any slices associated with this dynptr */
1004         WARN_ON_ONCE(release_reference(env, ref_obj_id));
1005
1006         /* Invalidate any dynptr clones */
1007         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1008                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1009                         continue;
1010
1011                 /* it should always be the case that if the ref obj id
1012                  * matches then the stack slot also belongs to a
1013                  * dynptr
1014                  */
1015                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1016                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1017                         return -EFAULT;
1018                 }
1019                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1020                         invalidate_dynptr(env, state, i);
1021         }
1022
1023         return 0;
1024 }
1025
1026 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1027                                struct bpf_reg_state *reg);
1028
1029 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1030 {
1031         if (!env->allow_ptr_leaks)
1032                 __mark_reg_not_init(env, reg);
1033         else
1034                 __mark_reg_unknown(env, reg);
1035 }
1036
1037 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1038                                         struct bpf_func_state *state, int spi)
1039 {
1040         struct bpf_func_state *fstate;
1041         struct bpf_reg_state *dreg;
1042         int i, dynptr_id;
1043
1044         /* We always ensure that STACK_DYNPTR is never set partially,
1045          * hence just checking for slot_type[0] is enough. This is
1046          * different for STACK_SPILL, where it may be only set for
1047          * 1 byte, so code has to use is_spilled_reg.
1048          */
1049         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1050                 return 0;
1051
1052         /* Reposition spi to first slot */
1053         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1054                 spi = spi + 1;
1055
1056         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1057                 verbose(env, "cannot overwrite referenced dynptr\n");
1058                 return -EINVAL;
1059         }
1060
1061         mark_stack_slot_scratched(env, spi);
1062         mark_stack_slot_scratched(env, spi - 1);
1063
1064         /* Writing partially to one dynptr stack slot destroys both. */
1065         for (i = 0; i < BPF_REG_SIZE; i++) {
1066                 state->stack[spi].slot_type[i] = STACK_INVALID;
1067                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1068         }
1069
1070         dynptr_id = state->stack[spi].spilled_ptr.id;
1071         /* Invalidate any slices associated with this dynptr */
1072         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1073                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1074                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1075                         continue;
1076                 if (dreg->dynptr_id == dynptr_id)
1077                         mark_reg_invalid(env, dreg);
1078         }));
1079
1080         /* Do not release reference state, we are destroying dynptr on stack,
1081          * not using some helper to release it. Just reset register.
1082          */
1083         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1084         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1085
1086         /* Same reason as unmark_stack_slots_dynptr above */
1087         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1088         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089
1090         return 0;
1091 }
1092
1093 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1094 {
1095         int spi;
1096
1097         if (reg->type == CONST_PTR_TO_DYNPTR)
1098                 return false;
1099
1100         spi = dynptr_get_spi(env, reg);
1101
1102         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1103          * error because this just means the stack state hasn't been updated yet.
1104          * We will do check_mem_access to check and update stack bounds later.
1105          */
1106         if (spi < 0 && spi != -ERANGE)
1107                 return false;
1108
1109         /* We don't need to check if the stack slots are marked by previous
1110          * dynptr initializations because we allow overwriting existing unreferenced
1111          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1112          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1113          * touching are completely destructed before we reinitialize them for a new
1114          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1115          * instead of delaying it until the end where the user will get "Unreleased
1116          * reference" error.
1117          */
1118         return true;
1119 }
1120
1121 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1122 {
1123         struct bpf_func_state *state = func(env, reg);
1124         int i, spi;
1125
1126         /* This already represents first slot of initialized bpf_dynptr.
1127          *
1128          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1129          * check_func_arg_reg_off's logic, so we don't need to check its
1130          * offset and alignment.
1131          */
1132         if (reg->type == CONST_PTR_TO_DYNPTR)
1133                 return true;
1134
1135         spi = dynptr_get_spi(env, reg);
1136         if (spi < 0)
1137                 return false;
1138         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1139                 return false;
1140
1141         for (i = 0; i < BPF_REG_SIZE; i++) {
1142                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1143                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1144                         return false;
1145         }
1146
1147         return true;
1148 }
1149
1150 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1151                                     enum bpf_arg_type arg_type)
1152 {
1153         struct bpf_func_state *state = func(env, reg);
1154         enum bpf_dynptr_type dynptr_type;
1155         int spi;
1156
1157         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1158         if (arg_type == ARG_PTR_TO_DYNPTR)
1159                 return true;
1160
1161         dynptr_type = arg_to_dynptr_type(arg_type);
1162         if (reg->type == CONST_PTR_TO_DYNPTR) {
1163                 return reg->dynptr.type == dynptr_type;
1164         } else {
1165                 spi = dynptr_get_spi(env, reg);
1166                 if (spi < 0)
1167                         return false;
1168                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1169         }
1170 }
1171
1172 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1173
1174 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1175                                  struct bpf_reg_state *reg, int insn_idx,
1176                                  struct btf *btf, u32 btf_id, int nr_slots)
1177 {
1178         struct bpf_func_state *state = func(env, reg);
1179         int spi, i, j, id;
1180
1181         spi = iter_get_spi(env, reg, nr_slots);
1182         if (spi < 0)
1183                 return spi;
1184
1185         id = acquire_reference_state(env, insn_idx);
1186         if (id < 0)
1187                 return id;
1188
1189         for (i = 0; i < nr_slots; i++) {
1190                 struct bpf_stack_state *slot = &state->stack[spi - i];
1191                 struct bpf_reg_state *st = &slot->spilled_ptr;
1192
1193                 __mark_reg_known_zero(st);
1194                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1195                 st->live |= REG_LIVE_WRITTEN;
1196                 st->ref_obj_id = i == 0 ? id : 0;
1197                 st->iter.btf = btf;
1198                 st->iter.btf_id = btf_id;
1199                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1200                 st->iter.depth = 0;
1201
1202                 for (j = 0; j < BPF_REG_SIZE; j++)
1203                         slot->slot_type[j] = STACK_ITER;
1204
1205                 mark_stack_slot_scratched(env, spi - i);
1206         }
1207
1208         return 0;
1209 }
1210
1211 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1212                                    struct bpf_reg_state *reg, int nr_slots)
1213 {
1214         struct bpf_func_state *state = func(env, reg);
1215         int spi, i, j;
1216
1217         spi = iter_get_spi(env, reg, nr_slots);
1218         if (spi < 0)
1219                 return spi;
1220
1221         for (i = 0; i < nr_slots; i++) {
1222                 struct bpf_stack_state *slot = &state->stack[spi - i];
1223                 struct bpf_reg_state *st = &slot->spilled_ptr;
1224
1225                 if (i == 0)
1226                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1227
1228                 __mark_reg_not_init(env, st);
1229
1230                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1231                 st->live |= REG_LIVE_WRITTEN;
1232
1233                 for (j = 0; j < BPF_REG_SIZE; j++)
1234                         slot->slot_type[j] = STACK_INVALID;
1235
1236                 mark_stack_slot_scratched(env, spi - i);
1237         }
1238
1239         return 0;
1240 }
1241
1242 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1243                                      struct bpf_reg_state *reg, int nr_slots)
1244 {
1245         struct bpf_func_state *state = func(env, reg);
1246         int spi, i, j;
1247
1248         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1249          * will do check_mem_access to check and update stack bounds later, so
1250          * return true for that case.
1251          */
1252         spi = iter_get_spi(env, reg, nr_slots);
1253         if (spi == -ERANGE)
1254                 return true;
1255         if (spi < 0)
1256                 return false;
1257
1258         for (i = 0; i < nr_slots; i++) {
1259                 struct bpf_stack_state *slot = &state->stack[spi - i];
1260
1261                 for (j = 0; j < BPF_REG_SIZE; j++)
1262                         if (slot->slot_type[j] == STACK_ITER)
1263                                 return false;
1264         }
1265
1266         return true;
1267 }
1268
1269 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1270                                    struct btf *btf, u32 btf_id, int nr_slots)
1271 {
1272         struct bpf_func_state *state = func(env, reg);
1273         int spi, i, j;
1274
1275         spi = iter_get_spi(env, reg, nr_slots);
1276         if (spi < 0)
1277                 return false;
1278
1279         for (i = 0; i < nr_slots; i++) {
1280                 struct bpf_stack_state *slot = &state->stack[spi - i];
1281                 struct bpf_reg_state *st = &slot->spilled_ptr;
1282
1283                 /* only main (first) slot has ref_obj_id set */
1284                 if (i == 0 && !st->ref_obj_id)
1285                         return false;
1286                 if (i != 0 && st->ref_obj_id)
1287                         return false;
1288                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1289                         return false;
1290
1291                 for (j = 0; j < BPF_REG_SIZE; j++)
1292                         if (slot->slot_type[j] != STACK_ITER)
1293                                 return false;
1294         }
1295
1296         return true;
1297 }
1298
1299 /* Check if given stack slot is "special":
1300  *   - spilled register state (STACK_SPILL);
1301  *   - dynptr state (STACK_DYNPTR);
1302  *   - iter state (STACK_ITER).
1303  */
1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1305 {
1306         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1307
1308         switch (type) {
1309         case STACK_SPILL:
1310         case STACK_DYNPTR:
1311         case STACK_ITER:
1312                 return true;
1313         case STACK_INVALID:
1314         case STACK_MISC:
1315         case STACK_ZERO:
1316                 return false;
1317         default:
1318                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1319                 return true;
1320         }
1321 }
1322
1323 /* The reg state of a pointer or a bounded scalar was saved when
1324  * it was spilled to the stack.
1325  */
1326 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1327 {
1328         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1329 }
1330
1331 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1332 {
1333         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1334                stack->spilled_ptr.type == SCALAR_VALUE;
1335 }
1336
1337 static void scrub_spilled_slot(u8 *stype)
1338 {
1339         if (*stype != STACK_INVALID)
1340                 *stype = STACK_MISC;
1341 }
1342
1343 static void print_verifier_state(struct bpf_verifier_env *env,
1344                                  const struct bpf_func_state *state,
1345                                  bool print_all)
1346 {
1347         const struct bpf_reg_state *reg;
1348         enum bpf_reg_type t;
1349         int i;
1350
1351         if (state->frameno)
1352                 verbose(env, " frame%d:", state->frameno);
1353         for (i = 0; i < MAX_BPF_REG; i++) {
1354                 reg = &state->regs[i];
1355                 t = reg->type;
1356                 if (t == NOT_INIT)
1357                         continue;
1358                 if (!print_all && !reg_scratched(env, i))
1359                         continue;
1360                 verbose(env, " R%d", i);
1361                 print_liveness(env, reg->live);
1362                 verbose(env, "=");
1363                 if (t == SCALAR_VALUE && reg->precise)
1364                         verbose(env, "P");
1365                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1366                     tnum_is_const(reg->var_off)) {
1367                         /* reg->off should be 0 for SCALAR_VALUE */
1368                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1369                         verbose(env, "%lld", reg->var_off.value + reg->off);
1370                 } else {
1371                         const char *sep = "";
1372
1373                         verbose(env, "%s", reg_type_str(env, t));
1374                         if (base_type(t) == PTR_TO_BTF_ID)
1375                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1376                         verbose(env, "(");
1377 /*
1378  * _a stands for append, was shortened to avoid multiline statements below.
1379  * This macro is used to output a comma separated list of attributes.
1380  */
1381 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1382
1383                         if (reg->id)
1384                                 verbose_a("id=%d", reg->id);
1385                         if (reg->ref_obj_id)
1386                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1387                         if (type_is_non_owning_ref(reg->type))
1388                                 verbose_a("%s", "non_own_ref");
1389                         if (t != SCALAR_VALUE)
1390                                 verbose_a("off=%d", reg->off);
1391                         if (type_is_pkt_pointer(t))
1392                                 verbose_a("r=%d", reg->range);
1393                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1394                                  base_type(t) == PTR_TO_MAP_KEY ||
1395                                  base_type(t) == PTR_TO_MAP_VALUE)
1396                                 verbose_a("ks=%d,vs=%d",
1397                                           reg->map_ptr->key_size,
1398                                           reg->map_ptr->value_size);
1399                         if (tnum_is_const(reg->var_off)) {
1400                                 /* Typically an immediate SCALAR_VALUE, but
1401                                  * could be a pointer whose offset is too big
1402                                  * for reg->off
1403                                  */
1404                                 verbose_a("imm=%llx", reg->var_off.value);
1405                         } else {
1406                                 if (reg->smin_value != reg->umin_value &&
1407                                     reg->smin_value != S64_MIN)
1408                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1409                                 if (reg->smax_value != reg->umax_value &&
1410                                     reg->smax_value != S64_MAX)
1411                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1412                                 if (reg->umin_value != 0)
1413                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1414                                 if (reg->umax_value != U64_MAX)
1415                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1416                                 if (!tnum_is_unknown(reg->var_off)) {
1417                                         char tn_buf[48];
1418
1419                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1420                                         verbose_a("var_off=%s", tn_buf);
1421                                 }
1422                                 if (reg->s32_min_value != reg->smin_value &&
1423                                     reg->s32_min_value != S32_MIN)
1424                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1425                                 if (reg->s32_max_value != reg->smax_value &&
1426                                     reg->s32_max_value != S32_MAX)
1427                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1428                                 if (reg->u32_min_value != reg->umin_value &&
1429                                     reg->u32_min_value != U32_MIN)
1430                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1431                                 if (reg->u32_max_value != reg->umax_value &&
1432                                     reg->u32_max_value != U32_MAX)
1433                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1434                         }
1435 #undef verbose_a
1436
1437                         verbose(env, ")");
1438                 }
1439         }
1440         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1441                 char types_buf[BPF_REG_SIZE + 1];
1442                 bool valid = false;
1443                 int j;
1444
1445                 for (j = 0; j < BPF_REG_SIZE; j++) {
1446                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1447                                 valid = true;
1448                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1449                 }
1450                 types_buf[BPF_REG_SIZE] = 0;
1451                 if (!valid)
1452                         continue;
1453                 if (!print_all && !stack_slot_scratched(env, i))
1454                         continue;
1455                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1456                 case STACK_SPILL:
1457                         reg = &state->stack[i].spilled_ptr;
1458                         t = reg->type;
1459
1460                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1461                         print_liveness(env, reg->live);
1462                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1463                         if (t == SCALAR_VALUE && reg->precise)
1464                                 verbose(env, "P");
1465                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1466                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1467                         break;
1468                 case STACK_DYNPTR:
1469                         i += BPF_DYNPTR_NR_SLOTS - 1;
1470                         reg = &state->stack[i].spilled_ptr;
1471
1472                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1473                         print_liveness(env, reg->live);
1474                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1475                         if (reg->ref_obj_id)
1476                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1477                         break;
1478                 case STACK_ITER:
1479                         /* only main slot has ref_obj_id set; skip others */
1480                         reg = &state->stack[i].spilled_ptr;
1481                         if (!reg->ref_obj_id)
1482                                 continue;
1483
1484                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1485                         print_liveness(env, reg->live);
1486                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1487                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1488                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1489                                 reg->iter.depth);
1490                         break;
1491                 case STACK_MISC:
1492                 case STACK_ZERO:
1493                 default:
1494                         reg = &state->stack[i].spilled_ptr;
1495
1496                         for (j = 0; j < BPF_REG_SIZE; j++)
1497                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1498                         types_buf[BPF_REG_SIZE] = 0;
1499
1500                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1501                         print_liveness(env, reg->live);
1502                         verbose(env, "=%s", types_buf);
1503                         break;
1504                 }
1505         }
1506         if (state->acquired_refs && state->refs[0].id) {
1507                 verbose(env, " refs=%d", state->refs[0].id);
1508                 for (i = 1; i < state->acquired_refs; i++)
1509                         if (state->refs[i].id)
1510                                 verbose(env, ",%d", state->refs[i].id);
1511         }
1512         if (state->in_callback_fn)
1513                 verbose(env, " cb");
1514         if (state->in_async_callback_fn)
1515                 verbose(env, " async_cb");
1516         verbose(env, "\n");
1517         mark_verifier_state_clean(env);
1518 }
1519
1520 static inline u32 vlog_alignment(u32 pos)
1521 {
1522         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1523                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1524 }
1525
1526 static void print_insn_state(struct bpf_verifier_env *env,
1527                              const struct bpf_func_state *state)
1528 {
1529         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1530                 /* remove new line character */
1531                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1532                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1533         } else {
1534                 verbose(env, "%d:", env->insn_idx);
1535         }
1536         print_verifier_state(env, state, false);
1537 }
1538
1539 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1540  * small to hold src. This is different from krealloc since we don't want to preserve
1541  * the contents of dst.
1542  *
1543  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1544  * not be allocated.
1545  */
1546 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1547 {
1548         size_t alloc_bytes;
1549         void *orig = dst;
1550         size_t bytes;
1551
1552         if (ZERO_OR_NULL_PTR(src))
1553                 goto out;
1554
1555         if (unlikely(check_mul_overflow(n, size, &bytes)))
1556                 return NULL;
1557
1558         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1559         dst = krealloc(orig, alloc_bytes, flags);
1560         if (!dst) {
1561                 kfree(orig);
1562                 return NULL;
1563         }
1564
1565         memcpy(dst, src, bytes);
1566 out:
1567         return dst ? dst : ZERO_SIZE_PTR;
1568 }
1569
1570 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1571  * small to hold new_n items. new items are zeroed out if the array grows.
1572  *
1573  * Contrary to krealloc_array, does not free arr if new_n is zero.
1574  */
1575 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1576 {
1577         size_t alloc_size;
1578         void *new_arr;
1579
1580         if (!new_n || old_n == new_n)
1581                 goto out;
1582
1583         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1584         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1585         if (!new_arr) {
1586                 kfree(arr);
1587                 return NULL;
1588         }
1589         arr = new_arr;
1590
1591         if (new_n > old_n)
1592                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1593
1594 out:
1595         return arr ? arr : ZERO_SIZE_PTR;
1596 }
1597
1598 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1599 {
1600         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1601                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1602         if (!dst->refs)
1603                 return -ENOMEM;
1604
1605         dst->acquired_refs = src->acquired_refs;
1606         return 0;
1607 }
1608
1609 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1610 {
1611         size_t n = src->allocated_stack / BPF_REG_SIZE;
1612
1613         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1614                                 GFP_KERNEL);
1615         if (!dst->stack)
1616                 return -ENOMEM;
1617
1618         dst->allocated_stack = src->allocated_stack;
1619         return 0;
1620 }
1621
1622 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1623 {
1624         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1625                                     sizeof(struct bpf_reference_state));
1626         if (!state->refs)
1627                 return -ENOMEM;
1628
1629         state->acquired_refs = n;
1630         return 0;
1631 }
1632
1633 static int grow_stack_state(struct bpf_func_state *state, int size)
1634 {
1635         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1636
1637         if (old_n >= n)
1638                 return 0;
1639
1640         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1641         if (!state->stack)
1642                 return -ENOMEM;
1643
1644         state->allocated_stack = size;
1645         return 0;
1646 }
1647
1648 /* Acquire a pointer id from the env and update the state->refs to include
1649  * this new pointer reference.
1650  * On success, returns a valid pointer id to associate with the register
1651  * On failure, returns a negative errno.
1652  */
1653 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1654 {
1655         struct bpf_func_state *state = cur_func(env);
1656         int new_ofs = state->acquired_refs;
1657         int id, err;
1658
1659         err = resize_reference_state(state, state->acquired_refs + 1);
1660         if (err)
1661                 return err;
1662         id = ++env->id_gen;
1663         state->refs[new_ofs].id = id;
1664         state->refs[new_ofs].insn_idx = insn_idx;
1665         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1666
1667         return id;
1668 }
1669
1670 /* release function corresponding to acquire_reference_state(). Idempotent. */
1671 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1672 {
1673         int i, last_idx;
1674
1675         last_idx = state->acquired_refs - 1;
1676         for (i = 0; i < state->acquired_refs; i++) {
1677                 if (state->refs[i].id == ptr_id) {
1678                         /* Cannot release caller references in callbacks */
1679                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1680                                 return -EINVAL;
1681                         if (last_idx && i != last_idx)
1682                                 memcpy(&state->refs[i], &state->refs[last_idx],
1683                                        sizeof(*state->refs));
1684                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1685                         state->acquired_refs--;
1686                         return 0;
1687                 }
1688         }
1689         return -EINVAL;
1690 }
1691
1692 static void free_func_state(struct bpf_func_state *state)
1693 {
1694         if (!state)
1695                 return;
1696         kfree(state->refs);
1697         kfree(state->stack);
1698         kfree(state);
1699 }
1700
1701 static void clear_jmp_history(struct bpf_verifier_state *state)
1702 {
1703         kfree(state->jmp_history);
1704         state->jmp_history = NULL;
1705         state->jmp_history_cnt = 0;
1706 }
1707
1708 static void free_verifier_state(struct bpf_verifier_state *state,
1709                                 bool free_self)
1710 {
1711         int i;
1712
1713         for (i = 0; i <= state->curframe; i++) {
1714                 free_func_state(state->frame[i]);
1715                 state->frame[i] = NULL;
1716         }
1717         clear_jmp_history(state);
1718         if (free_self)
1719                 kfree(state);
1720 }
1721
1722 /* copy verifier state from src to dst growing dst stack space
1723  * when necessary to accommodate larger src stack
1724  */
1725 static int copy_func_state(struct bpf_func_state *dst,
1726                            const struct bpf_func_state *src)
1727 {
1728         int err;
1729
1730         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1731         err = copy_reference_state(dst, src);
1732         if (err)
1733                 return err;
1734         return copy_stack_state(dst, src);
1735 }
1736
1737 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1738                                const struct bpf_verifier_state *src)
1739 {
1740         struct bpf_func_state *dst;
1741         int i, err;
1742
1743         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1744                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1745                                             GFP_USER);
1746         if (!dst_state->jmp_history)
1747                 return -ENOMEM;
1748         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1749
1750         /* if dst has more stack frames then src frame, free them */
1751         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1752                 free_func_state(dst_state->frame[i]);
1753                 dst_state->frame[i] = NULL;
1754         }
1755         dst_state->speculative = src->speculative;
1756         dst_state->active_rcu_lock = src->active_rcu_lock;
1757         dst_state->curframe = src->curframe;
1758         dst_state->active_lock.ptr = src->active_lock.ptr;
1759         dst_state->active_lock.id = src->active_lock.id;
1760         dst_state->branches = src->branches;
1761         dst_state->parent = src->parent;
1762         dst_state->first_insn_idx = src->first_insn_idx;
1763         dst_state->last_insn_idx = src->last_insn_idx;
1764         for (i = 0; i <= src->curframe; i++) {
1765                 dst = dst_state->frame[i];
1766                 if (!dst) {
1767                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1768                         if (!dst)
1769                                 return -ENOMEM;
1770                         dst_state->frame[i] = dst;
1771                 }
1772                 err = copy_func_state(dst, src->frame[i]);
1773                 if (err)
1774                         return err;
1775         }
1776         return 0;
1777 }
1778
1779 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1780 {
1781         while (st) {
1782                 u32 br = --st->branches;
1783
1784                 /* WARN_ON(br > 1) technically makes sense here,
1785                  * but see comment in push_stack(), hence:
1786                  */
1787                 WARN_ONCE((int)br < 0,
1788                           "BUG update_branch_counts:branches_to_explore=%d\n",
1789                           br);
1790                 if (br)
1791                         break;
1792                 st = st->parent;
1793         }
1794 }
1795
1796 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1797                      int *insn_idx, bool pop_log)
1798 {
1799         struct bpf_verifier_state *cur = env->cur_state;
1800         struct bpf_verifier_stack_elem *elem, *head = env->head;
1801         int err;
1802
1803         if (env->head == NULL)
1804                 return -ENOENT;
1805
1806         if (cur) {
1807                 err = copy_verifier_state(cur, &head->st);
1808                 if (err)
1809                         return err;
1810         }
1811         if (pop_log)
1812                 bpf_vlog_reset(&env->log, head->log_pos);
1813         if (insn_idx)
1814                 *insn_idx = head->insn_idx;
1815         if (prev_insn_idx)
1816                 *prev_insn_idx = head->prev_insn_idx;
1817         elem = head->next;
1818         free_verifier_state(&head->st, false);
1819         kfree(head);
1820         env->head = elem;
1821         env->stack_size--;
1822         return 0;
1823 }
1824
1825 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1826                                              int insn_idx, int prev_insn_idx,
1827                                              bool speculative)
1828 {
1829         struct bpf_verifier_state *cur = env->cur_state;
1830         struct bpf_verifier_stack_elem *elem;
1831         int err;
1832
1833         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1834         if (!elem)
1835                 goto err;
1836
1837         elem->insn_idx = insn_idx;
1838         elem->prev_insn_idx = prev_insn_idx;
1839         elem->next = env->head;
1840         elem->log_pos = env->log.end_pos;
1841         env->head = elem;
1842         env->stack_size++;
1843         err = copy_verifier_state(&elem->st, cur);
1844         if (err)
1845                 goto err;
1846         elem->st.speculative |= speculative;
1847         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1848                 verbose(env, "The sequence of %d jumps is too complex.\n",
1849                         env->stack_size);
1850                 goto err;
1851         }
1852         if (elem->st.parent) {
1853                 ++elem->st.parent->branches;
1854                 /* WARN_ON(branches > 2) technically makes sense here,
1855                  * but
1856                  * 1. speculative states will bump 'branches' for non-branch
1857                  * instructions
1858                  * 2. is_state_visited() heuristics may decide not to create
1859                  * a new state for a sequence of branches and all such current
1860                  * and cloned states will be pointing to a single parent state
1861                  * which might have large 'branches' count.
1862                  */
1863         }
1864         return &elem->st;
1865 err:
1866         free_verifier_state(env->cur_state, true);
1867         env->cur_state = NULL;
1868         /* pop all elements and return */
1869         while (!pop_stack(env, NULL, NULL, false));
1870         return NULL;
1871 }
1872
1873 #define CALLER_SAVED_REGS 6
1874 static const int caller_saved[CALLER_SAVED_REGS] = {
1875         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1876 };
1877
1878 /* This helper doesn't clear reg->id */
1879 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1880 {
1881         reg->var_off = tnum_const(imm);
1882         reg->smin_value = (s64)imm;
1883         reg->smax_value = (s64)imm;
1884         reg->umin_value = imm;
1885         reg->umax_value = imm;
1886
1887         reg->s32_min_value = (s32)imm;
1888         reg->s32_max_value = (s32)imm;
1889         reg->u32_min_value = (u32)imm;
1890         reg->u32_max_value = (u32)imm;
1891 }
1892
1893 /* Mark the unknown part of a register (variable offset or scalar value) as
1894  * known to have the value @imm.
1895  */
1896 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1897 {
1898         /* Clear off and union(map_ptr, range) */
1899         memset(((u8 *)reg) + sizeof(reg->type), 0,
1900                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1901         reg->id = 0;
1902         reg->ref_obj_id = 0;
1903         ___mark_reg_known(reg, imm);
1904 }
1905
1906 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1907 {
1908         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1909         reg->s32_min_value = (s32)imm;
1910         reg->s32_max_value = (s32)imm;
1911         reg->u32_min_value = (u32)imm;
1912         reg->u32_max_value = (u32)imm;
1913 }
1914
1915 /* Mark the 'variable offset' part of a register as zero.  This should be
1916  * used only on registers holding a pointer type.
1917  */
1918 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1919 {
1920         __mark_reg_known(reg, 0);
1921 }
1922
1923 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1924 {
1925         __mark_reg_known(reg, 0);
1926         reg->type = SCALAR_VALUE;
1927 }
1928
1929 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1930                                 struct bpf_reg_state *regs, u32 regno)
1931 {
1932         if (WARN_ON(regno >= MAX_BPF_REG)) {
1933                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1934                 /* Something bad happened, let's kill all regs */
1935                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1936                         __mark_reg_not_init(env, regs + regno);
1937                 return;
1938         }
1939         __mark_reg_known_zero(regs + regno);
1940 }
1941
1942 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1943                               bool first_slot, int dynptr_id)
1944 {
1945         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1946          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1947          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1948          */
1949         __mark_reg_known_zero(reg);
1950         reg->type = CONST_PTR_TO_DYNPTR;
1951         /* Give each dynptr a unique id to uniquely associate slices to it. */
1952         reg->id = dynptr_id;
1953         reg->dynptr.type = type;
1954         reg->dynptr.first_slot = first_slot;
1955 }
1956
1957 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1958 {
1959         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1960                 const struct bpf_map *map = reg->map_ptr;
1961
1962                 if (map->inner_map_meta) {
1963                         reg->type = CONST_PTR_TO_MAP;
1964                         reg->map_ptr = map->inner_map_meta;
1965                         /* transfer reg's id which is unique for every map_lookup_elem
1966                          * as UID of the inner map.
1967                          */
1968                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1969                                 reg->map_uid = reg->id;
1970                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1971                         reg->type = PTR_TO_XDP_SOCK;
1972                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1973                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1974                         reg->type = PTR_TO_SOCKET;
1975                 } else {
1976                         reg->type = PTR_TO_MAP_VALUE;
1977                 }
1978                 return;
1979         }
1980
1981         reg->type &= ~PTR_MAYBE_NULL;
1982 }
1983
1984 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1985                                 struct btf_field_graph_root *ds_head)
1986 {
1987         __mark_reg_known_zero(&regs[regno]);
1988         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1989         regs[regno].btf = ds_head->btf;
1990         regs[regno].btf_id = ds_head->value_btf_id;
1991         regs[regno].off = ds_head->node_offset;
1992 }
1993
1994 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1995 {
1996         return type_is_pkt_pointer(reg->type);
1997 }
1998
1999 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2000 {
2001         return reg_is_pkt_pointer(reg) ||
2002                reg->type == PTR_TO_PACKET_END;
2003 }
2004
2005 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2006 {
2007         return base_type(reg->type) == PTR_TO_MEM &&
2008                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2009 }
2010
2011 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2012 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2013                                     enum bpf_reg_type which)
2014 {
2015         /* The register can already have a range from prior markings.
2016          * This is fine as long as it hasn't been advanced from its
2017          * origin.
2018          */
2019         return reg->type == which &&
2020                reg->id == 0 &&
2021                reg->off == 0 &&
2022                tnum_equals_const(reg->var_off, 0);
2023 }
2024
2025 /* Reset the min/max bounds of a register */
2026 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2027 {
2028         reg->smin_value = S64_MIN;
2029         reg->smax_value = S64_MAX;
2030         reg->umin_value = 0;
2031         reg->umax_value = U64_MAX;
2032
2033         reg->s32_min_value = S32_MIN;
2034         reg->s32_max_value = S32_MAX;
2035         reg->u32_min_value = 0;
2036         reg->u32_max_value = U32_MAX;
2037 }
2038
2039 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2040 {
2041         reg->smin_value = S64_MIN;
2042         reg->smax_value = S64_MAX;
2043         reg->umin_value = 0;
2044         reg->umax_value = U64_MAX;
2045 }
2046
2047 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2048 {
2049         reg->s32_min_value = S32_MIN;
2050         reg->s32_max_value = S32_MAX;
2051         reg->u32_min_value = 0;
2052         reg->u32_max_value = U32_MAX;
2053 }
2054
2055 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2056 {
2057         struct tnum var32_off = tnum_subreg(reg->var_off);
2058
2059         /* min signed is max(sign bit) | min(other bits) */
2060         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2061                         var32_off.value | (var32_off.mask & S32_MIN));
2062         /* max signed is min(sign bit) | max(other bits) */
2063         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2064                         var32_off.value | (var32_off.mask & S32_MAX));
2065         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2066         reg->u32_max_value = min(reg->u32_max_value,
2067                                  (u32)(var32_off.value | var32_off.mask));
2068 }
2069
2070 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2071 {
2072         /* min signed is max(sign bit) | min(other bits) */
2073         reg->smin_value = max_t(s64, reg->smin_value,
2074                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2075         /* max signed is min(sign bit) | max(other bits) */
2076         reg->smax_value = min_t(s64, reg->smax_value,
2077                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2078         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2079         reg->umax_value = min(reg->umax_value,
2080                               reg->var_off.value | reg->var_off.mask);
2081 }
2082
2083 static void __update_reg_bounds(struct bpf_reg_state *reg)
2084 {
2085         __update_reg32_bounds(reg);
2086         __update_reg64_bounds(reg);
2087 }
2088
2089 /* Uses signed min/max values to inform unsigned, and vice-versa */
2090 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2091 {
2092         /* Learn sign from signed bounds.
2093          * If we cannot cross the sign boundary, then signed and unsigned bounds
2094          * are the same, so combine.  This works even in the negative case, e.g.
2095          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2096          */
2097         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2098                 reg->s32_min_value = reg->u32_min_value =
2099                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2100                 reg->s32_max_value = reg->u32_max_value =
2101                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2102                 return;
2103         }
2104         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2105          * boundary, so we must be careful.
2106          */
2107         if ((s32)reg->u32_max_value >= 0) {
2108                 /* Positive.  We can't learn anything from the smin, but smax
2109                  * is positive, hence safe.
2110                  */
2111                 reg->s32_min_value = reg->u32_min_value;
2112                 reg->s32_max_value = reg->u32_max_value =
2113                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2114         } else if ((s32)reg->u32_min_value < 0) {
2115                 /* Negative.  We can't learn anything from the smax, but smin
2116                  * is negative, hence safe.
2117                  */
2118                 reg->s32_min_value = reg->u32_min_value =
2119                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2120                 reg->s32_max_value = reg->u32_max_value;
2121         }
2122 }
2123
2124 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2125 {
2126         /* Learn sign from signed bounds.
2127          * If we cannot cross the sign boundary, then signed and unsigned bounds
2128          * are the same, so combine.  This works even in the negative case, e.g.
2129          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2130          */
2131         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2132                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2133                                                           reg->umin_value);
2134                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2135                                                           reg->umax_value);
2136                 return;
2137         }
2138         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2139          * boundary, so we must be careful.
2140          */
2141         if ((s64)reg->umax_value >= 0) {
2142                 /* Positive.  We can't learn anything from the smin, but smax
2143                  * is positive, hence safe.
2144                  */
2145                 reg->smin_value = reg->umin_value;
2146                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2147                                                           reg->umax_value);
2148         } else if ((s64)reg->umin_value < 0) {
2149                 /* Negative.  We can't learn anything from the smax, but smin
2150                  * is negative, hence safe.
2151                  */
2152                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2153                                                           reg->umin_value);
2154                 reg->smax_value = reg->umax_value;
2155         }
2156 }
2157
2158 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2159 {
2160         __reg32_deduce_bounds(reg);
2161         __reg64_deduce_bounds(reg);
2162 }
2163
2164 /* Attempts to improve var_off based on unsigned min/max information */
2165 static void __reg_bound_offset(struct bpf_reg_state *reg)
2166 {
2167         struct tnum var64_off = tnum_intersect(reg->var_off,
2168                                                tnum_range(reg->umin_value,
2169                                                           reg->umax_value));
2170         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2171                                                tnum_range(reg->u32_min_value,
2172                                                           reg->u32_max_value));
2173
2174         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2175 }
2176
2177 static void reg_bounds_sync(struct bpf_reg_state *reg)
2178 {
2179         /* We might have learned new bounds from the var_off. */
2180         __update_reg_bounds(reg);
2181         /* We might have learned something about the sign bit. */
2182         __reg_deduce_bounds(reg);
2183         /* We might have learned some bits from the bounds. */
2184         __reg_bound_offset(reg);
2185         /* Intersecting with the old var_off might have improved our bounds
2186          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2187          * then new var_off is (0; 0x7f...fc) which improves our umax.
2188          */
2189         __update_reg_bounds(reg);
2190 }
2191
2192 static bool __reg32_bound_s64(s32 a)
2193 {
2194         return a >= 0 && a <= S32_MAX;
2195 }
2196
2197 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2198 {
2199         reg->umin_value = reg->u32_min_value;
2200         reg->umax_value = reg->u32_max_value;
2201
2202         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2203          * be positive otherwise set to worse case bounds and refine later
2204          * from tnum.
2205          */
2206         if (__reg32_bound_s64(reg->s32_min_value) &&
2207             __reg32_bound_s64(reg->s32_max_value)) {
2208                 reg->smin_value = reg->s32_min_value;
2209                 reg->smax_value = reg->s32_max_value;
2210         } else {
2211                 reg->smin_value = 0;
2212                 reg->smax_value = U32_MAX;
2213         }
2214 }
2215
2216 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2217 {
2218         /* special case when 64-bit register has upper 32-bit register
2219          * zeroed. Typically happens after zext or <<32, >>32 sequence
2220          * allowing us to use 32-bit bounds directly,
2221          */
2222         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2223                 __reg_assign_32_into_64(reg);
2224         } else {
2225                 /* Otherwise the best we can do is push lower 32bit known and
2226                  * unknown bits into register (var_off set from jmp logic)
2227                  * then learn as much as possible from the 64-bit tnum
2228                  * known and unknown bits. The previous smin/smax bounds are
2229                  * invalid here because of jmp32 compare so mark them unknown
2230                  * so they do not impact tnum bounds calculation.
2231                  */
2232                 __mark_reg64_unbounded(reg);
2233         }
2234         reg_bounds_sync(reg);
2235 }
2236
2237 static bool __reg64_bound_s32(s64 a)
2238 {
2239         return a >= S32_MIN && a <= S32_MAX;
2240 }
2241
2242 static bool __reg64_bound_u32(u64 a)
2243 {
2244         return a >= U32_MIN && a <= U32_MAX;
2245 }
2246
2247 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2248 {
2249         __mark_reg32_unbounded(reg);
2250         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2251                 reg->s32_min_value = (s32)reg->smin_value;
2252                 reg->s32_max_value = (s32)reg->smax_value;
2253         }
2254         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2255                 reg->u32_min_value = (u32)reg->umin_value;
2256                 reg->u32_max_value = (u32)reg->umax_value;
2257         }
2258         reg_bounds_sync(reg);
2259 }
2260
2261 /* Mark a register as having a completely unknown (scalar) value. */
2262 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2263                                struct bpf_reg_state *reg)
2264 {
2265         /*
2266          * Clear type, off, and union(map_ptr, range) and
2267          * padding between 'type' and union
2268          */
2269         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2270         reg->type = SCALAR_VALUE;
2271         reg->id = 0;
2272         reg->ref_obj_id = 0;
2273         reg->var_off = tnum_unknown;
2274         reg->frameno = 0;
2275         reg->precise = !env->bpf_capable;
2276         __mark_reg_unbounded(reg);
2277 }
2278
2279 static void mark_reg_unknown(struct bpf_verifier_env *env,
2280                              struct bpf_reg_state *regs, u32 regno)
2281 {
2282         if (WARN_ON(regno >= MAX_BPF_REG)) {
2283                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2284                 /* Something bad happened, let's kill all regs except FP */
2285                 for (regno = 0; regno < BPF_REG_FP; regno++)
2286                         __mark_reg_not_init(env, regs + regno);
2287                 return;
2288         }
2289         __mark_reg_unknown(env, regs + regno);
2290 }
2291
2292 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2293                                 struct bpf_reg_state *reg)
2294 {
2295         __mark_reg_unknown(env, reg);
2296         reg->type = NOT_INIT;
2297 }
2298
2299 static void mark_reg_not_init(struct bpf_verifier_env *env,
2300                               struct bpf_reg_state *regs, u32 regno)
2301 {
2302         if (WARN_ON(regno >= MAX_BPF_REG)) {
2303                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2304                 /* Something bad happened, let's kill all regs except FP */
2305                 for (regno = 0; regno < BPF_REG_FP; regno++)
2306                         __mark_reg_not_init(env, regs + regno);
2307                 return;
2308         }
2309         __mark_reg_not_init(env, regs + regno);
2310 }
2311
2312 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2313                             struct bpf_reg_state *regs, u32 regno,
2314                             enum bpf_reg_type reg_type,
2315                             struct btf *btf, u32 btf_id,
2316                             enum bpf_type_flag flag)
2317 {
2318         if (reg_type == SCALAR_VALUE) {
2319                 mark_reg_unknown(env, regs, regno);
2320                 return;
2321         }
2322         mark_reg_known_zero(env, regs, regno);
2323         regs[regno].type = PTR_TO_BTF_ID | flag;
2324         regs[regno].btf = btf;
2325         regs[regno].btf_id = btf_id;
2326 }
2327
2328 #define DEF_NOT_SUBREG  (0)
2329 static void init_reg_state(struct bpf_verifier_env *env,
2330                            struct bpf_func_state *state)
2331 {
2332         struct bpf_reg_state *regs = state->regs;
2333         int i;
2334
2335         for (i = 0; i < MAX_BPF_REG; i++) {
2336                 mark_reg_not_init(env, regs, i);
2337                 regs[i].live = REG_LIVE_NONE;
2338                 regs[i].parent = NULL;
2339                 regs[i].subreg_def = DEF_NOT_SUBREG;
2340         }
2341
2342         /* frame pointer */
2343         regs[BPF_REG_FP].type = PTR_TO_STACK;
2344         mark_reg_known_zero(env, regs, BPF_REG_FP);
2345         regs[BPF_REG_FP].frameno = state->frameno;
2346 }
2347
2348 #define BPF_MAIN_FUNC (-1)
2349 static void init_func_state(struct bpf_verifier_env *env,
2350                             struct bpf_func_state *state,
2351                             int callsite, int frameno, int subprogno)
2352 {
2353         state->callsite = callsite;
2354         state->frameno = frameno;
2355         state->subprogno = subprogno;
2356         state->callback_ret_range = tnum_range(0, 0);
2357         init_reg_state(env, state);
2358         mark_verifier_state_scratched(env);
2359 }
2360
2361 /* Similar to push_stack(), but for async callbacks */
2362 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2363                                                 int insn_idx, int prev_insn_idx,
2364                                                 int subprog)
2365 {
2366         struct bpf_verifier_stack_elem *elem;
2367         struct bpf_func_state *frame;
2368
2369         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2370         if (!elem)
2371                 goto err;
2372
2373         elem->insn_idx = insn_idx;
2374         elem->prev_insn_idx = prev_insn_idx;
2375         elem->next = env->head;
2376         elem->log_pos = env->log.end_pos;
2377         env->head = elem;
2378         env->stack_size++;
2379         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2380                 verbose(env,
2381                         "The sequence of %d jumps is too complex for async cb.\n",
2382                         env->stack_size);
2383                 goto err;
2384         }
2385         /* Unlike push_stack() do not copy_verifier_state().
2386          * The caller state doesn't matter.
2387          * This is async callback. It starts in a fresh stack.
2388          * Initialize it similar to do_check_common().
2389          */
2390         elem->st.branches = 1;
2391         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2392         if (!frame)
2393                 goto err;
2394         init_func_state(env, frame,
2395                         BPF_MAIN_FUNC /* callsite */,
2396                         0 /* frameno within this callchain */,
2397                         subprog /* subprog number within this prog */);
2398         elem->st.frame[0] = frame;
2399         return &elem->st;
2400 err:
2401         free_verifier_state(env->cur_state, true);
2402         env->cur_state = NULL;
2403         /* pop all elements and return */
2404         while (!pop_stack(env, NULL, NULL, false));
2405         return NULL;
2406 }
2407
2408
2409 enum reg_arg_type {
2410         SRC_OP,         /* register is used as source operand */
2411         DST_OP,         /* register is used as destination operand */
2412         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2413 };
2414
2415 static int cmp_subprogs(const void *a, const void *b)
2416 {
2417         return ((struct bpf_subprog_info *)a)->start -
2418                ((struct bpf_subprog_info *)b)->start;
2419 }
2420
2421 static int find_subprog(struct bpf_verifier_env *env, int off)
2422 {
2423         struct bpf_subprog_info *p;
2424
2425         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2426                     sizeof(env->subprog_info[0]), cmp_subprogs);
2427         if (!p)
2428                 return -ENOENT;
2429         return p - env->subprog_info;
2430
2431 }
2432
2433 static int add_subprog(struct bpf_verifier_env *env, int off)
2434 {
2435         int insn_cnt = env->prog->len;
2436         int ret;
2437
2438         if (off >= insn_cnt || off < 0) {
2439                 verbose(env, "call to invalid destination\n");
2440                 return -EINVAL;
2441         }
2442         ret = find_subprog(env, off);
2443         if (ret >= 0)
2444                 return ret;
2445         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2446                 verbose(env, "too many subprograms\n");
2447                 return -E2BIG;
2448         }
2449         /* determine subprog starts. The end is one before the next starts */
2450         env->subprog_info[env->subprog_cnt++].start = off;
2451         sort(env->subprog_info, env->subprog_cnt,
2452              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2453         return env->subprog_cnt - 1;
2454 }
2455
2456 #define MAX_KFUNC_DESCS 256
2457 #define MAX_KFUNC_BTFS  256
2458
2459 struct bpf_kfunc_desc {
2460         struct btf_func_model func_model;
2461         u32 func_id;
2462         s32 imm;
2463         u16 offset;
2464         unsigned long addr;
2465 };
2466
2467 struct bpf_kfunc_btf {
2468         struct btf *btf;
2469         struct module *module;
2470         u16 offset;
2471 };
2472
2473 struct bpf_kfunc_desc_tab {
2474         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2475          * verification. JITs do lookups by bpf_insn, where func_id may not be
2476          * available, therefore at the end of verification do_misc_fixups()
2477          * sorts this by imm and offset.
2478          */
2479         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2480         u32 nr_descs;
2481 };
2482
2483 struct bpf_kfunc_btf_tab {
2484         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2485         u32 nr_descs;
2486 };
2487
2488 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2489 {
2490         const struct bpf_kfunc_desc *d0 = a;
2491         const struct bpf_kfunc_desc *d1 = b;
2492
2493         /* func_id is not greater than BTF_MAX_TYPE */
2494         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2495 }
2496
2497 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2498 {
2499         const struct bpf_kfunc_btf *d0 = a;
2500         const struct bpf_kfunc_btf *d1 = b;
2501
2502         return d0->offset - d1->offset;
2503 }
2504
2505 static const struct bpf_kfunc_desc *
2506 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2507 {
2508         struct bpf_kfunc_desc desc = {
2509                 .func_id = func_id,
2510                 .offset = offset,
2511         };
2512         struct bpf_kfunc_desc_tab *tab;
2513
2514         tab = prog->aux->kfunc_tab;
2515         return bsearch(&desc, tab->descs, tab->nr_descs,
2516                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2517 }
2518
2519 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2520                        u16 btf_fd_idx, u8 **func_addr)
2521 {
2522         const struct bpf_kfunc_desc *desc;
2523
2524         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2525         if (!desc)
2526                 return -EFAULT;
2527
2528         *func_addr = (u8 *)desc->addr;
2529         return 0;
2530 }
2531
2532 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2533                                          s16 offset)
2534 {
2535         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2536         struct bpf_kfunc_btf_tab *tab;
2537         struct bpf_kfunc_btf *b;
2538         struct module *mod;
2539         struct btf *btf;
2540         int btf_fd;
2541
2542         tab = env->prog->aux->kfunc_btf_tab;
2543         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2544                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2545         if (!b) {
2546                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2547                         verbose(env, "too many different module BTFs\n");
2548                         return ERR_PTR(-E2BIG);
2549                 }
2550
2551                 if (bpfptr_is_null(env->fd_array)) {
2552                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2553                         return ERR_PTR(-EPROTO);
2554                 }
2555
2556                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2557                                             offset * sizeof(btf_fd),
2558                                             sizeof(btf_fd)))
2559                         return ERR_PTR(-EFAULT);
2560
2561                 btf = btf_get_by_fd(btf_fd);
2562                 if (IS_ERR(btf)) {
2563                         verbose(env, "invalid module BTF fd specified\n");
2564                         return btf;
2565                 }
2566
2567                 if (!btf_is_module(btf)) {
2568                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2569                         btf_put(btf);
2570                         return ERR_PTR(-EINVAL);
2571                 }
2572
2573                 mod = btf_try_get_module(btf);
2574                 if (!mod) {
2575                         btf_put(btf);
2576                         return ERR_PTR(-ENXIO);
2577                 }
2578
2579                 b = &tab->descs[tab->nr_descs++];
2580                 b->btf = btf;
2581                 b->module = mod;
2582                 b->offset = offset;
2583
2584                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2585                      kfunc_btf_cmp_by_off, NULL);
2586         }
2587         return b->btf;
2588 }
2589
2590 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2591 {
2592         if (!tab)
2593                 return;
2594
2595         while (tab->nr_descs--) {
2596                 module_put(tab->descs[tab->nr_descs].module);
2597                 btf_put(tab->descs[tab->nr_descs].btf);
2598         }
2599         kfree(tab);
2600 }
2601
2602 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2603 {
2604         if (offset) {
2605                 if (offset < 0) {
2606                         /* In the future, this can be allowed to increase limit
2607                          * of fd index into fd_array, interpreted as u16.
2608                          */
2609                         verbose(env, "negative offset disallowed for kernel module function call\n");
2610                         return ERR_PTR(-EINVAL);
2611                 }
2612
2613                 return __find_kfunc_desc_btf(env, offset);
2614         }
2615         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2616 }
2617
2618 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2619 {
2620         const struct btf_type *func, *func_proto;
2621         struct bpf_kfunc_btf_tab *btf_tab;
2622         struct bpf_kfunc_desc_tab *tab;
2623         struct bpf_prog_aux *prog_aux;
2624         struct bpf_kfunc_desc *desc;
2625         const char *func_name;
2626         struct btf *desc_btf;
2627         unsigned long call_imm;
2628         unsigned long addr;
2629         int err;
2630
2631         prog_aux = env->prog->aux;
2632         tab = prog_aux->kfunc_tab;
2633         btf_tab = prog_aux->kfunc_btf_tab;
2634         if (!tab) {
2635                 if (!btf_vmlinux) {
2636                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2637                         return -ENOTSUPP;
2638                 }
2639
2640                 if (!env->prog->jit_requested) {
2641                         verbose(env, "JIT is required for calling kernel function\n");
2642                         return -ENOTSUPP;
2643                 }
2644
2645                 if (!bpf_jit_supports_kfunc_call()) {
2646                         verbose(env, "JIT does not support calling kernel function\n");
2647                         return -ENOTSUPP;
2648                 }
2649
2650                 if (!env->prog->gpl_compatible) {
2651                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2652                         return -EINVAL;
2653                 }
2654
2655                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2656                 if (!tab)
2657                         return -ENOMEM;
2658                 prog_aux->kfunc_tab = tab;
2659         }
2660
2661         /* func_id == 0 is always invalid, but instead of returning an error, be
2662          * conservative and wait until the code elimination pass before returning
2663          * error, so that invalid calls that get pruned out can be in BPF programs
2664          * loaded from userspace.  It is also required that offset be untouched
2665          * for such calls.
2666          */
2667         if (!func_id && !offset)
2668                 return 0;
2669
2670         if (!btf_tab && offset) {
2671                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2672                 if (!btf_tab)
2673                         return -ENOMEM;
2674                 prog_aux->kfunc_btf_tab = btf_tab;
2675         }
2676
2677         desc_btf = find_kfunc_desc_btf(env, offset);
2678         if (IS_ERR(desc_btf)) {
2679                 verbose(env, "failed to find BTF for kernel function\n");
2680                 return PTR_ERR(desc_btf);
2681         }
2682
2683         if (find_kfunc_desc(env->prog, func_id, offset))
2684                 return 0;
2685
2686         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2687                 verbose(env, "too many different kernel function calls\n");
2688                 return -E2BIG;
2689         }
2690
2691         func = btf_type_by_id(desc_btf, func_id);
2692         if (!func || !btf_type_is_func(func)) {
2693                 verbose(env, "kernel btf_id %u is not a function\n",
2694                         func_id);
2695                 return -EINVAL;
2696         }
2697         func_proto = btf_type_by_id(desc_btf, func->type);
2698         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2699                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2700                         func_id);
2701                 return -EINVAL;
2702         }
2703
2704         func_name = btf_name_by_offset(desc_btf, func->name_off);
2705         addr = kallsyms_lookup_name(func_name);
2706         if (!addr) {
2707                 verbose(env, "cannot find address for kernel function %s\n",
2708                         func_name);
2709                 return -EINVAL;
2710         }
2711         specialize_kfunc(env, func_id, offset, &addr);
2712
2713         if (bpf_jit_supports_far_kfunc_call()) {
2714                 call_imm = func_id;
2715         } else {
2716                 call_imm = BPF_CALL_IMM(addr);
2717                 /* Check whether the relative offset overflows desc->imm */
2718                 if ((unsigned long)(s32)call_imm != call_imm) {
2719                         verbose(env, "address of kernel function %s is out of range\n",
2720                                 func_name);
2721                         return -EINVAL;
2722                 }
2723         }
2724
2725         if (bpf_dev_bound_kfunc_id(func_id)) {
2726                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2727                 if (err)
2728                         return err;
2729         }
2730
2731         desc = &tab->descs[tab->nr_descs++];
2732         desc->func_id = func_id;
2733         desc->imm = call_imm;
2734         desc->offset = offset;
2735         desc->addr = addr;
2736         err = btf_distill_func_proto(&env->log, desc_btf,
2737                                      func_proto, func_name,
2738                                      &desc->func_model);
2739         if (!err)
2740                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2741                      kfunc_desc_cmp_by_id_off, NULL);
2742         return err;
2743 }
2744
2745 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2746 {
2747         const struct bpf_kfunc_desc *d0 = a;
2748         const struct bpf_kfunc_desc *d1 = b;
2749
2750         if (d0->imm != d1->imm)
2751                 return d0->imm < d1->imm ? -1 : 1;
2752         if (d0->offset != d1->offset)
2753                 return d0->offset < d1->offset ? -1 : 1;
2754         return 0;
2755 }
2756
2757 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2758 {
2759         struct bpf_kfunc_desc_tab *tab;
2760
2761         tab = prog->aux->kfunc_tab;
2762         if (!tab)
2763                 return;
2764
2765         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2766              kfunc_desc_cmp_by_imm_off, NULL);
2767 }
2768
2769 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2770 {
2771         return !!prog->aux->kfunc_tab;
2772 }
2773
2774 const struct btf_func_model *
2775 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2776                          const struct bpf_insn *insn)
2777 {
2778         const struct bpf_kfunc_desc desc = {
2779                 .imm = insn->imm,
2780                 .offset = insn->off,
2781         };
2782         const struct bpf_kfunc_desc *res;
2783         struct bpf_kfunc_desc_tab *tab;
2784
2785         tab = prog->aux->kfunc_tab;
2786         res = bsearch(&desc, tab->descs, tab->nr_descs,
2787                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2788
2789         return res ? &res->func_model : NULL;
2790 }
2791
2792 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2793 {
2794         struct bpf_subprog_info *subprog = env->subprog_info;
2795         struct bpf_insn *insn = env->prog->insnsi;
2796         int i, ret, insn_cnt = env->prog->len;
2797
2798         /* Add entry function. */
2799         ret = add_subprog(env, 0);
2800         if (ret)
2801                 return ret;
2802
2803         for (i = 0; i < insn_cnt; i++, insn++) {
2804                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2805                     !bpf_pseudo_kfunc_call(insn))
2806                         continue;
2807
2808                 if (!env->bpf_capable) {
2809                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2810                         return -EPERM;
2811                 }
2812
2813                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2814                         ret = add_subprog(env, i + insn->imm + 1);
2815                 else
2816                         ret = add_kfunc_call(env, insn->imm, insn->off);
2817
2818                 if (ret < 0)
2819                         return ret;
2820         }
2821
2822         /* Add a fake 'exit' subprog which could simplify subprog iteration
2823          * logic. 'subprog_cnt' should not be increased.
2824          */
2825         subprog[env->subprog_cnt].start = insn_cnt;
2826
2827         if (env->log.level & BPF_LOG_LEVEL2)
2828                 for (i = 0; i < env->subprog_cnt; i++)
2829                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2830
2831         return 0;
2832 }
2833
2834 static int check_subprogs(struct bpf_verifier_env *env)
2835 {
2836         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2837         struct bpf_subprog_info *subprog = env->subprog_info;
2838         struct bpf_insn *insn = env->prog->insnsi;
2839         int insn_cnt = env->prog->len;
2840
2841         /* now check that all jumps are within the same subprog */
2842         subprog_start = subprog[cur_subprog].start;
2843         subprog_end = subprog[cur_subprog + 1].start;
2844         for (i = 0; i < insn_cnt; i++) {
2845                 u8 code = insn[i].code;
2846
2847                 if (code == (BPF_JMP | BPF_CALL) &&
2848                     insn[i].src_reg == 0 &&
2849                     insn[i].imm == BPF_FUNC_tail_call)
2850                         subprog[cur_subprog].has_tail_call = true;
2851                 if (BPF_CLASS(code) == BPF_LD &&
2852                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2853                         subprog[cur_subprog].has_ld_abs = true;
2854                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2855                         goto next;
2856                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2857                         goto next;
2858                 if (code == (BPF_JMP32 | BPF_JA))
2859                         off = i + insn[i].imm + 1;
2860                 else
2861                         off = i + insn[i].off + 1;
2862                 if (off < subprog_start || off >= subprog_end) {
2863                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2864                         return -EINVAL;
2865                 }
2866 next:
2867                 if (i == subprog_end - 1) {
2868                         /* to avoid fall-through from one subprog into another
2869                          * the last insn of the subprog should be either exit
2870                          * or unconditional jump back
2871                          */
2872                         if (code != (BPF_JMP | BPF_EXIT) &&
2873                             code != (BPF_JMP32 | BPF_JA) &&
2874                             code != (BPF_JMP | BPF_JA)) {
2875                                 verbose(env, "last insn is not an exit or jmp\n");
2876                                 return -EINVAL;
2877                         }
2878                         subprog_start = subprog_end;
2879                         cur_subprog++;
2880                         if (cur_subprog < env->subprog_cnt)
2881                                 subprog_end = subprog[cur_subprog + 1].start;
2882                 }
2883         }
2884         return 0;
2885 }
2886
2887 /* Parentage chain of this register (or stack slot) should take care of all
2888  * issues like callee-saved registers, stack slot allocation time, etc.
2889  */
2890 static int mark_reg_read(struct bpf_verifier_env *env,
2891                          const struct bpf_reg_state *state,
2892                          struct bpf_reg_state *parent, u8 flag)
2893 {
2894         bool writes = parent == state->parent; /* Observe write marks */
2895         int cnt = 0;
2896
2897         while (parent) {
2898                 /* if read wasn't screened by an earlier write ... */
2899                 if (writes && state->live & REG_LIVE_WRITTEN)
2900                         break;
2901                 if (parent->live & REG_LIVE_DONE) {
2902                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2903                                 reg_type_str(env, parent->type),
2904                                 parent->var_off.value, parent->off);
2905                         return -EFAULT;
2906                 }
2907                 /* The first condition is more likely to be true than the
2908                  * second, checked it first.
2909                  */
2910                 if ((parent->live & REG_LIVE_READ) == flag ||
2911                     parent->live & REG_LIVE_READ64)
2912                         /* The parentage chain never changes and
2913                          * this parent was already marked as LIVE_READ.
2914                          * There is no need to keep walking the chain again and
2915                          * keep re-marking all parents as LIVE_READ.
2916                          * This case happens when the same register is read
2917                          * multiple times without writes into it in-between.
2918                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2919                          * then no need to set the weak REG_LIVE_READ32.
2920                          */
2921                         break;
2922                 /* ... then we depend on parent's value */
2923                 parent->live |= flag;
2924                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2925                 if (flag == REG_LIVE_READ64)
2926                         parent->live &= ~REG_LIVE_READ32;
2927                 state = parent;
2928                 parent = state->parent;
2929                 writes = true;
2930                 cnt++;
2931         }
2932
2933         if (env->longest_mark_read_walk < cnt)
2934                 env->longest_mark_read_walk = cnt;
2935         return 0;
2936 }
2937
2938 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2939 {
2940         struct bpf_func_state *state = func(env, reg);
2941         int spi, ret;
2942
2943         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2944          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2945          * check_kfunc_call.
2946          */
2947         if (reg->type == CONST_PTR_TO_DYNPTR)
2948                 return 0;
2949         spi = dynptr_get_spi(env, reg);
2950         if (spi < 0)
2951                 return spi;
2952         /* Caller ensures dynptr is valid and initialized, which means spi is in
2953          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2954          * read.
2955          */
2956         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2957                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2958         if (ret)
2959                 return ret;
2960         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2961                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2962 }
2963
2964 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2965                           int spi, int nr_slots)
2966 {
2967         struct bpf_func_state *state = func(env, reg);
2968         int err, i;
2969
2970         for (i = 0; i < nr_slots; i++) {
2971                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2972
2973                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2974                 if (err)
2975                         return err;
2976
2977                 mark_stack_slot_scratched(env, spi - i);
2978         }
2979
2980         return 0;
2981 }
2982
2983 /* This function is supposed to be used by the following 32-bit optimization
2984  * code only. It returns TRUE if the source or destination register operates
2985  * on 64-bit, otherwise return FALSE.
2986  */
2987 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2988                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2989 {
2990         u8 code, class, op;
2991
2992         code = insn->code;
2993         class = BPF_CLASS(code);
2994         op = BPF_OP(code);
2995         if (class == BPF_JMP) {
2996                 /* BPF_EXIT for "main" will reach here. Return TRUE
2997                  * conservatively.
2998                  */
2999                 if (op == BPF_EXIT)
3000                         return true;
3001                 if (op == BPF_CALL) {
3002                         /* BPF to BPF call will reach here because of marking
3003                          * caller saved clobber with DST_OP_NO_MARK for which we
3004                          * don't care the register def because they are anyway
3005                          * marked as NOT_INIT already.
3006                          */
3007                         if (insn->src_reg == BPF_PSEUDO_CALL)
3008                                 return false;
3009                         /* Helper call will reach here because of arg type
3010                          * check, conservatively return TRUE.
3011                          */
3012                         if (t == SRC_OP)
3013                                 return true;
3014
3015                         return false;
3016                 }
3017         }
3018
3019         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3020                 return false;
3021
3022         if (class == BPF_ALU64 || class == BPF_JMP ||
3023             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3024                 return true;
3025
3026         if (class == BPF_ALU || class == BPF_JMP32)
3027                 return false;
3028
3029         if (class == BPF_LDX) {
3030                 if (t != SRC_OP)
3031                         return BPF_SIZE(code) == BPF_DW;
3032                 /* LDX source must be ptr. */
3033                 return true;
3034         }
3035
3036         if (class == BPF_STX) {
3037                 /* BPF_STX (including atomic variants) has multiple source
3038                  * operands, one of which is a ptr. Check whether the caller is
3039                  * asking about it.
3040                  */
3041                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3042                         return true;
3043                 return BPF_SIZE(code) == BPF_DW;
3044         }
3045
3046         if (class == BPF_LD) {
3047                 u8 mode = BPF_MODE(code);
3048
3049                 /* LD_IMM64 */
3050                 if (mode == BPF_IMM)
3051                         return true;
3052
3053                 /* Both LD_IND and LD_ABS return 32-bit data. */
3054                 if (t != SRC_OP)
3055                         return  false;
3056
3057                 /* Implicit ctx ptr. */
3058                 if (regno == BPF_REG_6)
3059                         return true;
3060
3061                 /* Explicit source could be any width. */
3062                 return true;
3063         }
3064
3065         if (class == BPF_ST)
3066                 /* The only source register for BPF_ST is a ptr. */
3067                 return true;
3068
3069         /* Conservatively return true at default. */
3070         return true;
3071 }
3072
3073 /* Return the regno defined by the insn, or -1. */
3074 static int insn_def_regno(const struct bpf_insn *insn)
3075 {
3076         switch (BPF_CLASS(insn->code)) {
3077         case BPF_JMP:
3078         case BPF_JMP32:
3079         case BPF_ST:
3080                 return -1;
3081         case BPF_STX:
3082                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3083                     (insn->imm & BPF_FETCH)) {
3084                         if (insn->imm == BPF_CMPXCHG)
3085                                 return BPF_REG_0;
3086                         else
3087                                 return insn->src_reg;
3088                 } else {
3089                         return -1;
3090                 }
3091         default:
3092                 return insn->dst_reg;
3093         }
3094 }
3095
3096 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3097 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3098 {
3099         int dst_reg = insn_def_regno(insn);
3100
3101         if (dst_reg == -1)
3102                 return false;
3103
3104         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3105 }
3106
3107 static void mark_insn_zext(struct bpf_verifier_env *env,
3108                            struct bpf_reg_state *reg)
3109 {
3110         s32 def_idx = reg->subreg_def;
3111
3112         if (def_idx == DEF_NOT_SUBREG)
3113                 return;
3114
3115         env->insn_aux_data[def_idx - 1].zext_dst = true;
3116         /* The dst will be zero extended, so won't be sub-register anymore. */
3117         reg->subreg_def = DEF_NOT_SUBREG;
3118 }
3119
3120 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3121                          enum reg_arg_type t)
3122 {
3123         struct bpf_verifier_state *vstate = env->cur_state;
3124         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3125         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3126         struct bpf_reg_state *reg, *regs = state->regs;
3127         bool rw64;
3128
3129         if (regno >= MAX_BPF_REG) {
3130                 verbose(env, "R%d is invalid\n", regno);
3131                 return -EINVAL;
3132         }
3133
3134         mark_reg_scratched(env, regno);
3135
3136         reg = &regs[regno];
3137         rw64 = is_reg64(env, insn, regno, reg, t);
3138         if (t == SRC_OP) {
3139                 /* check whether register used as source operand can be read */
3140                 if (reg->type == NOT_INIT) {
3141                         verbose(env, "R%d !read_ok\n", regno);
3142                         return -EACCES;
3143                 }
3144                 /* We don't need to worry about FP liveness because it's read-only */
3145                 if (regno == BPF_REG_FP)
3146                         return 0;
3147
3148                 if (rw64)
3149                         mark_insn_zext(env, reg);
3150
3151                 return mark_reg_read(env, reg, reg->parent,
3152                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3153         } else {
3154                 /* check whether register used as dest operand can be written to */
3155                 if (regno == BPF_REG_FP) {
3156                         verbose(env, "frame pointer is read only\n");
3157                         return -EACCES;
3158                 }
3159                 reg->live |= REG_LIVE_WRITTEN;
3160                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3161                 if (t == DST_OP)
3162                         mark_reg_unknown(env, regs, regno);
3163         }
3164         return 0;
3165 }
3166
3167 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3168 {
3169         env->insn_aux_data[idx].jmp_point = true;
3170 }
3171
3172 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3173 {
3174         return env->insn_aux_data[insn_idx].jmp_point;
3175 }
3176
3177 /* for any branch, call, exit record the history of jmps in the given state */
3178 static int push_jmp_history(struct bpf_verifier_env *env,
3179                             struct bpf_verifier_state *cur)
3180 {
3181         u32 cnt = cur->jmp_history_cnt;
3182         struct bpf_idx_pair *p;
3183         size_t alloc_size;
3184
3185         if (!is_jmp_point(env, env->insn_idx))
3186                 return 0;
3187
3188         cnt++;
3189         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3190         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3191         if (!p)
3192                 return -ENOMEM;
3193         p[cnt - 1].idx = env->insn_idx;
3194         p[cnt - 1].prev_idx = env->prev_insn_idx;
3195         cur->jmp_history = p;
3196         cur->jmp_history_cnt = cnt;
3197         return 0;
3198 }
3199
3200 /* Backtrack one insn at a time. If idx is not at the top of recorded
3201  * history then previous instruction came from straight line execution.
3202  */
3203 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3204                              u32 *history)
3205 {
3206         u32 cnt = *history;
3207
3208         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3209                 i = st->jmp_history[cnt - 1].prev_idx;
3210                 (*history)--;
3211         } else {
3212                 i--;
3213         }
3214         return i;
3215 }
3216
3217 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3218 {
3219         const struct btf_type *func;
3220         struct btf *desc_btf;
3221
3222         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3223                 return NULL;
3224
3225         desc_btf = find_kfunc_desc_btf(data, insn->off);
3226         if (IS_ERR(desc_btf))
3227                 return "<error>";
3228
3229         func = btf_type_by_id(desc_btf, insn->imm);
3230         return btf_name_by_offset(desc_btf, func->name_off);
3231 }
3232
3233 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3234 {
3235         bt->frame = frame;
3236 }
3237
3238 static inline void bt_reset(struct backtrack_state *bt)
3239 {
3240         struct bpf_verifier_env *env = bt->env;
3241
3242         memset(bt, 0, sizeof(*bt));
3243         bt->env = env;
3244 }
3245
3246 static inline u32 bt_empty(struct backtrack_state *bt)
3247 {
3248         u64 mask = 0;
3249         int i;
3250
3251         for (i = 0; i <= bt->frame; i++)
3252                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3253
3254         return mask == 0;
3255 }
3256
3257 static inline int bt_subprog_enter(struct backtrack_state *bt)
3258 {
3259         if (bt->frame == MAX_CALL_FRAMES - 1) {
3260                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3261                 WARN_ONCE(1, "verifier backtracking bug");
3262                 return -EFAULT;
3263         }
3264         bt->frame++;
3265         return 0;
3266 }
3267
3268 static inline int bt_subprog_exit(struct backtrack_state *bt)
3269 {
3270         if (bt->frame == 0) {
3271                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3272                 WARN_ONCE(1, "verifier backtracking bug");
3273                 return -EFAULT;
3274         }
3275         bt->frame--;
3276         return 0;
3277 }
3278
3279 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3280 {
3281         bt->reg_masks[frame] |= 1 << reg;
3282 }
3283
3284 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3285 {
3286         bt->reg_masks[frame] &= ~(1 << reg);
3287 }
3288
3289 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3290 {
3291         bt_set_frame_reg(bt, bt->frame, reg);
3292 }
3293
3294 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3295 {
3296         bt_clear_frame_reg(bt, bt->frame, reg);
3297 }
3298
3299 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3300 {
3301         bt->stack_masks[frame] |= 1ull << slot;
3302 }
3303
3304 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3305 {
3306         bt->stack_masks[frame] &= ~(1ull << slot);
3307 }
3308
3309 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3310 {
3311         bt_set_frame_slot(bt, bt->frame, slot);
3312 }
3313
3314 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3315 {
3316         bt_clear_frame_slot(bt, bt->frame, slot);
3317 }
3318
3319 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3320 {
3321         return bt->reg_masks[frame];
3322 }
3323
3324 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3325 {
3326         return bt->reg_masks[bt->frame];
3327 }
3328
3329 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3330 {
3331         return bt->stack_masks[frame];
3332 }
3333
3334 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3335 {
3336         return bt->stack_masks[bt->frame];
3337 }
3338
3339 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3340 {
3341         return bt->reg_masks[bt->frame] & (1 << reg);
3342 }
3343
3344 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3345 {
3346         return bt->stack_masks[bt->frame] & (1ull << slot);
3347 }
3348
3349 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3350 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3351 {
3352         DECLARE_BITMAP(mask, 64);
3353         bool first = true;
3354         int i, n;
3355
3356         buf[0] = '\0';
3357
3358         bitmap_from_u64(mask, reg_mask);
3359         for_each_set_bit(i, mask, 32) {
3360                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3361                 first = false;
3362                 buf += n;
3363                 buf_sz -= n;
3364                 if (buf_sz < 0)
3365                         break;
3366         }
3367 }
3368 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3369 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3370 {
3371         DECLARE_BITMAP(mask, 64);
3372         bool first = true;
3373         int i, n;
3374
3375         buf[0] = '\0';
3376
3377         bitmap_from_u64(mask, stack_mask);
3378         for_each_set_bit(i, mask, 64) {
3379                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3380                 first = false;
3381                 buf += n;
3382                 buf_sz -= n;
3383                 if (buf_sz < 0)
3384                         break;
3385         }
3386 }
3387
3388 /* For given verifier state backtrack_insn() is called from the last insn to
3389  * the first insn. Its purpose is to compute a bitmask of registers and
3390  * stack slots that needs precision in the parent verifier state.
3391  *
3392  * @idx is an index of the instruction we are currently processing;
3393  * @subseq_idx is an index of the subsequent instruction that:
3394  *   - *would be* executed next, if jump history is viewed in forward order;
3395  *   - *was* processed previously during backtracking.
3396  */
3397 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3398                           struct backtrack_state *bt)
3399 {
3400         const struct bpf_insn_cbs cbs = {
3401                 .cb_call        = disasm_kfunc_name,
3402                 .cb_print       = verbose,
3403                 .private_data   = env,
3404         };
3405         struct bpf_insn *insn = env->prog->insnsi + idx;
3406         u8 class = BPF_CLASS(insn->code);
3407         u8 opcode = BPF_OP(insn->code);
3408         u8 mode = BPF_MODE(insn->code);
3409         u32 dreg = insn->dst_reg;
3410         u32 sreg = insn->src_reg;
3411         u32 spi, i;
3412
3413         if (insn->code == 0)
3414                 return 0;
3415         if (env->log.level & BPF_LOG_LEVEL2) {
3416                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3417                 verbose(env, "mark_precise: frame%d: regs=%s ",
3418                         bt->frame, env->tmp_str_buf);
3419                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3420                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3421                 verbose(env, "%d: ", idx);
3422                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3423         }
3424
3425         if (class == BPF_ALU || class == BPF_ALU64) {
3426                 if (!bt_is_reg_set(bt, dreg))
3427                         return 0;
3428                 if (opcode == BPF_MOV) {
3429                         if (BPF_SRC(insn->code) == BPF_X) {
3430                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3431                                  * dreg needs precision after this insn
3432                                  * sreg needs precision before this insn
3433                                  */
3434                                 bt_clear_reg(bt, dreg);
3435                                 bt_set_reg(bt, sreg);
3436                         } else {
3437                                 /* dreg = K
3438                                  * dreg needs precision after this insn.
3439                                  * Corresponding register is already marked
3440                                  * as precise=true in this verifier state.
3441                                  * No further markings in parent are necessary
3442                                  */
3443                                 bt_clear_reg(bt, dreg);
3444                         }
3445                 } else {
3446                         if (BPF_SRC(insn->code) == BPF_X) {
3447                                 /* dreg += sreg
3448                                  * both dreg and sreg need precision
3449                                  * before this insn
3450                                  */
3451                                 bt_set_reg(bt, sreg);
3452                         } /* else dreg += K
3453                            * dreg still needs precision before this insn
3454                            */
3455                 }
3456         } else if (class == BPF_LDX) {
3457                 if (!bt_is_reg_set(bt, dreg))
3458                         return 0;
3459                 bt_clear_reg(bt, dreg);
3460
3461                 /* scalars can only be spilled into stack w/o losing precision.
3462                  * Load from any other memory can be zero extended.
3463                  * The desire to keep that precision is already indicated
3464                  * by 'precise' mark in corresponding register of this state.
3465                  * No further tracking necessary.
3466                  */
3467                 if (insn->src_reg != BPF_REG_FP)
3468                         return 0;
3469
3470                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3471                  * that [fp - off] slot contains scalar that needs to be
3472                  * tracked with precision
3473                  */
3474                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3475                 if (spi >= 64) {
3476                         verbose(env, "BUG spi %d\n", spi);
3477                         WARN_ONCE(1, "verifier backtracking bug");
3478                         return -EFAULT;
3479                 }
3480                 bt_set_slot(bt, spi);
3481         } else if (class == BPF_STX || class == BPF_ST) {
3482                 if (bt_is_reg_set(bt, dreg))
3483                         /* stx & st shouldn't be using _scalar_ dst_reg
3484                          * to access memory. It means backtracking
3485                          * encountered a case of pointer subtraction.
3486                          */
3487                         return -ENOTSUPP;
3488                 /* scalars can only be spilled into stack */
3489                 if (insn->dst_reg != BPF_REG_FP)
3490                         return 0;
3491                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3492                 if (spi >= 64) {
3493                         verbose(env, "BUG spi %d\n", spi);
3494                         WARN_ONCE(1, "verifier backtracking bug");
3495                         return -EFAULT;
3496                 }
3497                 if (!bt_is_slot_set(bt, spi))
3498                         return 0;
3499                 bt_clear_slot(bt, spi);
3500                 if (class == BPF_STX)
3501                         bt_set_reg(bt, sreg);
3502         } else if (class == BPF_JMP || class == BPF_JMP32) {
3503                 if (bpf_pseudo_call(insn)) {
3504                         int subprog_insn_idx, subprog;
3505
3506                         subprog_insn_idx = idx + insn->imm + 1;
3507                         subprog = find_subprog(env, subprog_insn_idx);
3508                         if (subprog < 0)
3509                                 return -EFAULT;
3510
3511                         if (subprog_is_global(env, subprog)) {
3512                                 /* check that jump history doesn't have any
3513                                  * extra instructions from subprog; the next
3514                                  * instruction after call to global subprog
3515                                  * should be literally next instruction in
3516                                  * caller program
3517                                  */
3518                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3519                                 /* r1-r5 are invalidated after subprog call,
3520                                  * so for global func call it shouldn't be set
3521                                  * anymore
3522                                  */
3523                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3524                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3525                                         WARN_ONCE(1, "verifier backtracking bug");
3526                                         return -EFAULT;
3527                                 }
3528                                 /* global subprog always sets R0 */
3529                                 bt_clear_reg(bt, BPF_REG_0);
3530                                 return 0;
3531                         } else {
3532                                 /* static subprog call instruction, which
3533                                  * means that we are exiting current subprog,
3534                                  * so only r1-r5 could be still requested as
3535                                  * precise, r0 and r6-r10 or any stack slot in
3536                                  * the current frame should be zero by now
3537                                  */
3538                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3539                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3540                                         WARN_ONCE(1, "verifier backtracking bug");
3541                                         return -EFAULT;
3542                                 }
3543                                 /* we don't track register spills perfectly,
3544                                  * so fallback to force-precise instead of failing */
3545                                 if (bt_stack_mask(bt) != 0)
3546                                         return -ENOTSUPP;
3547                                 /* propagate r1-r5 to the caller */
3548                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3549                                         if (bt_is_reg_set(bt, i)) {
3550                                                 bt_clear_reg(bt, i);
3551                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3552                                         }
3553                                 }
3554                                 if (bt_subprog_exit(bt))
3555                                         return -EFAULT;
3556                                 return 0;
3557                         }
3558                 } else if ((bpf_helper_call(insn) &&
3559                             is_callback_calling_function(insn->imm) &&
3560                             !is_async_callback_calling_function(insn->imm)) ||
3561                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3562                         /* callback-calling helper or kfunc call, which means
3563                          * we are exiting from subprog, but unlike the subprog
3564                          * call handling above, we shouldn't propagate
3565                          * precision of r1-r5 (if any requested), as they are
3566                          * not actually arguments passed directly to callback
3567                          * subprogs
3568                          */
3569                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3570                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3571                                 WARN_ONCE(1, "verifier backtracking bug");
3572                                 return -EFAULT;
3573                         }
3574                         if (bt_stack_mask(bt) != 0)
3575                                 return -ENOTSUPP;
3576                         /* clear r1-r5 in callback subprog's mask */
3577                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3578                                 bt_clear_reg(bt, i);
3579                         if (bt_subprog_exit(bt))
3580                                 return -EFAULT;
3581                         return 0;
3582                 } else if (opcode == BPF_CALL) {
3583                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3584                          * catch this error later. Make backtracking conservative
3585                          * with ENOTSUPP.
3586                          */
3587                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3588                                 return -ENOTSUPP;
3589                         /* regular helper call sets R0 */
3590                         bt_clear_reg(bt, BPF_REG_0);
3591                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3592                                 /* if backtracing was looking for registers R1-R5
3593                                  * they should have been found already.
3594                                  */
3595                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3596                                 WARN_ONCE(1, "verifier backtracking bug");
3597                                 return -EFAULT;
3598                         }
3599                 } else if (opcode == BPF_EXIT) {
3600                         bool r0_precise;
3601
3602                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3603                                 /* if backtracing was looking for registers R1-R5
3604                                  * they should have been found already.
3605                                  */
3606                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3607                                 WARN_ONCE(1, "verifier backtracking bug");
3608                                 return -EFAULT;
3609                         }
3610
3611                         /* BPF_EXIT in subprog or callback always returns
3612                          * right after the call instruction, so by checking
3613                          * whether the instruction at subseq_idx-1 is subprog
3614                          * call or not we can distinguish actual exit from
3615                          * *subprog* from exit from *callback*. In the former
3616                          * case, we need to propagate r0 precision, if
3617                          * necessary. In the former we never do that.
3618                          */
3619                         r0_precise = subseq_idx - 1 >= 0 &&
3620                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3621                                      bt_is_reg_set(bt, BPF_REG_0);
3622
3623                         bt_clear_reg(bt, BPF_REG_0);
3624                         if (bt_subprog_enter(bt))
3625                                 return -EFAULT;
3626
3627                         if (r0_precise)
3628                                 bt_set_reg(bt, BPF_REG_0);
3629                         /* r6-r9 and stack slots will stay set in caller frame
3630                          * bitmasks until we return back from callee(s)
3631                          */
3632                         return 0;
3633                 } else if (BPF_SRC(insn->code) == BPF_X) {
3634                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3635                                 return 0;
3636                         /* dreg <cond> sreg
3637                          * Both dreg and sreg need precision before
3638                          * this insn. If only sreg was marked precise
3639                          * before it would be equally necessary to
3640                          * propagate it to dreg.
3641                          */
3642                         bt_set_reg(bt, dreg);
3643                         bt_set_reg(bt, sreg);
3644                          /* else dreg <cond> K
3645                           * Only dreg still needs precision before
3646                           * this insn, so for the K-based conditional
3647                           * there is nothing new to be marked.
3648                           */
3649                 }
3650         } else if (class == BPF_LD) {
3651                 if (!bt_is_reg_set(bt, dreg))
3652                         return 0;
3653                 bt_clear_reg(bt, dreg);
3654                 /* It's ld_imm64 or ld_abs or ld_ind.
3655                  * For ld_imm64 no further tracking of precision
3656                  * into parent is necessary
3657                  */
3658                 if (mode == BPF_IND || mode == BPF_ABS)
3659                         /* to be analyzed */
3660                         return -ENOTSUPP;
3661         }
3662         return 0;
3663 }
3664
3665 /* the scalar precision tracking algorithm:
3666  * . at the start all registers have precise=false.
3667  * . scalar ranges are tracked as normal through alu and jmp insns.
3668  * . once precise value of the scalar register is used in:
3669  *   .  ptr + scalar alu
3670  *   . if (scalar cond K|scalar)
3671  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3672  *   backtrack through the verifier states and mark all registers and
3673  *   stack slots with spilled constants that these scalar regisers
3674  *   should be precise.
3675  * . during state pruning two registers (or spilled stack slots)
3676  *   are equivalent if both are not precise.
3677  *
3678  * Note the verifier cannot simply walk register parentage chain,
3679  * since many different registers and stack slots could have been
3680  * used to compute single precise scalar.
3681  *
3682  * The approach of starting with precise=true for all registers and then
3683  * backtrack to mark a register as not precise when the verifier detects
3684  * that program doesn't care about specific value (e.g., when helper
3685  * takes register as ARG_ANYTHING parameter) is not safe.
3686  *
3687  * It's ok to walk single parentage chain of the verifier states.
3688  * It's possible that this backtracking will go all the way till 1st insn.
3689  * All other branches will be explored for needing precision later.
3690  *
3691  * The backtracking needs to deal with cases like:
3692  *   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)
3693  * r9 -= r8
3694  * r5 = r9
3695  * if r5 > 0x79f goto pc+7
3696  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3697  * r5 += 1
3698  * ...
3699  * call bpf_perf_event_output#25
3700  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3701  *
3702  * and this case:
3703  * r6 = 1
3704  * call foo // uses callee's r6 inside to compute r0
3705  * r0 += r6
3706  * if r0 == 0 goto
3707  *
3708  * to track above reg_mask/stack_mask needs to be independent for each frame.
3709  *
3710  * Also if parent's curframe > frame where backtracking started,
3711  * the verifier need to mark registers in both frames, otherwise callees
3712  * may incorrectly prune callers. This is similar to
3713  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3714  *
3715  * For now backtracking falls back into conservative marking.
3716  */
3717 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3718                                      struct bpf_verifier_state *st)
3719 {
3720         struct bpf_func_state *func;
3721         struct bpf_reg_state *reg;
3722         int i, j;
3723
3724         if (env->log.level & BPF_LOG_LEVEL2) {
3725                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3726                         st->curframe);
3727         }
3728
3729         /* big hammer: mark all scalars precise in this path.
3730          * pop_stack may still get !precise scalars.
3731          * We also skip current state and go straight to first parent state,
3732          * because precision markings in current non-checkpointed state are
3733          * not needed. See why in the comment in __mark_chain_precision below.
3734          */
3735         for (st = st->parent; st; st = st->parent) {
3736                 for (i = 0; i <= st->curframe; i++) {
3737                         func = st->frame[i];
3738                         for (j = 0; j < BPF_REG_FP; j++) {
3739                                 reg = &func->regs[j];
3740                                 if (reg->type != SCALAR_VALUE || reg->precise)
3741                                         continue;
3742                                 reg->precise = true;
3743                                 if (env->log.level & BPF_LOG_LEVEL2) {
3744                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3745                                                 i, j);
3746                                 }
3747                         }
3748                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3749                                 if (!is_spilled_reg(&func->stack[j]))
3750                                         continue;
3751                                 reg = &func->stack[j].spilled_ptr;
3752                                 if (reg->type != SCALAR_VALUE || reg->precise)
3753                                         continue;
3754                                 reg->precise = true;
3755                                 if (env->log.level & BPF_LOG_LEVEL2) {
3756                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3757                                                 i, -(j + 1) * 8);
3758                                 }
3759                         }
3760                 }
3761         }
3762 }
3763
3764 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3765 {
3766         struct bpf_func_state *func;
3767         struct bpf_reg_state *reg;
3768         int i, j;
3769
3770         for (i = 0; i <= st->curframe; i++) {
3771                 func = st->frame[i];
3772                 for (j = 0; j < BPF_REG_FP; j++) {
3773                         reg = &func->regs[j];
3774                         if (reg->type != SCALAR_VALUE)
3775                                 continue;
3776                         reg->precise = false;
3777                 }
3778                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3779                         if (!is_spilled_reg(&func->stack[j]))
3780                                 continue;
3781                         reg = &func->stack[j].spilled_ptr;
3782                         if (reg->type != SCALAR_VALUE)
3783                                 continue;
3784                         reg->precise = false;
3785                 }
3786         }
3787 }
3788
3789 static bool idset_contains(struct bpf_idset *s, u32 id)
3790 {
3791         u32 i;
3792
3793         for (i = 0; i < s->count; ++i)
3794                 if (s->ids[i] == id)
3795                         return true;
3796
3797         return false;
3798 }
3799
3800 static int idset_push(struct bpf_idset *s, u32 id)
3801 {
3802         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3803                 return -EFAULT;
3804         s->ids[s->count++] = id;
3805         return 0;
3806 }
3807
3808 static void idset_reset(struct bpf_idset *s)
3809 {
3810         s->count = 0;
3811 }
3812
3813 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3814  * Mark all registers with these IDs as precise.
3815  */
3816 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3817 {
3818         struct bpf_idset *precise_ids = &env->idset_scratch;
3819         struct backtrack_state *bt = &env->bt;
3820         struct bpf_func_state *func;
3821         struct bpf_reg_state *reg;
3822         DECLARE_BITMAP(mask, 64);
3823         int i, fr;
3824
3825         idset_reset(precise_ids);
3826
3827         for (fr = bt->frame; fr >= 0; fr--) {
3828                 func = st->frame[fr];
3829
3830                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3831                 for_each_set_bit(i, mask, 32) {
3832                         reg = &func->regs[i];
3833                         if (!reg->id || reg->type != SCALAR_VALUE)
3834                                 continue;
3835                         if (idset_push(precise_ids, reg->id))
3836                                 return -EFAULT;
3837                 }
3838
3839                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3840                 for_each_set_bit(i, mask, 64) {
3841                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3842                                 break;
3843                         if (!is_spilled_scalar_reg(&func->stack[i]))
3844                                 continue;
3845                         reg = &func->stack[i].spilled_ptr;
3846                         if (!reg->id)
3847                                 continue;
3848                         if (idset_push(precise_ids, reg->id))
3849                                 return -EFAULT;
3850                 }
3851         }
3852
3853         for (fr = 0; fr <= st->curframe; ++fr) {
3854                 func = st->frame[fr];
3855
3856                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3857                         reg = &func->regs[i];
3858                         if (!reg->id)
3859                                 continue;
3860                         if (!idset_contains(precise_ids, reg->id))
3861                                 continue;
3862                         bt_set_frame_reg(bt, fr, i);
3863                 }
3864                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3865                         if (!is_spilled_scalar_reg(&func->stack[i]))
3866                                 continue;
3867                         reg = &func->stack[i].spilled_ptr;
3868                         if (!reg->id)
3869                                 continue;
3870                         if (!idset_contains(precise_ids, reg->id))
3871                                 continue;
3872                         bt_set_frame_slot(bt, fr, i);
3873                 }
3874         }
3875
3876         return 0;
3877 }
3878
3879 /*
3880  * __mark_chain_precision() backtracks BPF program instruction sequence and
3881  * chain of verifier states making sure that register *regno* (if regno >= 0)
3882  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3883  * SCALARS, as well as any other registers and slots that contribute to
3884  * a tracked state of given registers/stack slots, depending on specific BPF
3885  * assembly instructions (see backtrack_insns() for exact instruction handling
3886  * logic). This backtracking relies on recorded jmp_history and is able to
3887  * traverse entire chain of parent states. This process ends only when all the
3888  * necessary registers/slots and their transitive dependencies are marked as
3889  * precise.
3890  *
3891  * One important and subtle aspect is that precise marks *do not matter* in
3892  * the currently verified state (current state). It is important to understand
3893  * why this is the case.
3894  *
3895  * First, note that current state is the state that is not yet "checkpointed",
3896  * i.e., it is not yet put into env->explored_states, and it has no children
3897  * states as well. It's ephemeral, and can end up either a) being discarded if
3898  * compatible explored state is found at some point or BPF_EXIT instruction is
3899  * reached or b) checkpointed and put into env->explored_states, branching out
3900  * into one or more children states.
3901  *
3902  * In the former case, precise markings in current state are completely
3903  * ignored by state comparison code (see regsafe() for details). Only
3904  * checkpointed ("old") state precise markings are important, and if old
3905  * state's register/slot is precise, regsafe() assumes current state's
3906  * register/slot as precise and checks value ranges exactly and precisely. If
3907  * states turn out to be compatible, current state's necessary precise
3908  * markings and any required parent states' precise markings are enforced
3909  * after the fact with propagate_precision() logic, after the fact. But it's
3910  * important to realize that in this case, even after marking current state
3911  * registers/slots as precise, we immediately discard current state. So what
3912  * actually matters is any of the precise markings propagated into current
3913  * state's parent states, which are always checkpointed (due to b) case above).
3914  * As such, for scenario a) it doesn't matter if current state has precise
3915  * markings set or not.
3916  *
3917  * Now, for the scenario b), checkpointing and forking into child(ren)
3918  * state(s). Note that before current state gets to checkpointing step, any
3919  * processed instruction always assumes precise SCALAR register/slot
3920  * knowledge: if precise value or range is useful to prune jump branch, BPF
3921  * verifier takes this opportunity enthusiastically. Similarly, when
3922  * register's value is used to calculate offset or memory address, exact
3923  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3924  * what we mentioned above about state comparison ignoring precise markings
3925  * during state comparison, BPF verifier ignores and also assumes precise
3926  * markings *at will* during instruction verification process. But as verifier
3927  * assumes precision, it also propagates any precision dependencies across
3928  * parent states, which are not yet finalized, so can be further restricted
3929  * based on new knowledge gained from restrictions enforced by their children
3930  * states. This is so that once those parent states are finalized, i.e., when
3931  * they have no more active children state, state comparison logic in
3932  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3933  * required for correctness.
3934  *
3935  * To build a bit more intuition, note also that once a state is checkpointed,
3936  * the path we took to get to that state is not important. This is crucial
3937  * property for state pruning. When state is checkpointed and finalized at
3938  * some instruction index, it can be correctly and safely used to "short
3939  * circuit" any *compatible* state that reaches exactly the same instruction
3940  * index. I.e., if we jumped to that instruction from a completely different
3941  * code path than original finalized state was derived from, it doesn't
3942  * matter, current state can be discarded because from that instruction
3943  * forward having a compatible state will ensure we will safely reach the
3944  * exit. States describe preconditions for further exploration, but completely
3945  * forget the history of how we got here.
3946  *
3947  * This also means that even if we needed precise SCALAR range to get to
3948  * finalized state, but from that point forward *that same* SCALAR register is
3949  * never used in a precise context (i.e., it's precise value is not needed for
3950  * correctness), it's correct and safe to mark such register as "imprecise"
3951  * (i.e., precise marking set to false). This is what we rely on when we do
3952  * not set precise marking in current state. If no child state requires
3953  * precision for any given SCALAR register, it's safe to dictate that it can
3954  * be imprecise. If any child state does require this register to be precise,
3955  * we'll mark it precise later retroactively during precise markings
3956  * propagation from child state to parent states.
3957  *
3958  * Skipping precise marking setting in current state is a mild version of
3959  * relying on the above observation. But we can utilize this property even
3960  * more aggressively by proactively forgetting any precise marking in the
3961  * current state (which we inherited from the parent state), right before we
3962  * checkpoint it and branch off into new child state. This is done by
3963  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3964  * finalized states which help in short circuiting more future states.
3965  */
3966 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3967 {
3968         struct backtrack_state *bt = &env->bt;
3969         struct bpf_verifier_state *st = env->cur_state;
3970         int first_idx = st->first_insn_idx;
3971         int last_idx = env->insn_idx;
3972         int subseq_idx = -1;
3973         struct bpf_func_state *func;
3974         struct bpf_reg_state *reg;
3975         bool skip_first = true;
3976         int i, fr, err;
3977
3978         if (!env->bpf_capable)
3979                 return 0;
3980
3981         /* set frame number from which we are starting to backtrack */
3982         bt_init(bt, env->cur_state->curframe);
3983
3984         /* Do sanity checks against current state of register and/or stack
3985          * slot, but don't set precise flag in current state, as precision
3986          * tracking in the current state is unnecessary.
3987          */
3988         func = st->frame[bt->frame];
3989         if (regno >= 0) {
3990                 reg = &func->regs[regno];
3991                 if (reg->type != SCALAR_VALUE) {
3992                         WARN_ONCE(1, "backtracing misuse");
3993                         return -EFAULT;
3994                 }
3995                 bt_set_reg(bt, regno);
3996         }
3997
3998         if (bt_empty(bt))
3999                 return 0;
4000
4001         for (;;) {
4002                 DECLARE_BITMAP(mask, 64);
4003                 u32 history = st->jmp_history_cnt;
4004
4005                 if (env->log.level & BPF_LOG_LEVEL2) {
4006                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4007                                 bt->frame, last_idx, first_idx, subseq_idx);
4008                 }
4009
4010                 /* If some register with scalar ID is marked as precise,
4011                  * make sure that all registers sharing this ID are also precise.
4012                  * This is needed to estimate effect of find_equal_scalars().
4013                  * Do this at the last instruction of each state,
4014                  * bpf_reg_state::id fields are valid for these instructions.
4015                  *
4016                  * Allows to track precision in situation like below:
4017                  *
4018                  *     r2 = unknown value
4019                  *     ...
4020                  *   --- state #0 ---
4021                  *     ...
4022                  *     r1 = r2                 // r1 and r2 now share the same ID
4023                  *     ...
4024                  *   --- state #1 {r1.id = A, r2.id = A} ---
4025                  *     ...
4026                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4027                  *     ...
4028                  *   --- state #2 {r1.id = A, r2.id = A} ---
4029                  *     r3 = r10
4030                  *     r3 += r1                // need to mark both r1 and r2
4031                  */
4032                 if (mark_precise_scalar_ids(env, st))
4033                         return -EFAULT;
4034
4035                 if (last_idx < 0) {
4036                         /* we are at the entry into subprog, which
4037                          * is expected for global funcs, but only if
4038                          * requested precise registers are R1-R5
4039                          * (which are global func's input arguments)
4040                          */
4041                         if (st->curframe == 0 &&
4042                             st->frame[0]->subprogno > 0 &&
4043                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4044                             bt_stack_mask(bt) == 0 &&
4045                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4046                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4047                                 for_each_set_bit(i, mask, 32) {
4048                                         reg = &st->frame[0]->regs[i];
4049                                         if (reg->type != SCALAR_VALUE) {
4050                                                 bt_clear_reg(bt, i);
4051                                                 continue;
4052                                         }
4053                                         reg->precise = true;
4054                                 }
4055                                 return 0;
4056                         }
4057
4058                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4059                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4060                         WARN_ONCE(1, "verifier backtracking bug");
4061                         return -EFAULT;
4062                 }
4063
4064                 for (i = last_idx;;) {
4065                         if (skip_first) {
4066                                 err = 0;
4067                                 skip_first = false;
4068                         } else {
4069                                 err = backtrack_insn(env, i, subseq_idx, bt);
4070                         }
4071                         if (err == -ENOTSUPP) {
4072                                 mark_all_scalars_precise(env, env->cur_state);
4073                                 bt_reset(bt);
4074                                 return 0;
4075                         } else if (err) {
4076                                 return err;
4077                         }
4078                         if (bt_empty(bt))
4079                                 /* Found assignment(s) into tracked register in this state.
4080                                  * Since this state is already marked, just return.
4081                                  * Nothing to be tracked further in the parent state.
4082                                  */
4083                                 return 0;
4084                         if (i == first_idx)
4085                                 break;
4086                         subseq_idx = i;
4087                         i = get_prev_insn_idx(st, i, &history);
4088                         if (i >= env->prog->len) {
4089                                 /* This can happen if backtracking reached insn 0
4090                                  * and there are still reg_mask or stack_mask
4091                                  * to backtrack.
4092                                  * It means the backtracking missed the spot where
4093                                  * particular register was initialized with a constant.
4094                                  */
4095                                 verbose(env, "BUG backtracking idx %d\n", i);
4096                                 WARN_ONCE(1, "verifier backtracking bug");
4097                                 return -EFAULT;
4098                         }
4099                 }
4100                 st = st->parent;
4101                 if (!st)
4102                         break;
4103
4104                 for (fr = bt->frame; fr >= 0; fr--) {
4105                         func = st->frame[fr];
4106                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4107                         for_each_set_bit(i, mask, 32) {
4108                                 reg = &func->regs[i];
4109                                 if (reg->type != SCALAR_VALUE) {
4110                                         bt_clear_frame_reg(bt, fr, i);
4111                                         continue;
4112                                 }
4113                                 if (reg->precise)
4114                                         bt_clear_frame_reg(bt, fr, i);
4115                                 else
4116                                         reg->precise = true;
4117                         }
4118
4119                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4120                         for_each_set_bit(i, mask, 64) {
4121                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4122                                         /* the sequence of instructions:
4123                                          * 2: (bf) r3 = r10
4124                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4125                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4126                                          * doesn't contain jmps. It's backtracked
4127                                          * as a single block.
4128                                          * During backtracking insn 3 is not recognized as
4129                                          * stack access, so at the end of backtracking
4130                                          * stack slot fp-8 is still marked in stack_mask.
4131                                          * However the parent state may not have accessed
4132                                          * fp-8 and it's "unallocated" stack space.
4133                                          * In such case fallback to conservative.
4134                                          */
4135                                         mark_all_scalars_precise(env, env->cur_state);
4136                                         bt_reset(bt);
4137                                         return 0;
4138                                 }
4139
4140                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4141                                         bt_clear_frame_slot(bt, fr, i);
4142                                         continue;
4143                                 }
4144                                 reg = &func->stack[i].spilled_ptr;
4145                                 if (reg->precise)
4146                                         bt_clear_frame_slot(bt, fr, i);
4147                                 else
4148                                         reg->precise = true;
4149                         }
4150                         if (env->log.level & BPF_LOG_LEVEL2) {
4151                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4152                                              bt_frame_reg_mask(bt, fr));
4153                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4154                                         fr, env->tmp_str_buf);
4155                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4156                                                bt_frame_stack_mask(bt, fr));
4157                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4158                                 print_verifier_state(env, func, true);
4159                         }
4160                 }
4161
4162                 if (bt_empty(bt))
4163                         return 0;
4164
4165                 subseq_idx = first_idx;
4166                 last_idx = st->last_insn_idx;
4167                 first_idx = st->first_insn_idx;
4168         }
4169
4170         /* if we still have requested precise regs or slots, we missed
4171          * something (e.g., stack access through non-r10 register), so
4172          * fallback to marking all precise
4173          */
4174         if (!bt_empty(bt)) {
4175                 mark_all_scalars_precise(env, env->cur_state);
4176                 bt_reset(bt);
4177         }
4178
4179         return 0;
4180 }
4181
4182 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4183 {
4184         return __mark_chain_precision(env, regno);
4185 }
4186
4187 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4188  * desired reg and stack masks across all relevant frames
4189  */
4190 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4191 {
4192         return __mark_chain_precision(env, -1);
4193 }
4194
4195 static bool is_spillable_regtype(enum bpf_reg_type type)
4196 {
4197         switch (base_type(type)) {
4198         case PTR_TO_MAP_VALUE:
4199         case PTR_TO_STACK:
4200         case PTR_TO_CTX:
4201         case PTR_TO_PACKET:
4202         case PTR_TO_PACKET_META:
4203         case PTR_TO_PACKET_END:
4204         case PTR_TO_FLOW_KEYS:
4205         case CONST_PTR_TO_MAP:
4206         case PTR_TO_SOCKET:
4207         case PTR_TO_SOCK_COMMON:
4208         case PTR_TO_TCP_SOCK:
4209         case PTR_TO_XDP_SOCK:
4210         case PTR_TO_BTF_ID:
4211         case PTR_TO_BUF:
4212         case PTR_TO_MEM:
4213         case PTR_TO_FUNC:
4214         case PTR_TO_MAP_KEY:
4215                 return true;
4216         default:
4217                 return false;
4218         }
4219 }
4220
4221 /* Does this register contain a constant zero? */
4222 static bool register_is_null(struct bpf_reg_state *reg)
4223 {
4224         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4225 }
4226
4227 static bool register_is_const(struct bpf_reg_state *reg)
4228 {
4229         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4230 }
4231
4232 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4233 {
4234         return tnum_is_unknown(reg->var_off) &&
4235                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4236                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4237                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4238                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4239 }
4240
4241 static bool register_is_bounded(struct bpf_reg_state *reg)
4242 {
4243         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4244 }
4245
4246 static bool __is_pointer_value(bool allow_ptr_leaks,
4247                                const struct bpf_reg_state *reg)
4248 {
4249         if (allow_ptr_leaks)
4250                 return false;
4251
4252         return reg->type != SCALAR_VALUE;
4253 }
4254
4255 /* Copy src state preserving dst->parent and dst->live fields */
4256 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4257 {
4258         struct bpf_reg_state *parent = dst->parent;
4259         enum bpf_reg_liveness live = dst->live;
4260
4261         *dst = *src;
4262         dst->parent = parent;
4263         dst->live = live;
4264 }
4265
4266 static void save_register_state(struct bpf_func_state *state,
4267                                 int spi, struct bpf_reg_state *reg,
4268                                 int size)
4269 {
4270         int i;
4271
4272         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4273         if (size == BPF_REG_SIZE)
4274                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4275
4276         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4277                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4278
4279         /* size < 8 bytes spill */
4280         for (; i; i--)
4281                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4282 }
4283
4284 static bool is_bpf_st_mem(struct bpf_insn *insn)
4285 {
4286         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4287 }
4288
4289 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4290  * stack boundary and alignment are checked in check_mem_access()
4291  */
4292 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4293                                        /* stack frame we're writing to */
4294                                        struct bpf_func_state *state,
4295                                        int off, int size, int value_regno,
4296                                        int insn_idx)
4297 {
4298         struct bpf_func_state *cur; /* state of the current function */
4299         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4300         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4301         struct bpf_reg_state *reg = NULL;
4302         u32 dst_reg = insn->dst_reg;
4303
4304         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4305         if (err)
4306                 return err;
4307         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4308          * so it's aligned access and [off, off + size) are within stack limits
4309          */
4310         if (!env->allow_ptr_leaks &&
4311             state->stack[spi].slot_type[0] == STACK_SPILL &&
4312             size != BPF_REG_SIZE) {
4313                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4314                 return -EACCES;
4315         }
4316
4317         cur = env->cur_state->frame[env->cur_state->curframe];
4318         if (value_regno >= 0)
4319                 reg = &cur->regs[value_regno];
4320         if (!env->bypass_spec_v4) {
4321                 bool sanitize = reg && is_spillable_regtype(reg->type);
4322
4323                 for (i = 0; i < size; i++) {
4324                         u8 type = state->stack[spi].slot_type[i];
4325
4326                         if (type != STACK_MISC && type != STACK_ZERO) {
4327                                 sanitize = true;
4328                                 break;
4329                         }
4330                 }
4331
4332                 if (sanitize)
4333                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4334         }
4335
4336         err = destroy_if_dynptr_stack_slot(env, state, spi);
4337         if (err)
4338                 return err;
4339
4340         mark_stack_slot_scratched(env, spi);
4341         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4342             !register_is_null(reg) && env->bpf_capable) {
4343                 if (dst_reg != BPF_REG_FP) {
4344                         /* The backtracking logic can only recognize explicit
4345                          * stack slot address like [fp - 8]. Other spill of
4346                          * scalar via different register has to be conservative.
4347                          * Backtrack from here and mark all registers as precise
4348                          * that contributed into 'reg' being a constant.
4349                          */
4350                         err = mark_chain_precision(env, value_regno);
4351                         if (err)
4352                                 return err;
4353                 }
4354                 save_register_state(state, spi, reg, size);
4355                 /* Break the relation on a narrowing spill. */
4356                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4357                         state->stack[spi].spilled_ptr.id = 0;
4358         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4359                    insn->imm != 0 && env->bpf_capable) {
4360                 struct bpf_reg_state fake_reg = {};
4361
4362                 __mark_reg_known(&fake_reg, (u32)insn->imm);
4363                 fake_reg.type = SCALAR_VALUE;
4364                 save_register_state(state, spi, &fake_reg, size);
4365         } else if (reg && is_spillable_regtype(reg->type)) {
4366                 /* register containing pointer is being spilled into stack */
4367                 if (size != BPF_REG_SIZE) {
4368                         verbose_linfo(env, insn_idx, "; ");
4369                         verbose(env, "invalid size of register spill\n");
4370                         return -EACCES;
4371                 }
4372                 if (state != cur && reg->type == PTR_TO_STACK) {
4373                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4374                         return -EINVAL;
4375                 }
4376                 save_register_state(state, spi, reg, size);
4377         } else {
4378                 u8 type = STACK_MISC;
4379
4380                 /* regular write of data into stack destroys any spilled ptr */
4381                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4382                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4383                 if (is_stack_slot_special(&state->stack[spi]))
4384                         for (i = 0; i < BPF_REG_SIZE; i++)
4385                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4386
4387                 /* only mark the slot as written if all 8 bytes were written
4388                  * otherwise read propagation may incorrectly stop too soon
4389                  * when stack slots are partially written.
4390                  * This heuristic means that read propagation will be
4391                  * conservative, since it will add reg_live_read marks
4392                  * to stack slots all the way to first state when programs
4393                  * writes+reads less than 8 bytes
4394                  */
4395                 if (size == BPF_REG_SIZE)
4396                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4397
4398                 /* when we zero initialize stack slots mark them as such */
4399                 if ((reg && register_is_null(reg)) ||
4400                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4401                         /* backtracking doesn't work for STACK_ZERO yet. */
4402                         err = mark_chain_precision(env, value_regno);
4403                         if (err)
4404                                 return err;
4405                         type = STACK_ZERO;
4406                 }
4407
4408                 /* Mark slots affected by this stack write. */
4409                 for (i = 0; i < size; i++)
4410                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4411                                 type;
4412         }
4413         return 0;
4414 }
4415
4416 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4417  * known to contain a variable offset.
4418  * This function checks whether the write is permitted and conservatively
4419  * tracks the effects of the write, considering that each stack slot in the
4420  * dynamic range is potentially written to.
4421  *
4422  * 'off' includes 'regno->off'.
4423  * 'value_regno' can be -1, meaning that an unknown value is being written to
4424  * the stack.
4425  *
4426  * Spilled pointers in range are not marked as written because we don't know
4427  * what's going to be actually written. This means that read propagation for
4428  * future reads cannot be terminated by this write.
4429  *
4430  * For privileged programs, uninitialized stack slots are considered
4431  * initialized by this write (even though we don't know exactly what offsets
4432  * are going to be written to). The idea is that we don't want the verifier to
4433  * reject future reads that access slots written to through variable offsets.
4434  */
4435 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4436                                      /* func where register points to */
4437                                      struct bpf_func_state *state,
4438                                      int ptr_regno, int off, int size,
4439                                      int value_regno, int insn_idx)
4440 {
4441         struct bpf_func_state *cur; /* state of the current function */
4442         int min_off, max_off;
4443         int i, err;
4444         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4445         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4446         bool writing_zero = false;
4447         /* set if the fact that we're writing a zero is used to let any
4448          * stack slots remain STACK_ZERO
4449          */
4450         bool zero_used = false;
4451
4452         cur = env->cur_state->frame[env->cur_state->curframe];
4453         ptr_reg = &cur->regs[ptr_regno];
4454         min_off = ptr_reg->smin_value + off;
4455         max_off = ptr_reg->smax_value + off + size;
4456         if (value_regno >= 0)
4457                 value_reg = &cur->regs[value_regno];
4458         if ((value_reg && register_is_null(value_reg)) ||
4459             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4460                 writing_zero = true;
4461
4462         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4463         if (err)
4464                 return err;
4465
4466         for (i = min_off; i < max_off; i++) {
4467                 int spi;
4468
4469                 spi = __get_spi(i);
4470                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4471                 if (err)
4472                         return err;
4473         }
4474
4475         /* Variable offset writes destroy any spilled pointers in range. */
4476         for (i = min_off; i < max_off; i++) {
4477                 u8 new_type, *stype;
4478                 int slot, spi;
4479
4480                 slot = -i - 1;
4481                 spi = slot / BPF_REG_SIZE;
4482                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4483                 mark_stack_slot_scratched(env, spi);
4484
4485                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4486                         /* Reject the write if range we may write to has not
4487                          * been initialized beforehand. If we didn't reject
4488                          * here, the ptr status would be erased below (even
4489                          * though not all slots are actually overwritten),
4490                          * possibly opening the door to leaks.
4491                          *
4492                          * We do however catch STACK_INVALID case below, and
4493                          * only allow reading possibly uninitialized memory
4494                          * later for CAP_PERFMON, as the write may not happen to
4495                          * that slot.
4496                          */
4497                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4498                                 insn_idx, i);
4499                         return -EINVAL;
4500                 }
4501
4502                 /* Erase all spilled pointers. */
4503                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4504
4505                 /* Update the slot type. */
4506                 new_type = STACK_MISC;
4507                 if (writing_zero && *stype == STACK_ZERO) {
4508                         new_type = STACK_ZERO;
4509                         zero_used = true;
4510                 }
4511                 /* If the slot is STACK_INVALID, we check whether it's OK to
4512                  * pretend that it will be initialized by this write. The slot
4513                  * might not actually be written to, and so if we mark it as
4514                  * initialized future reads might leak uninitialized memory.
4515                  * For privileged programs, we will accept such reads to slots
4516                  * that may or may not be written because, if we're reject
4517                  * them, the error would be too confusing.
4518                  */
4519                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4520                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4521                                         insn_idx, i);
4522                         return -EINVAL;
4523                 }
4524                 *stype = new_type;
4525         }
4526         if (zero_used) {
4527                 /* backtracking doesn't work for STACK_ZERO yet. */
4528                 err = mark_chain_precision(env, value_regno);
4529                 if (err)
4530                         return err;
4531         }
4532         return 0;
4533 }
4534
4535 /* When register 'dst_regno' is assigned some values from stack[min_off,
4536  * max_off), we set the register's type according to the types of the
4537  * respective stack slots. If all the stack values are known to be zeros, then
4538  * so is the destination reg. Otherwise, the register is considered to be
4539  * SCALAR. This function does not deal with register filling; the caller must
4540  * ensure that all spilled registers in the stack range have been marked as
4541  * read.
4542  */
4543 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4544                                 /* func where src register points to */
4545                                 struct bpf_func_state *ptr_state,
4546                                 int min_off, int max_off, int dst_regno)
4547 {
4548         struct bpf_verifier_state *vstate = env->cur_state;
4549         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4550         int i, slot, spi;
4551         u8 *stype;
4552         int zeros = 0;
4553
4554         for (i = min_off; i < max_off; i++) {
4555                 slot = -i - 1;
4556                 spi = slot / BPF_REG_SIZE;
4557                 mark_stack_slot_scratched(env, spi);
4558                 stype = ptr_state->stack[spi].slot_type;
4559                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4560                         break;
4561                 zeros++;
4562         }
4563         if (zeros == max_off - min_off) {
4564                 /* any access_size read into register is zero extended,
4565                  * so the whole register == const_zero
4566                  */
4567                 __mark_reg_const_zero(&state->regs[dst_regno]);
4568                 /* backtracking doesn't support STACK_ZERO yet,
4569                  * so mark it precise here, so that later
4570                  * backtracking can stop here.
4571                  * Backtracking may not need this if this register
4572                  * doesn't participate in pointer adjustment.
4573                  * Forward propagation of precise flag is not
4574                  * necessary either. This mark is only to stop
4575                  * backtracking. Any register that contributed
4576                  * to const 0 was marked precise before spill.
4577                  */
4578                 state->regs[dst_regno].precise = true;
4579         } else {
4580                 /* have read misc data from the stack */
4581                 mark_reg_unknown(env, state->regs, dst_regno);
4582         }
4583         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4584 }
4585
4586 /* Read the stack at 'off' and put the results into the register indicated by
4587  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4588  * spilled reg.
4589  *
4590  * 'dst_regno' can be -1, meaning that the read value is not going to a
4591  * register.
4592  *
4593  * The access is assumed to be within the current stack bounds.
4594  */
4595 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4596                                       /* func where src register points to */
4597                                       struct bpf_func_state *reg_state,
4598                                       int off, int size, int dst_regno)
4599 {
4600         struct bpf_verifier_state *vstate = env->cur_state;
4601         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4602         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4603         struct bpf_reg_state *reg;
4604         u8 *stype, type;
4605
4606         stype = reg_state->stack[spi].slot_type;
4607         reg = &reg_state->stack[spi].spilled_ptr;
4608
4609         mark_stack_slot_scratched(env, spi);
4610
4611         if (is_spilled_reg(&reg_state->stack[spi])) {
4612                 u8 spill_size = 1;
4613
4614                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4615                         spill_size++;
4616
4617                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4618                         if (reg->type != SCALAR_VALUE) {
4619                                 verbose_linfo(env, env->insn_idx, "; ");
4620                                 verbose(env, "invalid size of register fill\n");
4621                                 return -EACCES;
4622                         }
4623
4624                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4625                         if (dst_regno < 0)
4626                                 return 0;
4627
4628                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4629                                 /* The earlier check_reg_arg() has decided the
4630                                  * subreg_def for this insn.  Save it first.
4631                                  */
4632                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4633
4634                                 copy_register_state(&state->regs[dst_regno], reg);
4635                                 state->regs[dst_regno].subreg_def = subreg_def;
4636                         } else {
4637                                 for (i = 0; i < size; i++) {
4638                                         type = stype[(slot - i) % BPF_REG_SIZE];
4639                                         if (type == STACK_SPILL)
4640                                                 continue;
4641                                         if (type == STACK_MISC)
4642                                                 continue;
4643                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4644                                                 continue;
4645                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4646                                                 off, i, size);
4647                                         return -EACCES;
4648                                 }
4649                                 mark_reg_unknown(env, state->regs, dst_regno);
4650                         }
4651                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4652                         return 0;
4653                 }
4654
4655                 if (dst_regno >= 0) {
4656                         /* restore register state from stack */
4657                         copy_register_state(&state->regs[dst_regno], reg);
4658                         /* mark reg as written since spilled pointer state likely
4659                          * has its liveness marks cleared by is_state_visited()
4660                          * which resets stack/reg liveness for state transitions
4661                          */
4662                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4663                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4664                         /* If dst_regno==-1, the caller is asking us whether
4665                          * it is acceptable to use this value as a SCALAR_VALUE
4666                          * (e.g. for XADD).
4667                          * We must not allow unprivileged callers to do that
4668                          * with spilled pointers.
4669                          */
4670                         verbose(env, "leaking pointer from stack off %d\n",
4671                                 off);
4672                         return -EACCES;
4673                 }
4674                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4675         } else {
4676                 for (i = 0; i < size; i++) {
4677                         type = stype[(slot - i) % BPF_REG_SIZE];
4678                         if (type == STACK_MISC)
4679                                 continue;
4680                         if (type == STACK_ZERO)
4681                                 continue;
4682                         if (type == STACK_INVALID && env->allow_uninit_stack)
4683                                 continue;
4684                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4685                                 off, i, size);
4686                         return -EACCES;
4687                 }
4688                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4689                 if (dst_regno >= 0)
4690                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4691         }
4692         return 0;
4693 }
4694
4695 enum bpf_access_src {
4696         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4697         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4698 };
4699
4700 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4701                                          int regno, int off, int access_size,
4702                                          bool zero_size_allowed,
4703                                          enum bpf_access_src type,
4704                                          struct bpf_call_arg_meta *meta);
4705
4706 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4707 {
4708         return cur_regs(env) + regno;
4709 }
4710
4711 /* Read the stack at 'ptr_regno + off' and put the result into the register
4712  * 'dst_regno'.
4713  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4714  * but not its variable offset.
4715  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4716  *
4717  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4718  * filling registers (i.e. reads of spilled register cannot be detected when
4719  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4720  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4721  * offset; for a fixed offset check_stack_read_fixed_off should be used
4722  * instead.
4723  */
4724 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4725                                     int ptr_regno, int off, int size, int dst_regno)
4726 {
4727         /* The state of the source register. */
4728         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4729         struct bpf_func_state *ptr_state = func(env, reg);
4730         int err;
4731         int min_off, max_off;
4732
4733         /* Note that we pass a NULL meta, so raw access will not be permitted.
4734          */
4735         err = check_stack_range_initialized(env, ptr_regno, off, size,
4736                                             false, ACCESS_DIRECT, NULL);
4737         if (err)
4738                 return err;
4739
4740         min_off = reg->smin_value + off;
4741         max_off = reg->smax_value + off;
4742         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4743         return 0;
4744 }
4745
4746 /* check_stack_read dispatches to check_stack_read_fixed_off or
4747  * check_stack_read_var_off.
4748  *
4749  * The caller must ensure that the offset falls within the allocated stack
4750  * bounds.
4751  *
4752  * 'dst_regno' is a register which will receive the value from the stack. It
4753  * can be -1, meaning that the read value is not going to a register.
4754  */
4755 static int check_stack_read(struct bpf_verifier_env *env,
4756                             int ptr_regno, int off, int size,
4757                             int dst_regno)
4758 {
4759         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4760         struct bpf_func_state *state = func(env, reg);
4761         int err;
4762         /* Some accesses are only permitted with a static offset. */
4763         bool var_off = !tnum_is_const(reg->var_off);
4764
4765         /* The offset is required to be static when reads don't go to a
4766          * register, in order to not leak pointers (see
4767          * check_stack_read_fixed_off).
4768          */
4769         if (dst_regno < 0 && var_off) {
4770                 char tn_buf[48];
4771
4772                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4773                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4774                         tn_buf, off, size);
4775                 return -EACCES;
4776         }
4777         /* Variable offset is prohibited for unprivileged mode for simplicity
4778          * since it requires corresponding support in Spectre masking for stack
4779          * ALU. See also retrieve_ptr_limit(). The check in
4780          * check_stack_access_for_ptr_arithmetic() called by
4781          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4782          * with variable offsets, therefore no check is required here. Further,
4783          * just checking it here would be insufficient as speculative stack
4784          * writes could still lead to unsafe speculative behaviour.
4785          */
4786         if (!var_off) {
4787                 off += reg->var_off.value;
4788                 err = check_stack_read_fixed_off(env, state, off, size,
4789                                                  dst_regno);
4790         } else {
4791                 /* Variable offset stack reads need more conservative handling
4792                  * than fixed offset ones. Note that dst_regno >= 0 on this
4793                  * branch.
4794                  */
4795                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4796                                                dst_regno);
4797         }
4798         return err;
4799 }
4800
4801
4802 /* check_stack_write dispatches to check_stack_write_fixed_off or
4803  * check_stack_write_var_off.
4804  *
4805  * 'ptr_regno' is the register used as a pointer into the stack.
4806  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4807  * 'value_regno' is the register whose value we're writing to the stack. It can
4808  * be -1, meaning that we're not writing from a register.
4809  *
4810  * The caller must ensure that the offset falls within the maximum stack size.
4811  */
4812 static int check_stack_write(struct bpf_verifier_env *env,
4813                              int ptr_regno, int off, int size,
4814                              int value_regno, int insn_idx)
4815 {
4816         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4817         struct bpf_func_state *state = func(env, reg);
4818         int err;
4819
4820         if (tnum_is_const(reg->var_off)) {
4821                 off += reg->var_off.value;
4822                 err = check_stack_write_fixed_off(env, state, off, size,
4823                                                   value_regno, insn_idx);
4824         } else {
4825                 /* Variable offset stack reads need more conservative handling
4826                  * than fixed offset ones.
4827                  */
4828                 err = check_stack_write_var_off(env, state,
4829                                                 ptr_regno, off, size,
4830                                                 value_regno, insn_idx);
4831         }
4832         return err;
4833 }
4834
4835 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4836                                  int off, int size, enum bpf_access_type type)
4837 {
4838         struct bpf_reg_state *regs = cur_regs(env);
4839         struct bpf_map *map = regs[regno].map_ptr;
4840         u32 cap = bpf_map_flags_to_cap(map);
4841
4842         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4843                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4844                         map->value_size, off, size);
4845                 return -EACCES;
4846         }
4847
4848         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4849                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4850                         map->value_size, off, size);
4851                 return -EACCES;
4852         }
4853
4854         return 0;
4855 }
4856
4857 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4858 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4859                               int off, int size, u32 mem_size,
4860                               bool zero_size_allowed)
4861 {
4862         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4863         struct bpf_reg_state *reg;
4864
4865         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4866                 return 0;
4867
4868         reg = &cur_regs(env)[regno];
4869         switch (reg->type) {
4870         case PTR_TO_MAP_KEY:
4871                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4872                         mem_size, off, size);
4873                 break;
4874         case PTR_TO_MAP_VALUE:
4875                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4876                         mem_size, off, size);
4877                 break;
4878         case PTR_TO_PACKET:
4879         case PTR_TO_PACKET_META:
4880         case PTR_TO_PACKET_END:
4881                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4882                         off, size, regno, reg->id, off, mem_size);
4883                 break;
4884         case PTR_TO_MEM:
4885         default:
4886                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4887                         mem_size, off, size);
4888         }
4889
4890         return -EACCES;
4891 }
4892
4893 /* check read/write into a memory region with possible variable offset */
4894 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4895                                    int off, int size, u32 mem_size,
4896                                    bool zero_size_allowed)
4897 {
4898         struct bpf_verifier_state *vstate = env->cur_state;
4899         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4900         struct bpf_reg_state *reg = &state->regs[regno];
4901         int err;
4902
4903         /* We may have adjusted the register pointing to memory region, so we
4904          * need to try adding each of min_value and max_value to off
4905          * to make sure our theoretical access will be safe.
4906          *
4907          * The minimum value is only important with signed
4908          * comparisons where we can't assume the floor of a
4909          * value is 0.  If we are using signed variables for our
4910          * index'es we need to make sure that whatever we use
4911          * will have a set floor within our range.
4912          */
4913         if (reg->smin_value < 0 &&
4914             (reg->smin_value == S64_MIN ||
4915              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4916               reg->smin_value + off < 0)) {
4917                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4918                         regno);
4919                 return -EACCES;
4920         }
4921         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4922                                  mem_size, zero_size_allowed);
4923         if (err) {
4924                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4925                         regno);
4926                 return err;
4927         }
4928
4929         /* If we haven't set a max value then we need to bail since we can't be
4930          * sure we won't do bad things.
4931          * If reg->umax_value + off could overflow, treat that as unbounded too.
4932          */
4933         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4934                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4935                         regno);
4936                 return -EACCES;
4937         }
4938         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4939                                  mem_size, zero_size_allowed);
4940         if (err) {
4941                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4942                         regno);
4943                 return err;
4944         }
4945
4946         return 0;
4947 }
4948
4949 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4950                                const struct bpf_reg_state *reg, int regno,
4951                                bool fixed_off_ok)
4952 {
4953         /* Access to this pointer-typed register or passing it to a helper
4954          * is only allowed in its original, unmodified form.
4955          */
4956
4957         if (reg->off < 0) {
4958                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4959                         reg_type_str(env, reg->type), regno, reg->off);
4960                 return -EACCES;
4961         }
4962
4963         if (!fixed_off_ok && reg->off) {
4964                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4965                         reg_type_str(env, reg->type), regno, reg->off);
4966                 return -EACCES;
4967         }
4968
4969         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4970                 char tn_buf[48];
4971
4972                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4973                 verbose(env, "variable %s access var_off=%s disallowed\n",
4974                         reg_type_str(env, reg->type), tn_buf);
4975                 return -EACCES;
4976         }
4977
4978         return 0;
4979 }
4980
4981 int check_ptr_off_reg(struct bpf_verifier_env *env,
4982                       const struct bpf_reg_state *reg, int regno)
4983 {
4984         return __check_ptr_off_reg(env, reg, regno, false);
4985 }
4986
4987 static int map_kptr_match_type(struct bpf_verifier_env *env,
4988                                struct btf_field *kptr_field,
4989                                struct bpf_reg_state *reg, u32 regno)
4990 {
4991         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4992         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4993         const char *reg_name = "";
4994
4995         /* Only unreferenced case accepts untrusted pointers */
4996         if (kptr_field->type == BPF_KPTR_UNREF)
4997                 perm_flags |= PTR_UNTRUSTED;
4998
4999         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5000                 goto bad_type;
5001
5002         if (!btf_is_kernel(reg->btf)) {
5003                 verbose(env, "R%d must point to kernel BTF\n", regno);
5004                 return -EINVAL;
5005         }
5006         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5007         reg_name = btf_type_name(reg->btf, reg->btf_id);
5008
5009         /* For ref_ptr case, release function check should ensure we get one
5010          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5011          * normal store of unreferenced kptr, we must ensure var_off is zero.
5012          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5013          * reg->off and reg->ref_obj_id are not needed here.
5014          */
5015         if (__check_ptr_off_reg(env, reg, regno, true))
5016                 return -EACCES;
5017
5018         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5019          * we also need to take into account the reg->off.
5020          *
5021          * We want to support cases like:
5022          *
5023          * struct foo {
5024          *         struct bar br;
5025          *         struct baz bz;
5026          * };
5027          *
5028          * struct foo *v;
5029          * v = func();        // PTR_TO_BTF_ID
5030          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5031          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5032          *                    // first member type of struct after comparison fails
5033          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5034          *                    // to match type
5035          *
5036          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5037          * is zero. We must also ensure that btf_struct_ids_match does not walk
5038          * the struct to match type against first member of struct, i.e. reject
5039          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5040          * strict mode to true for type match.
5041          */
5042         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5043                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5044                                   kptr_field->type == BPF_KPTR_REF))
5045                 goto bad_type;
5046         return 0;
5047 bad_type:
5048         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5049                 reg_type_str(env, reg->type), reg_name);
5050         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5051         if (kptr_field->type == BPF_KPTR_UNREF)
5052                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5053                         targ_name);
5054         else
5055                 verbose(env, "\n");
5056         return -EINVAL;
5057 }
5058
5059 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5060  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5061  */
5062 static bool in_rcu_cs(struct bpf_verifier_env *env)
5063 {
5064         return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5065 }
5066
5067 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5068 BTF_SET_START(rcu_protected_types)
5069 BTF_ID(struct, prog_test_ref_kfunc)
5070 BTF_ID(struct, cgroup)
5071 BTF_ID(struct, bpf_cpumask)
5072 BTF_ID(struct, task_struct)
5073 BTF_SET_END(rcu_protected_types)
5074
5075 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5076 {
5077         if (!btf_is_kernel(btf))
5078                 return false;
5079         return btf_id_set_contains(&rcu_protected_types, btf_id);
5080 }
5081
5082 static bool rcu_safe_kptr(const struct btf_field *field)
5083 {
5084         const struct btf_field_kptr *kptr = &field->kptr;
5085
5086         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5087 }
5088
5089 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5090                                  int value_regno, int insn_idx,
5091                                  struct btf_field *kptr_field)
5092 {
5093         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5094         int class = BPF_CLASS(insn->code);
5095         struct bpf_reg_state *val_reg;
5096
5097         /* Things we already checked for in check_map_access and caller:
5098          *  - Reject cases where variable offset may touch kptr
5099          *  - size of access (must be BPF_DW)
5100          *  - tnum_is_const(reg->var_off)
5101          *  - kptr_field->offset == off + reg->var_off.value
5102          */
5103         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5104         if (BPF_MODE(insn->code) != BPF_MEM) {
5105                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5106                 return -EACCES;
5107         }
5108
5109         /* We only allow loading referenced kptr, since it will be marked as
5110          * untrusted, similar to unreferenced kptr.
5111          */
5112         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5113                 verbose(env, "store to referenced kptr disallowed\n");
5114                 return -EACCES;
5115         }
5116
5117         if (class == BPF_LDX) {
5118                 val_reg = reg_state(env, value_regno);
5119                 /* We can simply mark the value_regno receiving the pointer
5120                  * value from map as PTR_TO_BTF_ID, with the correct type.
5121                  */
5122                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5123                                 kptr_field->kptr.btf_id,
5124                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5125                                 PTR_MAYBE_NULL | MEM_RCU :
5126                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5127                 /* For mark_ptr_or_null_reg */
5128                 val_reg->id = ++env->id_gen;
5129         } else if (class == BPF_STX) {
5130                 val_reg = reg_state(env, value_regno);
5131                 if (!register_is_null(val_reg) &&
5132                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5133                         return -EACCES;
5134         } else if (class == BPF_ST) {
5135                 if (insn->imm) {
5136                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5137                                 kptr_field->offset);
5138                         return -EACCES;
5139                 }
5140         } else {
5141                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5142                 return -EACCES;
5143         }
5144         return 0;
5145 }
5146
5147 /* check read/write into a map element with possible variable offset */
5148 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5149                             int off, int size, bool zero_size_allowed,
5150                             enum bpf_access_src src)
5151 {
5152         struct bpf_verifier_state *vstate = env->cur_state;
5153         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5154         struct bpf_reg_state *reg = &state->regs[regno];
5155         struct bpf_map *map = reg->map_ptr;
5156         struct btf_record *rec;
5157         int err, i;
5158
5159         err = check_mem_region_access(env, regno, off, size, map->value_size,
5160                                       zero_size_allowed);
5161         if (err)
5162                 return err;
5163
5164         if (IS_ERR_OR_NULL(map->record))
5165                 return 0;
5166         rec = map->record;
5167         for (i = 0; i < rec->cnt; i++) {
5168                 struct btf_field *field = &rec->fields[i];
5169                 u32 p = field->offset;
5170
5171                 /* If any part of a field  can be touched by load/store, reject
5172                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5173                  * it is sufficient to check x1 < y2 && y1 < x2.
5174                  */
5175                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5176                     p < reg->umax_value + off + size) {
5177                         switch (field->type) {
5178                         case BPF_KPTR_UNREF:
5179                         case BPF_KPTR_REF:
5180                                 if (src != ACCESS_DIRECT) {
5181                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5182                                         return -EACCES;
5183                                 }
5184                                 if (!tnum_is_const(reg->var_off)) {
5185                                         verbose(env, "kptr access cannot have variable offset\n");
5186                                         return -EACCES;
5187                                 }
5188                                 if (p != off + reg->var_off.value) {
5189                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5190                                                 p, off + reg->var_off.value);
5191                                         return -EACCES;
5192                                 }
5193                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5194                                         verbose(env, "kptr access size must be BPF_DW\n");
5195                                         return -EACCES;
5196                                 }
5197                                 break;
5198                         default:
5199                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5200                                         btf_field_type_name(field->type));
5201                                 return -EACCES;
5202                         }
5203                 }
5204         }
5205         return 0;
5206 }
5207
5208 #define MAX_PACKET_OFF 0xffff
5209
5210 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5211                                        const struct bpf_call_arg_meta *meta,
5212                                        enum bpf_access_type t)
5213 {
5214         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5215
5216         switch (prog_type) {
5217         /* Program types only with direct read access go here! */
5218         case BPF_PROG_TYPE_LWT_IN:
5219         case BPF_PROG_TYPE_LWT_OUT:
5220         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5221         case BPF_PROG_TYPE_SK_REUSEPORT:
5222         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5223         case BPF_PROG_TYPE_CGROUP_SKB:
5224                 if (t == BPF_WRITE)
5225                         return false;
5226                 fallthrough;
5227
5228         /* Program types with direct read + write access go here! */
5229         case BPF_PROG_TYPE_SCHED_CLS:
5230         case BPF_PROG_TYPE_SCHED_ACT:
5231         case BPF_PROG_TYPE_XDP:
5232         case BPF_PROG_TYPE_LWT_XMIT:
5233         case BPF_PROG_TYPE_SK_SKB:
5234         case BPF_PROG_TYPE_SK_MSG:
5235                 if (meta)
5236                         return meta->pkt_access;
5237
5238                 env->seen_direct_write = true;
5239                 return true;
5240
5241         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5242                 if (t == BPF_WRITE)
5243                         env->seen_direct_write = true;
5244
5245                 return true;
5246
5247         default:
5248                 return false;
5249         }
5250 }
5251
5252 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5253                                int size, bool zero_size_allowed)
5254 {
5255         struct bpf_reg_state *regs = cur_regs(env);
5256         struct bpf_reg_state *reg = &regs[regno];
5257         int err;
5258
5259         /* We may have added a variable offset to the packet pointer; but any
5260          * reg->range we have comes after that.  We are only checking the fixed
5261          * offset.
5262          */
5263
5264         /* We don't allow negative numbers, because we aren't tracking enough
5265          * detail to prove they're safe.
5266          */
5267         if (reg->smin_value < 0) {
5268                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5269                         regno);
5270                 return -EACCES;
5271         }
5272
5273         err = reg->range < 0 ? -EINVAL :
5274               __check_mem_access(env, regno, off, size, reg->range,
5275                                  zero_size_allowed);
5276         if (err) {
5277                 verbose(env, "R%d offset is outside of the packet\n", regno);
5278                 return err;
5279         }
5280
5281         /* __check_mem_access has made sure "off + size - 1" is within u16.
5282          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5283          * otherwise find_good_pkt_pointers would have refused to set range info
5284          * that __check_mem_access would have rejected this pkt access.
5285          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5286          */
5287         env->prog->aux->max_pkt_offset =
5288                 max_t(u32, env->prog->aux->max_pkt_offset,
5289                       off + reg->umax_value + size - 1);
5290
5291         return err;
5292 }
5293
5294 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5295 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5296                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5297                             struct btf **btf, u32 *btf_id)
5298 {
5299         struct bpf_insn_access_aux info = {
5300                 .reg_type = *reg_type,
5301                 .log = &env->log,
5302         };
5303
5304         if (env->ops->is_valid_access &&
5305             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5306                 /* A non zero info.ctx_field_size indicates that this field is a
5307                  * candidate for later verifier transformation to load the whole
5308                  * field and then apply a mask when accessed with a narrower
5309                  * access than actual ctx access size. A zero info.ctx_field_size
5310                  * will only allow for whole field access and rejects any other
5311                  * type of narrower access.
5312                  */
5313                 *reg_type = info.reg_type;
5314
5315                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5316                         *btf = info.btf;
5317                         *btf_id = info.btf_id;
5318                 } else {
5319                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5320                 }
5321                 /* remember the offset of last byte accessed in ctx */
5322                 if (env->prog->aux->max_ctx_offset < off + size)
5323                         env->prog->aux->max_ctx_offset = off + size;
5324                 return 0;
5325         }
5326
5327         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5328         return -EACCES;
5329 }
5330
5331 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5332                                   int size)
5333 {
5334         if (size < 0 || off < 0 ||
5335             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5336                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5337                         off, size);
5338                 return -EACCES;
5339         }
5340         return 0;
5341 }
5342
5343 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5344                              u32 regno, int off, int size,
5345                              enum bpf_access_type t)
5346 {
5347         struct bpf_reg_state *regs = cur_regs(env);
5348         struct bpf_reg_state *reg = &regs[regno];
5349         struct bpf_insn_access_aux info = {};
5350         bool valid;
5351
5352         if (reg->smin_value < 0) {
5353                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5354                         regno);
5355                 return -EACCES;
5356         }
5357
5358         switch (reg->type) {
5359         case PTR_TO_SOCK_COMMON:
5360                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5361                 break;
5362         case PTR_TO_SOCKET:
5363                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5364                 break;
5365         case PTR_TO_TCP_SOCK:
5366                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5367                 break;
5368         case PTR_TO_XDP_SOCK:
5369                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5370                 break;
5371         default:
5372                 valid = false;
5373         }
5374
5375
5376         if (valid) {
5377                 env->insn_aux_data[insn_idx].ctx_field_size =
5378                         info.ctx_field_size;
5379                 return 0;
5380         }
5381
5382         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5383                 regno, reg_type_str(env, reg->type), off, size);
5384
5385         return -EACCES;
5386 }
5387
5388 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5389 {
5390         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5391 }
5392
5393 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5394 {
5395         const struct bpf_reg_state *reg = reg_state(env, regno);
5396
5397         return reg->type == PTR_TO_CTX;
5398 }
5399
5400 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5401 {
5402         const struct bpf_reg_state *reg = reg_state(env, regno);
5403
5404         return type_is_sk_pointer(reg->type);
5405 }
5406
5407 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5408 {
5409         const struct bpf_reg_state *reg = reg_state(env, regno);
5410
5411         return type_is_pkt_pointer(reg->type);
5412 }
5413
5414 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5415 {
5416         const struct bpf_reg_state *reg = reg_state(env, regno);
5417
5418         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5419         return reg->type == PTR_TO_FLOW_KEYS;
5420 }
5421
5422 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5423 #ifdef CONFIG_NET
5424         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5425         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5426         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5427 #endif
5428         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5429 };
5430
5431 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5432 {
5433         /* A referenced register is always trusted. */
5434         if (reg->ref_obj_id)
5435                 return true;
5436
5437         /* Types listed in the reg2btf_ids are always trusted */
5438         if (reg2btf_ids[base_type(reg->type)])
5439                 return true;
5440
5441         /* If a register is not referenced, it is trusted if it has the
5442          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5443          * other type modifiers may be safe, but we elect to take an opt-in
5444          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5445          * not.
5446          *
5447          * Eventually, we should make PTR_TRUSTED the single source of truth
5448          * for whether a register is trusted.
5449          */
5450         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5451                !bpf_type_has_unsafe_modifiers(reg->type);
5452 }
5453
5454 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5455 {
5456         return reg->type & MEM_RCU;
5457 }
5458
5459 static void clear_trusted_flags(enum bpf_type_flag *flag)
5460 {
5461         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5462 }
5463
5464 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5465                                    const struct bpf_reg_state *reg,
5466                                    int off, int size, bool strict)
5467 {
5468         struct tnum reg_off;
5469         int ip_align;
5470
5471         /* Byte size accesses are always allowed. */
5472         if (!strict || size == 1)
5473                 return 0;
5474
5475         /* For platforms that do not have a Kconfig enabling
5476          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5477          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5478          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5479          * to this code only in strict mode where we want to emulate
5480          * the NET_IP_ALIGN==2 checking.  Therefore use an
5481          * unconditional IP align value of '2'.
5482          */
5483         ip_align = 2;
5484
5485         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5486         if (!tnum_is_aligned(reg_off, size)) {
5487                 char tn_buf[48];
5488
5489                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5490                 verbose(env,
5491                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5492                         ip_align, tn_buf, reg->off, off, size);
5493                 return -EACCES;
5494         }
5495
5496         return 0;
5497 }
5498
5499 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5500                                        const struct bpf_reg_state *reg,
5501                                        const char *pointer_desc,
5502                                        int off, int size, bool strict)
5503 {
5504         struct tnum reg_off;
5505
5506         /* Byte size accesses are always allowed. */
5507         if (!strict || size == 1)
5508                 return 0;
5509
5510         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5511         if (!tnum_is_aligned(reg_off, size)) {
5512                 char tn_buf[48];
5513
5514                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5515                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5516                         pointer_desc, tn_buf, reg->off, off, size);
5517                 return -EACCES;
5518         }
5519
5520         return 0;
5521 }
5522
5523 static int check_ptr_alignment(struct bpf_verifier_env *env,
5524                                const struct bpf_reg_state *reg, int off,
5525                                int size, bool strict_alignment_once)
5526 {
5527         bool strict = env->strict_alignment || strict_alignment_once;
5528         const char *pointer_desc = "";
5529
5530         switch (reg->type) {
5531         case PTR_TO_PACKET:
5532         case PTR_TO_PACKET_META:
5533                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5534                  * right in front, treat it the very same way.
5535                  */
5536                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5537         case PTR_TO_FLOW_KEYS:
5538                 pointer_desc = "flow keys ";
5539                 break;
5540         case PTR_TO_MAP_KEY:
5541                 pointer_desc = "key ";
5542                 break;
5543         case PTR_TO_MAP_VALUE:
5544                 pointer_desc = "value ";
5545                 break;
5546         case PTR_TO_CTX:
5547                 pointer_desc = "context ";
5548                 break;
5549         case PTR_TO_STACK:
5550                 pointer_desc = "stack ";
5551                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5552                  * and check_stack_read_fixed_off() relies on stack accesses being
5553                  * aligned.
5554                  */
5555                 strict = true;
5556                 break;
5557         case PTR_TO_SOCKET:
5558                 pointer_desc = "sock ";
5559                 break;
5560         case PTR_TO_SOCK_COMMON:
5561                 pointer_desc = "sock_common ";
5562                 break;
5563         case PTR_TO_TCP_SOCK:
5564                 pointer_desc = "tcp_sock ";
5565                 break;
5566         case PTR_TO_XDP_SOCK:
5567                 pointer_desc = "xdp_sock ";
5568                 break;
5569         default:
5570                 break;
5571         }
5572         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5573                                            strict);
5574 }
5575
5576 static int update_stack_depth(struct bpf_verifier_env *env,
5577                               const struct bpf_func_state *func,
5578                               int off)
5579 {
5580         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5581
5582         if (stack >= -off)
5583                 return 0;
5584
5585         /* update known max for given subprogram */
5586         env->subprog_info[func->subprogno].stack_depth = -off;
5587         return 0;
5588 }
5589
5590 /* starting from main bpf function walk all instructions of the function
5591  * and recursively walk all callees that given function can call.
5592  * Ignore jump and exit insns.
5593  * Since recursion is prevented by check_cfg() this algorithm
5594  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5595  */
5596 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5597 {
5598         struct bpf_subprog_info *subprog = env->subprog_info;
5599         struct bpf_insn *insn = env->prog->insnsi;
5600         int depth = 0, frame = 0, i, subprog_end;
5601         bool tail_call_reachable = false;
5602         int ret_insn[MAX_CALL_FRAMES];
5603         int ret_prog[MAX_CALL_FRAMES];
5604         int j;
5605
5606         i = subprog[idx].start;
5607 process_func:
5608         /* protect against potential stack overflow that might happen when
5609          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5610          * depth for such case down to 256 so that the worst case scenario
5611          * would result in 8k stack size (32 which is tailcall limit * 256 =
5612          * 8k).
5613          *
5614          * To get the idea what might happen, see an example:
5615          * func1 -> sub rsp, 128
5616          *  subfunc1 -> sub rsp, 256
5617          *  tailcall1 -> add rsp, 256
5618          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5619          *   subfunc2 -> sub rsp, 64
5620          *   subfunc22 -> sub rsp, 128
5621          *   tailcall2 -> add rsp, 128
5622          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5623          *
5624          * tailcall will unwind the current stack frame but it will not get rid
5625          * of caller's stack as shown on the example above.
5626          */
5627         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5628                 verbose(env,
5629                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5630                         depth);
5631                 return -EACCES;
5632         }
5633         /* round up to 32-bytes, since this is granularity
5634          * of interpreter stack size
5635          */
5636         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5637         if (depth > MAX_BPF_STACK) {
5638                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5639                         frame + 1, depth);
5640                 return -EACCES;
5641         }
5642 continue_func:
5643         subprog_end = subprog[idx + 1].start;
5644         for (; i < subprog_end; i++) {
5645                 int next_insn, sidx;
5646
5647                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5648                         continue;
5649                 /* remember insn and function to return to */
5650                 ret_insn[frame] = i + 1;
5651                 ret_prog[frame] = idx;
5652
5653                 /* find the callee */
5654                 next_insn = i + insn[i].imm + 1;
5655                 sidx = find_subprog(env, next_insn);
5656                 if (sidx < 0) {
5657                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5658                                   next_insn);
5659                         return -EFAULT;
5660                 }
5661                 if (subprog[sidx].is_async_cb) {
5662                         if (subprog[sidx].has_tail_call) {
5663                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5664                                 return -EFAULT;
5665                         }
5666                         /* async callbacks don't increase bpf prog stack size unless called directly */
5667                         if (!bpf_pseudo_call(insn + i))
5668                                 continue;
5669                 }
5670                 i = next_insn;
5671                 idx = sidx;
5672
5673                 if (subprog[idx].has_tail_call)
5674                         tail_call_reachable = true;
5675
5676                 frame++;
5677                 if (frame >= MAX_CALL_FRAMES) {
5678                         verbose(env, "the call stack of %d frames is too deep !\n",
5679                                 frame);
5680                         return -E2BIG;
5681                 }
5682                 goto process_func;
5683         }
5684         /* if tail call got detected across bpf2bpf calls then mark each of the
5685          * currently present subprog frames as tail call reachable subprogs;
5686          * this info will be utilized by JIT so that we will be preserving the
5687          * tail call counter throughout bpf2bpf calls combined with tailcalls
5688          */
5689         if (tail_call_reachable)
5690                 for (j = 0; j < frame; j++)
5691                         subprog[ret_prog[j]].tail_call_reachable = true;
5692         if (subprog[0].tail_call_reachable)
5693                 env->prog->aux->tail_call_reachable = true;
5694
5695         /* end of for() loop means the last insn of the 'subprog'
5696          * was reached. Doesn't matter whether it was JA or EXIT
5697          */
5698         if (frame == 0)
5699                 return 0;
5700         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5701         frame--;
5702         i = ret_insn[frame];
5703         idx = ret_prog[frame];
5704         goto continue_func;
5705 }
5706
5707 static int check_max_stack_depth(struct bpf_verifier_env *env)
5708 {
5709         struct bpf_subprog_info *si = env->subprog_info;
5710         int ret;
5711
5712         for (int i = 0; i < env->subprog_cnt; i++) {
5713                 if (!i || si[i].is_async_cb) {
5714                         ret = check_max_stack_depth_subprog(env, i);
5715                         if (ret < 0)
5716                                 return ret;
5717                 }
5718                 continue;
5719         }
5720         return 0;
5721 }
5722
5723 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5724 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5725                                   const struct bpf_insn *insn, int idx)
5726 {
5727         int start = idx + insn->imm + 1, subprog;
5728
5729         subprog = find_subprog(env, start);
5730         if (subprog < 0) {
5731                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5732                           start);
5733                 return -EFAULT;
5734         }
5735         return env->subprog_info[subprog].stack_depth;
5736 }
5737 #endif
5738
5739 static int __check_buffer_access(struct bpf_verifier_env *env,
5740                                  const char *buf_info,
5741                                  const struct bpf_reg_state *reg,
5742                                  int regno, int off, int size)
5743 {
5744         if (off < 0) {
5745                 verbose(env,
5746                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5747                         regno, buf_info, off, size);
5748                 return -EACCES;
5749         }
5750         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5751                 char tn_buf[48];
5752
5753                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5754                 verbose(env,
5755                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5756                         regno, off, tn_buf);
5757                 return -EACCES;
5758         }
5759
5760         return 0;
5761 }
5762
5763 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5764                                   const struct bpf_reg_state *reg,
5765                                   int regno, int off, int size)
5766 {
5767         int err;
5768
5769         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5770         if (err)
5771                 return err;
5772
5773         if (off + size > env->prog->aux->max_tp_access)
5774                 env->prog->aux->max_tp_access = off + size;
5775
5776         return 0;
5777 }
5778
5779 static int check_buffer_access(struct bpf_verifier_env *env,
5780                                const struct bpf_reg_state *reg,
5781                                int regno, int off, int size,
5782                                bool zero_size_allowed,
5783                                u32 *max_access)
5784 {
5785         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5786         int err;
5787
5788         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5789         if (err)
5790                 return err;
5791
5792         if (off + size > *max_access)
5793                 *max_access = off + size;
5794
5795         return 0;
5796 }
5797
5798 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5799 static void zext_32_to_64(struct bpf_reg_state *reg)
5800 {
5801         reg->var_off = tnum_subreg(reg->var_off);
5802         __reg_assign_32_into_64(reg);
5803 }
5804
5805 /* truncate register to smaller size (in bytes)
5806  * must be called with size < BPF_REG_SIZE
5807  */
5808 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5809 {
5810         u64 mask;
5811
5812         /* clear high bits in bit representation */
5813         reg->var_off = tnum_cast(reg->var_off, size);
5814
5815         /* fix arithmetic bounds */
5816         mask = ((u64)1 << (size * 8)) - 1;
5817         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5818                 reg->umin_value &= mask;
5819                 reg->umax_value &= mask;
5820         } else {
5821                 reg->umin_value = 0;
5822                 reg->umax_value = mask;
5823         }
5824         reg->smin_value = reg->umin_value;
5825         reg->smax_value = reg->umax_value;
5826
5827         /* If size is smaller than 32bit register the 32bit register
5828          * values are also truncated so we push 64-bit bounds into
5829          * 32-bit bounds. Above were truncated < 32-bits already.
5830          */
5831         if (size >= 4)
5832                 return;
5833         __reg_combine_64_into_32(reg);
5834 }
5835
5836 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5837 {
5838         if (size == 1) {
5839                 reg->smin_value = reg->s32_min_value = S8_MIN;
5840                 reg->smax_value = reg->s32_max_value = S8_MAX;
5841         } else if (size == 2) {
5842                 reg->smin_value = reg->s32_min_value = S16_MIN;
5843                 reg->smax_value = reg->s32_max_value = S16_MAX;
5844         } else {
5845                 /* size == 4 */
5846                 reg->smin_value = reg->s32_min_value = S32_MIN;
5847                 reg->smax_value = reg->s32_max_value = S32_MAX;
5848         }
5849         reg->umin_value = reg->u32_min_value = 0;
5850         reg->umax_value = U64_MAX;
5851         reg->u32_max_value = U32_MAX;
5852         reg->var_off = tnum_unknown;
5853 }
5854
5855 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5856 {
5857         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5858         u64 top_smax_value, top_smin_value;
5859         u64 num_bits = size * 8;
5860
5861         if (tnum_is_const(reg->var_off)) {
5862                 u64_cval = reg->var_off.value;
5863                 if (size == 1)
5864                         reg->var_off = tnum_const((s8)u64_cval);
5865                 else if (size == 2)
5866                         reg->var_off = tnum_const((s16)u64_cval);
5867                 else
5868                         /* size == 4 */
5869                         reg->var_off = tnum_const((s32)u64_cval);
5870
5871                 u64_cval = reg->var_off.value;
5872                 reg->smax_value = reg->smin_value = u64_cval;
5873                 reg->umax_value = reg->umin_value = u64_cval;
5874                 reg->s32_max_value = reg->s32_min_value = u64_cval;
5875                 reg->u32_max_value = reg->u32_min_value = u64_cval;
5876                 return;
5877         }
5878
5879         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5880         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5881
5882         if (top_smax_value != top_smin_value)
5883                 goto out;
5884
5885         /* find the s64_min and s64_min after sign extension */
5886         if (size == 1) {
5887                 init_s64_max = (s8)reg->smax_value;
5888                 init_s64_min = (s8)reg->smin_value;
5889         } else if (size == 2) {
5890                 init_s64_max = (s16)reg->smax_value;
5891                 init_s64_min = (s16)reg->smin_value;
5892         } else {
5893                 init_s64_max = (s32)reg->smax_value;
5894                 init_s64_min = (s32)reg->smin_value;
5895         }
5896
5897         s64_max = max(init_s64_max, init_s64_min);
5898         s64_min = min(init_s64_max, init_s64_min);
5899
5900         /* both of s64_max/s64_min positive or negative */
5901         if (s64_max >= 0 == s64_min >= 0) {
5902                 reg->smin_value = reg->s32_min_value = s64_min;
5903                 reg->smax_value = reg->s32_max_value = s64_max;
5904                 reg->umin_value = reg->u32_min_value = s64_min;
5905                 reg->umax_value = reg->u32_max_value = s64_max;
5906                 reg->var_off = tnum_range(s64_min, s64_max);
5907                 return;
5908         }
5909
5910 out:
5911         set_sext64_default_val(reg, size);
5912 }
5913
5914 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5915 {
5916         if (size == 1) {
5917                 reg->s32_min_value = S8_MIN;
5918                 reg->s32_max_value = S8_MAX;
5919         } else {
5920                 /* size == 2 */
5921                 reg->s32_min_value = S16_MIN;
5922                 reg->s32_max_value = S16_MAX;
5923         }
5924         reg->u32_min_value = 0;
5925         reg->u32_max_value = U32_MAX;
5926 }
5927
5928 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5929 {
5930         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5931         u32 top_smax_value, top_smin_value;
5932         u32 num_bits = size * 8;
5933
5934         if (tnum_is_const(reg->var_off)) {
5935                 u32_val = reg->var_off.value;
5936                 if (size == 1)
5937                         reg->var_off = tnum_const((s8)u32_val);
5938                 else
5939                         reg->var_off = tnum_const((s16)u32_val);
5940
5941                 u32_val = reg->var_off.value;
5942                 reg->s32_min_value = reg->s32_max_value = u32_val;
5943                 reg->u32_min_value = reg->u32_max_value = u32_val;
5944                 return;
5945         }
5946
5947         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5948         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5949
5950         if (top_smax_value != top_smin_value)
5951                 goto out;
5952
5953         /* find the s32_min and s32_min after sign extension */
5954         if (size == 1) {
5955                 init_s32_max = (s8)reg->s32_max_value;
5956                 init_s32_min = (s8)reg->s32_min_value;
5957         } else {
5958                 /* size == 2 */
5959                 init_s32_max = (s16)reg->s32_max_value;
5960                 init_s32_min = (s16)reg->s32_min_value;
5961         }
5962         s32_max = max(init_s32_max, init_s32_min);
5963         s32_min = min(init_s32_max, init_s32_min);
5964
5965         if (s32_min >= 0 == s32_max >= 0) {
5966                 reg->s32_min_value = s32_min;
5967                 reg->s32_max_value = s32_max;
5968                 reg->u32_min_value = (u32)s32_min;
5969                 reg->u32_max_value = (u32)s32_max;
5970                 return;
5971         }
5972
5973 out:
5974         set_sext32_default_val(reg, size);
5975 }
5976
5977 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5978 {
5979         /* A map is considered read-only if the following condition are true:
5980          *
5981          * 1) BPF program side cannot change any of the map content. The
5982          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5983          *    and was set at map creation time.
5984          * 2) The map value(s) have been initialized from user space by a
5985          *    loader and then "frozen", such that no new map update/delete
5986          *    operations from syscall side are possible for the rest of
5987          *    the map's lifetime from that point onwards.
5988          * 3) Any parallel/pending map update/delete operations from syscall
5989          *    side have been completed. Only after that point, it's safe to
5990          *    assume that map value(s) are immutable.
5991          */
5992         return (map->map_flags & BPF_F_RDONLY_PROG) &&
5993                READ_ONCE(map->frozen) &&
5994                !bpf_map_write_active(map);
5995 }
5996
5997 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5998                                bool is_ldsx)
5999 {
6000         void *ptr;
6001         u64 addr;
6002         int err;
6003
6004         err = map->ops->map_direct_value_addr(map, &addr, off);
6005         if (err)
6006                 return err;
6007         ptr = (void *)(long)addr + off;
6008
6009         switch (size) {
6010         case sizeof(u8):
6011                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6012                 break;
6013         case sizeof(u16):
6014                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6015                 break;
6016         case sizeof(u32):
6017                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6018                 break;
6019         case sizeof(u64):
6020                 *val = *(u64 *)ptr;
6021                 break;
6022         default:
6023                 return -EINVAL;
6024         }
6025         return 0;
6026 }
6027
6028 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6029 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6030 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6031
6032 /*
6033  * Allow list few fields as RCU trusted or full trusted.
6034  * This logic doesn't allow mix tagging and will be removed once GCC supports
6035  * btf_type_tag.
6036  */
6037
6038 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6039 BTF_TYPE_SAFE_RCU(struct task_struct) {
6040         const cpumask_t *cpus_ptr;
6041         struct css_set __rcu *cgroups;
6042         struct task_struct __rcu *real_parent;
6043         struct task_struct *group_leader;
6044 };
6045
6046 BTF_TYPE_SAFE_RCU(struct cgroup) {
6047         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6048         struct kernfs_node *kn;
6049 };
6050
6051 BTF_TYPE_SAFE_RCU(struct css_set) {
6052         struct cgroup *dfl_cgrp;
6053 };
6054
6055 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6056 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6057         struct file __rcu *exe_file;
6058 };
6059
6060 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6061  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6062  */
6063 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6064         struct sock *sk;
6065 };
6066
6067 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6068         struct sock *sk;
6069 };
6070
6071 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6072 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6073         struct seq_file *seq;
6074 };
6075
6076 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6077         struct bpf_iter_meta *meta;
6078         struct task_struct *task;
6079 };
6080
6081 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6082         struct file *file;
6083 };
6084
6085 BTF_TYPE_SAFE_TRUSTED(struct file) {
6086         struct inode *f_inode;
6087 };
6088
6089 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6090         /* no negative dentry-s in places where bpf can see it */
6091         struct inode *d_inode;
6092 };
6093
6094 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6095         struct sock *sk;
6096 };
6097
6098 static bool type_is_rcu(struct bpf_verifier_env *env,
6099                         struct bpf_reg_state *reg,
6100                         const char *field_name, u32 btf_id)
6101 {
6102         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6103         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6104         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6105
6106         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6107 }
6108
6109 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6110                                 struct bpf_reg_state *reg,
6111                                 const char *field_name, u32 btf_id)
6112 {
6113         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6114         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6115         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6116
6117         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6118 }
6119
6120 static bool type_is_trusted(struct bpf_verifier_env *env,
6121                             struct bpf_reg_state *reg,
6122                             const char *field_name, u32 btf_id)
6123 {
6124         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6125         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6126         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6127         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6128         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6129         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6130
6131         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6132 }
6133
6134 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6135                                    struct bpf_reg_state *regs,
6136                                    int regno, int off, int size,
6137                                    enum bpf_access_type atype,
6138                                    int value_regno)
6139 {
6140         struct bpf_reg_state *reg = regs + regno;
6141         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6142         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6143         const char *field_name = NULL;
6144         enum bpf_type_flag flag = 0;
6145         u32 btf_id = 0;
6146         int ret;
6147
6148         if (!env->allow_ptr_leaks) {
6149                 verbose(env,
6150                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6151                         tname);
6152                 return -EPERM;
6153         }
6154         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6155                 verbose(env,
6156                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6157                         tname);
6158                 return -EINVAL;
6159         }
6160         if (off < 0) {
6161                 verbose(env,
6162                         "R%d is ptr_%s invalid negative access: off=%d\n",
6163                         regno, tname, off);
6164                 return -EACCES;
6165         }
6166         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6167                 char tn_buf[48];
6168
6169                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6170                 verbose(env,
6171                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6172                         regno, tname, off, tn_buf);
6173                 return -EACCES;
6174         }
6175
6176         if (reg->type & MEM_USER) {
6177                 verbose(env,
6178                         "R%d is ptr_%s access user memory: off=%d\n",
6179                         regno, tname, off);
6180                 return -EACCES;
6181         }
6182
6183         if (reg->type & MEM_PERCPU) {
6184                 verbose(env,
6185                         "R%d is ptr_%s access percpu memory: off=%d\n",
6186                         regno, tname, off);
6187                 return -EACCES;
6188         }
6189
6190         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6191                 if (!btf_is_kernel(reg->btf)) {
6192                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6193                         return -EFAULT;
6194                 }
6195                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6196         } else {
6197                 /* Writes are permitted with default btf_struct_access for
6198                  * program allocated objects (which always have ref_obj_id > 0),
6199                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6200                  */
6201                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6202                         verbose(env, "only read is supported\n");
6203                         return -EACCES;
6204                 }
6205
6206                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6207                     !reg->ref_obj_id) {
6208                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6209                         return -EFAULT;
6210                 }
6211
6212                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6213         }
6214
6215         if (ret < 0)
6216                 return ret;
6217
6218         if (ret != PTR_TO_BTF_ID) {
6219                 /* just mark; */
6220
6221         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6222                 /* If this is an untrusted pointer, all pointers formed by walking it
6223                  * also inherit the untrusted flag.
6224                  */
6225                 flag = PTR_UNTRUSTED;
6226
6227         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6228                 /* By default any pointer obtained from walking a trusted pointer is no
6229                  * longer trusted, unless the field being accessed has explicitly been
6230                  * marked as inheriting its parent's state of trust (either full or RCU).
6231                  * For example:
6232                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6233                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6234                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6235                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6236                  *
6237                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6238                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6239                  */
6240                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6241                         flag |= PTR_TRUSTED;
6242                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6243                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6244                                 /* ignore __rcu tag and mark it MEM_RCU */
6245                                 flag |= MEM_RCU;
6246                         } else if (flag & MEM_RCU ||
6247                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6248                                 /* __rcu tagged pointers can be NULL */
6249                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6250
6251                                 /* We always trust them */
6252                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6253                                     flag & PTR_UNTRUSTED)
6254                                         flag &= ~PTR_UNTRUSTED;
6255                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6256                                 /* keep as-is */
6257                         } else {
6258                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6259                                 clear_trusted_flags(&flag);
6260                         }
6261                 } else {
6262                         /*
6263                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6264                          * aggressively mark as untrusted otherwise such
6265                          * pointers will be plain PTR_TO_BTF_ID without flags
6266                          * and will be allowed to be passed into helpers for
6267                          * compat reasons.
6268                          */
6269                         flag = PTR_UNTRUSTED;
6270                 }
6271         } else {
6272                 /* Old compat. Deprecated */
6273                 clear_trusted_flags(&flag);
6274         }
6275
6276         if (atype == BPF_READ && value_regno >= 0)
6277                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6278
6279         return 0;
6280 }
6281
6282 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6283                                    struct bpf_reg_state *regs,
6284                                    int regno, int off, int size,
6285                                    enum bpf_access_type atype,
6286                                    int value_regno)
6287 {
6288         struct bpf_reg_state *reg = regs + regno;
6289         struct bpf_map *map = reg->map_ptr;
6290         struct bpf_reg_state map_reg;
6291         enum bpf_type_flag flag = 0;
6292         const struct btf_type *t;
6293         const char *tname;
6294         u32 btf_id;
6295         int ret;
6296
6297         if (!btf_vmlinux) {
6298                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6299                 return -ENOTSUPP;
6300         }
6301
6302         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6303                 verbose(env, "map_ptr access not supported for map type %d\n",
6304                         map->map_type);
6305                 return -ENOTSUPP;
6306         }
6307
6308         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6309         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6310
6311         if (!env->allow_ptr_leaks) {
6312                 verbose(env,
6313                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6314                         tname);
6315                 return -EPERM;
6316         }
6317
6318         if (off < 0) {
6319                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6320                         regno, tname, off);
6321                 return -EACCES;
6322         }
6323
6324         if (atype != BPF_READ) {
6325                 verbose(env, "only read from %s is supported\n", tname);
6326                 return -EACCES;
6327         }
6328
6329         /* Simulate access to a PTR_TO_BTF_ID */
6330         memset(&map_reg, 0, sizeof(map_reg));
6331         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6332         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6333         if (ret < 0)
6334                 return ret;
6335
6336         if (value_regno >= 0)
6337                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6338
6339         return 0;
6340 }
6341
6342 /* Check that the stack access at the given offset is within bounds. The
6343  * maximum valid offset is -1.
6344  *
6345  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6346  * -state->allocated_stack for reads.
6347  */
6348 static int check_stack_slot_within_bounds(int off,
6349                                           struct bpf_func_state *state,
6350                                           enum bpf_access_type t)
6351 {
6352         int min_valid_off;
6353
6354         if (t == BPF_WRITE)
6355                 min_valid_off = -MAX_BPF_STACK;
6356         else
6357                 min_valid_off = -state->allocated_stack;
6358
6359         if (off < min_valid_off || off > -1)
6360                 return -EACCES;
6361         return 0;
6362 }
6363
6364 /* Check that the stack access at 'regno + off' falls within the maximum stack
6365  * bounds.
6366  *
6367  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6368  */
6369 static int check_stack_access_within_bounds(
6370                 struct bpf_verifier_env *env,
6371                 int regno, int off, int access_size,
6372                 enum bpf_access_src src, enum bpf_access_type type)
6373 {
6374         struct bpf_reg_state *regs = cur_regs(env);
6375         struct bpf_reg_state *reg = regs + regno;
6376         struct bpf_func_state *state = func(env, reg);
6377         int min_off, max_off;
6378         int err;
6379         char *err_extra;
6380
6381         if (src == ACCESS_HELPER)
6382                 /* We don't know if helpers are reading or writing (or both). */
6383                 err_extra = " indirect access to";
6384         else if (type == BPF_READ)
6385                 err_extra = " read from";
6386         else
6387                 err_extra = " write to";
6388
6389         if (tnum_is_const(reg->var_off)) {
6390                 min_off = reg->var_off.value + off;
6391                 if (access_size > 0)
6392                         max_off = min_off + access_size - 1;
6393                 else
6394                         max_off = min_off;
6395         } else {
6396                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6397                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6398                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6399                                 err_extra, regno);
6400                         return -EACCES;
6401                 }
6402                 min_off = reg->smin_value + off;
6403                 if (access_size > 0)
6404                         max_off = reg->smax_value + off + access_size - 1;
6405                 else
6406                         max_off = min_off;
6407         }
6408
6409         err = check_stack_slot_within_bounds(min_off, state, type);
6410         if (!err)
6411                 err = check_stack_slot_within_bounds(max_off, state, type);
6412
6413         if (err) {
6414                 if (tnum_is_const(reg->var_off)) {
6415                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6416                                 err_extra, regno, off, access_size);
6417                 } else {
6418                         char tn_buf[48];
6419
6420                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6421                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6422                                 err_extra, regno, tn_buf, access_size);
6423                 }
6424         }
6425         return err;
6426 }
6427
6428 /* check whether memory at (regno + off) is accessible for t = (read | write)
6429  * if t==write, value_regno is a register which value is stored into memory
6430  * if t==read, value_regno is a register which will receive the value from memory
6431  * if t==write && value_regno==-1, some unknown value is stored into memory
6432  * if t==read && value_regno==-1, don't care what we read from memory
6433  */
6434 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6435                             int off, int bpf_size, enum bpf_access_type t,
6436                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6437 {
6438         struct bpf_reg_state *regs = cur_regs(env);
6439         struct bpf_reg_state *reg = regs + regno;
6440         struct bpf_func_state *state;
6441         int size, err = 0;
6442
6443         size = bpf_size_to_bytes(bpf_size);
6444         if (size < 0)
6445                 return size;
6446
6447         /* alignment checks will add in reg->off themselves */
6448         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6449         if (err)
6450                 return err;
6451
6452         /* for access checks, reg->off is just part of off */
6453         off += reg->off;
6454
6455         if (reg->type == PTR_TO_MAP_KEY) {
6456                 if (t == BPF_WRITE) {
6457                         verbose(env, "write to change key R%d not allowed\n", regno);
6458                         return -EACCES;
6459                 }
6460
6461                 err = check_mem_region_access(env, regno, off, size,
6462                                               reg->map_ptr->key_size, false);
6463                 if (err)
6464                         return err;
6465                 if (value_regno >= 0)
6466                         mark_reg_unknown(env, regs, value_regno);
6467         } else if (reg->type == PTR_TO_MAP_VALUE) {
6468                 struct btf_field *kptr_field = NULL;
6469
6470                 if (t == BPF_WRITE && value_regno >= 0 &&
6471                     is_pointer_value(env, value_regno)) {
6472                         verbose(env, "R%d leaks addr into map\n", value_regno);
6473                         return -EACCES;
6474                 }
6475                 err = check_map_access_type(env, regno, off, size, t);
6476                 if (err)
6477                         return err;
6478                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6479                 if (err)
6480                         return err;
6481                 if (tnum_is_const(reg->var_off))
6482                         kptr_field = btf_record_find(reg->map_ptr->record,
6483                                                      off + reg->var_off.value, BPF_KPTR);
6484                 if (kptr_field) {
6485                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6486                 } else if (t == BPF_READ && value_regno >= 0) {
6487                         struct bpf_map *map = reg->map_ptr;
6488
6489                         /* if map is read-only, track its contents as scalars */
6490                         if (tnum_is_const(reg->var_off) &&
6491                             bpf_map_is_rdonly(map) &&
6492                             map->ops->map_direct_value_addr) {
6493                                 int map_off = off + reg->var_off.value;
6494                                 u64 val = 0;
6495
6496                                 err = bpf_map_direct_read(map, map_off, size,
6497                                                           &val, is_ldsx);
6498                                 if (err)
6499                                         return err;
6500
6501                                 regs[value_regno].type = SCALAR_VALUE;
6502                                 __mark_reg_known(&regs[value_regno], val);
6503                         } else {
6504                                 mark_reg_unknown(env, regs, value_regno);
6505                         }
6506                 }
6507         } else if (base_type(reg->type) == PTR_TO_MEM) {
6508                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6509
6510                 if (type_may_be_null(reg->type)) {
6511                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6512                                 reg_type_str(env, reg->type));
6513                         return -EACCES;
6514                 }
6515
6516                 if (t == BPF_WRITE && rdonly_mem) {
6517                         verbose(env, "R%d cannot write into %s\n",
6518                                 regno, reg_type_str(env, reg->type));
6519                         return -EACCES;
6520                 }
6521
6522                 if (t == BPF_WRITE && value_regno >= 0 &&
6523                     is_pointer_value(env, value_regno)) {
6524                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6525                         return -EACCES;
6526                 }
6527
6528                 err = check_mem_region_access(env, regno, off, size,
6529                                               reg->mem_size, false);
6530                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6531                         mark_reg_unknown(env, regs, value_regno);
6532         } else if (reg->type == PTR_TO_CTX) {
6533                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6534                 struct btf *btf = NULL;
6535                 u32 btf_id = 0;
6536
6537                 if (t == BPF_WRITE && value_regno >= 0 &&
6538                     is_pointer_value(env, value_regno)) {
6539                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6540                         return -EACCES;
6541                 }
6542
6543                 err = check_ptr_off_reg(env, reg, regno);
6544                 if (err < 0)
6545                         return err;
6546
6547                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6548                                        &btf_id);
6549                 if (err)
6550                         verbose_linfo(env, insn_idx, "; ");
6551                 if (!err && t == BPF_READ && value_regno >= 0) {
6552                         /* ctx access returns either a scalar, or a
6553                          * PTR_TO_PACKET[_META,_END]. In the latter
6554                          * case, we know the offset is zero.
6555                          */
6556                         if (reg_type == SCALAR_VALUE) {
6557                                 mark_reg_unknown(env, regs, value_regno);
6558                         } else {
6559                                 mark_reg_known_zero(env, regs,
6560                                                     value_regno);
6561                                 if (type_may_be_null(reg_type))
6562                                         regs[value_regno].id = ++env->id_gen;
6563                                 /* A load of ctx field could have different
6564                                  * actual load size with the one encoded in the
6565                                  * insn. When the dst is PTR, it is for sure not
6566                                  * a sub-register.
6567                                  */
6568                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6569                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6570                                         regs[value_regno].btf = btf;
6571                                         regs[value_regno].btf_id = btf_id;
6572                                 }
6573                         }
6574                         regs[value_regno].type = reg_type;
6575                 }
6576
6577         } else if (reg->type == PTR_TO_STACK) {
6578                 /* Basic bounds checks. */
6579                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6580                 if (err)
6581                         return err;
6582
6583                 state = func(env, reg);
6584                 err = update_stack_depth(env, state, off);
6585                 if (err)
6586                         return err;
6587
6588                 if (t == BPF_READ)
6589                         err = check_stack_read(env, regno, off, size,
6590                                                value_regno);
6591                 else
6592                         err = check_stack_write(env, regno, off, size,
6593                                                 value_regno, insn_idx);
6594         } else if (reg_is_pkt_pointer(reg)) {
6595                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6596                         verbose(env, "cannot write into packet\n");
6597                         return -EACCES;
6598                 }
6599                 if (t == BPF_WRITE && value_regno >= 0 &&
6600                     is_pointer_value(env, value_regno)) {
6601                         verbose(env, "R%d leaks addr into packet\n",
6602                                 value_regno);
6603                         return -EACCES;
6604                 }
6605                 err = check_packet_access(env, regno, off, size, false);
6606                 if (!err && t == BPF_READ && value_regno >= 0)
6607                         mark_reg_unknown(env, regs, value_regno);
6608         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6609                 if (t == BPF_WRITE && value_regno >= 0 &&
6610                     is_pointer_value(env, value_regno)) {
6611                         verbose(env, "R%d leaks addr into flow keys\n",
6612                                 value_regno);
6613                         return -EACCES;
6614                 }
6615
6616                 err = check_flow_keys_access(env, off, size);
6617                 if (!err && t == BPF_READ && value_regno >= 0)
6618                         mark_reg_unknown(env, regs, value_regno);
6619         } else if (type_is_sk_pointer(reg->type)) {
6620                 if (t == BPF_WRITE) {
6621                         verbose(env, "R%d cannot write into %s\n",
6622                                 regno, reg_type_str(env, reg->type));
6623                         return -EACCES;
6624                 }
6625                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6626                 if (!err && value_regno >= 0)
6627                         mark_reg_unknown(env, regs, value_regno);
6628         } else if (reg->type == PTR_TO_TP_BUFFER) {
6629                 err = check_tp_buffer_access(env, reg, regno, off, size);
6630                 if (!err && t == BPF_READ && value_regno >= 0)
6631                         mark_reg_unknown(env, regs, value_regno);
6632         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6633                    !type_may_be_null(reg->type)) {
6634                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6635                                               value_regno);
6636         } else if (reg->type == CONST_PTR_TO_MAP) {
6637                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6638                                               value_regno);
6639         } else if (base_type(reg->type) == PTR_TO_BUF) {
6640                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6641                 u32 *max_access;
6642
6643                 if (rdonly_mem) {
6644                         if (t == BPF_WRITE) {
6645                                 verbose(env, "R%d cannot write into %s\n",
6646                                         regno, reg_type_str(env, reg->type));
6647                                 return -EACCES;
6648                         }
6649                         max_access = &env->prog->aux->max_rdonly_access;
6650                 } else {
6651                         max_access = &env->prog->aux->max_rdwr_access;
6652                 }
6653
6654                 err = check_buffer_access(env, reg, regno, off, size, false,
6655                                           max_access);
6656
6657                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6658                         mark_reg_unknown(env, regs, value_regno);
6659         } else {
6660                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6661                         reg_type_str(env, reg->type));
6662                 return -EACCES;
6663         }
6664
6665         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6666             regs[value_regno].type == SCALAR_VALUE) {
6667                 if (!is_ldsx)
6668                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6669                         coerce_reg_to_size(&regs[value_regno], size);
6670                 else
6671                         coerce_reg_to_size_sx(&regs[value_regno], size);
6672         }
6673         return err;
6674 }
6675
6676 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6677 {
6678         int load_reg;
6679         int err;
6680
6681         switch (insn->imm) {
6682         case BPF_ADD:
6683         case BPF_ADD | BPF_FETCH:
6684         case BPF_AND:
6685         case BPF_AND | BPF_FETCH:
6686         case BPF_OR:
6687         case BPF_OR | BPF_FETCH:
6688         case BPF_XOR:
6689         case BPF_XOR | BPF_FETCH:
6690         case BPF_XCHG:
6691         case BPF_CMPXCHG:
6692                 break;
6693         default:
6694                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6695                 return -EINVAL;
6696         }
6697
6698         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6699                 verbose(env, "invalid atomic operand size\n");
6700                 return -EINVAL;
6701         }
6702
6703         /* check src1 operand */
6704         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6705         if (err)
6706                 return err;
6707
6708         /* check src2 operand */
6709         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6710         if (err)
6711                 return err;
6712
6713         if (insn->imm == BPF_CMPXCHG) {
6714                 /* Check comparison of R0 with memory location */
6715                 const u32 aux_reg = BPF_REG_0;
6716
6717                 err = check_reg_arg(env, aux_reg, SRC_OP);
6718                 if (err)
6719                         return err;
6720
6721                 if (is_pointer_value(env, aux_reg)) {
6722                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6723                         return -EACCES;
6724                 }
6725         }
6726
6727         if (is_pointer_value(env, insn->src_reg)) {
6728                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6729                 return -EACCES;
6730         }
6731
6732         if (is_ctx_reg(env, insn->dst_reg) ||
6733             is_pkt_reg(env, insn->dst_reg) ||
6734             is_flow_key_reg(env, insn->dst_reg) ||
6735             is_sk_reg(env, insn->dst_reg)) {
6736                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6737                         insn->dst_reg,
6738                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6739                 return -EACCES;
6740         }
6741
6742         if (insn->imm & BPF_FETCH) {
6743                 if (insn->imm == BPF_CMPXCHG)
6744                         load_reg = BPF_REG_0;
6745                 else
6746                         load_reg = insn->src_reg;
6747
6748                 /* check and record load of old value */
6749                 err = check_reg_arg(env, load_reg, DST_OP);
6750                 if (err)
6751                         return err;
6752         } else {
6753                 /* This instruction accesses a memory location but doesn't
6754                  * actually load it into a register.
6755                  */
6756                 load_reg = -1;
6757         }
6758
6759         /* Check whether we can read the memory, with second call for fetch
6760          * case to simulate the register fill.
6761          */
6762         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6763                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6764         if (!err && load_reg >= 0)
6765                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6766                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6767                                        true, false);
6768         if (err)
6769                 return err;
6770
6771         /* Check whether we can write into the same memory. */
6772         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6773                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6774         if (err)
6775                 return err;
6776
6777         return 0;
6778 }
6779
6780 /* When register 'regno' is used to read the stack (either directly or through
6781  * a helper function) make sure that it's within stack boundary and, depending
6782  * on the access type, that all elements of the stack are initialized.
6783  *
6784  * 'off' includes 'regno->off', but not its dynamic part (if any).
6785  *
6786  * All registers that have been spilled on the stack in the slots within the
6787  * read offsets are marked as read.
6788  */
6789 static int check_stack_range_initialized(
6790                 struct bpf_verifier_env *env, int regno, int off,
6791                 int access_size, bool zero_size_allowed,
6792                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6793 {
6794         struct bpf_reg_state *reg = reg_state(env, regno);
6795         struct bpf_func_state *state = func(env, reg);
6796         int err, min_off, max_off, i, j, slot, spi;
6797         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6798         enum bpf_access_type bounds_check_type;
6799         /* Some accesses can write anything into the stack, others are
6800          * read-only.
6801          */
6802         bool clobber = false;
6803
6804         if (access_size == 0 && !zero_size_allowed) {
6805                 verbose(env, "invalid zero-sized read\n");
6806                 return -EACCES;
6807         }
6808
6809         if (type == ACCESS_HELPER) {
6810                 /* The bounds checks for writes are more permissive than for
6811                  * reads. However, if raw_mode is not set, we'll do extra
6812                  * checks below.
6813                  */
6814                 bounds_check_type = BPF_WRITE;
6815                 clobber = true;
6816         } else {
6817                 bounds_check_type = BPF_READ;
6818         }
6819         err = check_stack_access_within_bounds(env, regno, off, access_size,
6820                                                type, bounds_check_type);
6821         if (err)
6822                 return err;
6823
6824
6825         if (tnum_is_const(reg->var_off)) {
6826                 min_off = max_off = reg->var_off.value + off;
6827         } else {
6828                 /* Variable offset is prohibited for unprivileged mode for
6829                  * simplicity since it requires corresponding support in
6830                  * Spectre masking for stack ALU.
6831                  * See also retrieve_ptr_limit().
6832                  */
6833                 if (!env->bypass_spec_v1) {
6834                         char tn_buf[48];
6835
6836                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6837                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6838                                 regno, err_extra, tn_buf);
6839                         return -EACCES;
6840                 }
6841                 /* Only initialized buffer on stack is allowed to be accessed
6842                  * with variable offset. With uninitialized buffer it's hard to
6843                  * guarantee that whole memory is marked as initialized on
6844                  * helper return since specific bounds are unknown what may
6845                  * cause uninitialized stack leaking.
6846                  */
6847                 if (meta && meta->raw_mode)
6848                         meta = NULL;
6849
6850                 min_off = reg->smin_value + off;
6851                 max_off = reg->smax_value + off;
6852         }
6853
6854         if (meta && meta->raw_mode) {
6855                 /* Ensure we won't be overwriting dynptrs when simulating byte
6856                  * by byte access in check_helper_call using meta.access_size.
6857                  * This would be a problem if we have a helper in the future
6858                  * which takes:
6859                  *
6860                  *      helper(uninit_mem, len, dynptr)
6861                  *
6862                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6863                  * may end up writing to dynptr itself when touching memory from
6864                  * arg 1. This can be relaxed on a case by case basis for known
6865                  * safe cases, but reject due to the possibilitiy of aliasing by
6866                  * default.
6867                  */
6868                 for (i = min_off; i < max_off + access_size; i++) {
6869                         int stack_off = -i - 1;
6870
6871                         spi = __get_spi(i);
6872                         /* raw_mode may write past allocated_stack */
6873                         if (state->allocated_stack <= stack_off)
6874                                 continue;
6875                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6876                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6877                                 return -EACCES;
6878                         }
6879                 }
6880                 meta->access_size = access_size;
6881                 meta->regno = regno;
6882                 return 0;
6883         }
6884
6885         for (i = min_off; i < max_off + access_size; i++) {
6886                 u8 *stype;
6887
6888                 slot = -i - 1;
6889                 spi = slot / BPF_REG_SIZE;
6890                 if (state->allocated_stack <= slot)
6891                         goto err;
6892                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6893                 if (*stype == STACK_MISC)
6894                         goto mark;
6895                 if ((*stype == STACK_ZERO) ||
6896                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6897                         if (clobber) {
6898                                 /* helper can write anything into the stack */
6899                                 *stype = STACK_MISC;
6900                         }
6901                         goto mark;
6902                 }
6903
6904                 if (is_spilled_reg(&state->stack[spi]) &&
6905                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6906                      env->allow_ptr_leaks)) {
6907                         if (clobber) {
6908                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6909                                 for (j = 0; j < BPF_REG_SIZE; j++)
6910                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6911                         }
6912                         goto mark;
6913                 }
6914
6915 err:
6916                 if (tnum_is_const(reg->var_off)) {
6917                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6918                                 err_extra, regno, min_off, i - min_off, access_size);
6919                 } else {
6920                         char tn_buf[48];
6921
6922                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6923                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6924                                 err_extra, regno, tn_buf, i - min_off, access_size);
6925                 }
6926                 return -EACCES;
6927 mark:
6928                 /* reading any byte out of 8-byte 'spill_slot' will cause
6929                  * the whole slot to be marked as 'read'
6930                  */
6931                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6932                               state->stack[spi].spilled_ptr.parent,
6933                               REG_LIVE_READ64);
6934                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6935                  * be sure that whether stack slot is written to or not. Hence,
6936                  * we must still conservatively propagate reads upwards even if
6937                  * helper may write to the entire memory range.
6938                  */
6939         }
6940         return update_stack_depth(env, state, min_off);
6941 }
6942
6943 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6944                                    int access_size, bool zero_size_allowed,
6945                                    struct bpf_call_arg_meta *meta)
6946 {
6947         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6948         u32 *max_access;
6949
6950         switch (base_type(reg->type)) {
6951         case PTR_TO_PACKET:
6952         case PTR_TO_PACKET_META:
6953                 return check_packet_access(env, regno, reg->off, access_size,
6954                                            zero_size_allowed);
6955         case PTR_TO_MAP_KEY:
6956                 if (meta && meta->raw_mode) {
6957                         verbose(env, "R%d cannot write into %s\n", regno,
6958                                 reg_type_str(env, reg->type));
6959                         return -EACCES;
6960                 }
6961                 return check_mem_region_access(env, regno, reg->off, access_size,
6962                                                reg->map_ptr->key_size, false);
6963         case PTR_TO_MAP_VALUE:
6964                 if (check_map_access_type(env, regno, reg->off, access_size,
6965                                           meta && meta->raw_mode ? BPF_WRITE :
6966                                           BPF_READ))
6967                         return -EACCES;
6968                 return check_map_access(env, regno, reg->off, access_size,
6969                                         zero_size_allowed, ACCESS_HELPER);
6970         case PTR_TO_MEM:
6971                 if (type_is_rdonly_mem(reg->type)) {
6972                         if (meta && meta->raw_mode) {
6973                                 verbose(env, "R%d cannot write into %s\n", regno,
6974                                         reg_type_str(env, reg->type));
6975                                 return -EACCES;
6976                         }
6977                 }
6978                 return check_mem_region_access(env, regno, reg->off,
6979                                                access_size, reg->mem_size,
6980                                                zero_size_allowed);
6981         case PTR_TO_BUF:
6982                 if (type_is_rdonly_mem(reg->type)) {
6983                         if (meta && meta->raw_mode) {
6984                                 verbose(env, "R%d cannot write into %s\n", regno,
6985                                         reg_type_str(env, reg->type));
6986                                 return -EACCES;
6987                         }
6988
6989                         max_access = &env->prog->aux->max_rdonly_access;
6990                 } else {
6991                         max_access = &env->prog->aux->max_rdwr_access;
6992                 }
6993                 return check_buffer_access(env, reg, regno, reg->off,
6994                                            access_size, zero_size_allowed,
6995                                            max_access);
6996         case PTR_TO_STACK:
6997                 return check_stack_range_initialized(
6998                                 env,
6999                                 regno, reg->off, access_size,
7000                                 zero_size_allowed, ACCESS_HELPER, meta);
7001         case PTR_TO_BTF_ID:
7002                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7003                                                access_size, BPF_READ, -1);
7004         case PTR_TO_CTX:
7005                 /* in case the function doesn't know how to access the context,
7006                  * (because we are in a program of type SYSCALL for example), we
7007                  * can not statically check its size.
7008                  * Dynamically check it now.
7009                  */
7010                 if (!env->ops->convert_ctx_access) {
7011                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7012                         int offset = access_size - 1;
7013
7014                         /* Allow zero-byte read from PTR_TO_CTX */
7015                         if (access_size == 0)
7016                                 return zero_size_allowed ? 0 : -EACCES;
7017
7018                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7019                                                 atype, -1, false, false);
7020                 }
7021
7022                 fallthrough;
7023         default: /* scalar_value or invalid ptr */
7024                 /* Allow zero-byte read from NULL, regardless of pointer type */
7025                 if (zero_size_allowed && access_size == 0 &&
7026                     register_is_null(reg))
7027                         return 0;
7028
7029                 verbose(env, "R%d type=%s ", regno,
7030                         reg_type_str(env, reg->type));
7031                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7032                 return -EACCES;
7033         }
7034 }
7035
7036 static int check_mem_size_reg(struct bpf_verifier_env *env,
7037                               struct bpf_reg_state *reg, u32 regno,
7038                               bool zero_size_allowed,
7039                               struct bpf_call_arg_meta *meta)
7040 {
7041         int err;
7042
7043         /* This is used to refine r0 return value bounds for helpers
7044          * that enforce this value as an upper bound on return values.
7045          * See do_refine_retval_range() for helpers that can refine
7046          * the return value. C type of helper is u32 so we pull register
7047          * bound from umax_value however, if negative verifier errors
7048          * out. Only upper bounds can be learned because retval is an
7049          * int type and negative retvals are allowed.
7050          */
7051         meta->msize_max_value = reg->umax_value;
7052
7053         /* The register is SCALAR_VALUE; the access check
7054          * happens using its boundaries.
7055          */
7056         if (!tnum_is_const(reg->var_off))
7057                 /* For unprivileged variable accesses, disable raw
7058                  * mode so that the program is required to
7059                  * initialize all the memory that the helper could
7060                  * just partially fill up.
7061                  */
7062                 meta = NULL;
7063
7064         if (reg->smin_value < 0) {
7065                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7066                         regno);
7067                 return -EACCES;
7068         }
7069
7070         if (reg->umin_value == 0) {
7071                 err = check_helper_mem_access(env, regno - 1, 0,
7072                                               zero_size_allowed,
7073                                               meta);
7074                 if (err)
7075                         return err;
7076         }
7077
7078         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7079                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7080                         regno);
7081                 return -EACCES;
7082         }
7083         err = check_helper_mem_access(env, regno - 1,
7084                                       reg->umax_value,
7085                                       zero_size_allowed, meta);
7086         if (!err)
7087                 err = mark_chain_precision(env, regno);
7088         return err;
7089 }
7090
7091 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7092                    u32 regno, u32 mem_size)
7093 {
7094         bool may_be_null = type_may_be_null(reg->type);
7095         struct bpf_reg_state saved_reg;
7096         struct bpf_call_arg_meta meta;
7097         int err;
7098
7099         if (register_is_null(reg))
7100                 return 0;
7101
7102         memset(&meta, 0, sizeof(meta));
7103         /* Assuming that the register contains a value check if the memory
7104          * access is safe. Temporarily save and restore the register's state as
7105          * the conversion shouldn't be visible to a caller.
7106          */
7107         if (may_be_null) {
7108                 saved_reg = *reg;
7109                 mark_ptr_not_null_reg(reg);
7110         }
7111
7112         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7113         /* Check access for BPF_WRITE */
7114         meta.raw_mode = true;
7115         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7116
7117         if (may_be_null)
7118                 *reg = saved_reg;
7119
7120         return err;
7121 }
7122
7123 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7124                                     u32 regno)
7125 {
7126         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7127         bool may_be_null = type_may_be_null(mem_reg->type);
7128         struct bpf_reg_state saved_reg;
7129         struct bpf_call_arg_meta meta;
7130         int err;
7131
7132         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7133
7134         memset(&meta, 0, sizeof(meta));
7135
7136         if (may_be_null) {
7137                 saved_reg = *mem_reg;
7138                 mark_ptr_not_null_reg(mem_reg);
7139         }
7140
7141         err = check_mem_size_reg(env, reg, regno, true, &meta);
7142         /* Check access for BPF_WRITE */
7143         meta.raw_mode = true;
7144         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7145
7146         if (may_be_null)
7147                 *mem_reg = saved_reg;
7148         return err;
7149 }
7150
7151 /* Implementation details:
7152  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7153  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7154  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7155  * Two separate bpf_obj_new will also have different reg->id.
7156  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7157  * clears reg->id after value_or_null->value transition, since the verifier only
7158  * cares about the range of access to valid map value pointer and doesn't care
7159  * about actual address of the map element.
7160  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7161  * reg->id > 0 after value_or_null->value transition. By doing so
7162  * two bpf_map_lookups will be considered two different pointers that
7163  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7164  * returned from bpf_obj_new.
7165  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7166  * dead-locks.
7167  * Since only one bpf_spin_lock is allowed the checks are simpler than
7168  * reg_is_refcounted() logic. The verifier needs to remember only
7169  * one spin_lock instead of array of acquired_refs.
7170  * cur_state->active_lock remembers which map value element or allocated
7171  * object got locked and clears it after bpf_spin_unlock.
7172  */
7173 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7174                              bool is_lock)
7175 {
7176         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7177         struct bpf_verifier_state *cur = env->cur_state;
7178         bool is_const = tnum_is_const(reg->var_off);
7179         u64 val = reg->var_off.value;
7180         struct bpf_map *map = NULL;
7181         struct btf *btf = NULL;
7182         struct btf_record *rec;
7183
7184         if (!is_const) {
7185                 verbose(env,
7186                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7187                         regno);
7188                 return -EINVAL;
7189         }
7190         if (reg->type == PTR_TO_MAP_VALUE) {
7191                 map = reg->map_ptr;
7192                 if (!map->btf) {
7193                         verbose(env,
7194                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7195                                 map->name);
7196                         return -EINVAL;
7197                 }
7198         } else {
7199                 btf = reg->btf;
7200         }
7201
7202         rec = reg_btf_record(reg);
7203         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7204                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7205                         map ? map->name : "kptr");
7206                 return -EINVAL;
7207         }
7208         if (rec->spin_lock_off != val + reg->off) {
7209                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7210                         val + reg->off, rec->spin_lock_off);
7211                 return -EINVAL;
7212         }
7213         if (is_lock) {
7214                 if (cur->active_lock.ptr) {
7215                         verbose(env,
7216                                 "Locking two bpf_spin_locks are not allowed\n");
7217                         return -EINVAL;
7218                 }
7219                 if (map)
7220                         cur->active_lock.ptr = map;
7221                 else
7222                         cur->active_lock.ptr = btf;
7223                 cur->active_lock.id = reg->id;
7224         } else {
7225                 void *ptr;
7226
7227                 if (map)
7228                         ptr = map;
7229                 else
7230                         ptr = btf;
7231
7232                 if (!cur->active_lock.ptr) {
7233                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7234                         return -EINVAL;
7235                 }
7236                 if (cur->active_lock.ptr != ptr ||
7237                     cur->active_lock.id != reg->id) {
7238                         verbose(env, "bpf_spin_unlock of different lock\n");
7239                         return -EINVAL;
7240                 }
7241
7242                 invalidate_non_owning_refs(env);
7243
7244                 cur->active_lock.ptr = NULL;
7245                 cur->active_lock.id = 0;
7246         }
7247         return 0;
7248 }
7249
7250 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7251                               struct bpf_call_arg_meta *meta)
7252 {
7253         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7254         bool is_const = tnum_is_const(reg->var_off);
7255         struct bpf_map *map = reg->map_ptr;
7256         u64 val = reg->var_off.value;
7257
7258         if (!is_const) {
7259                 verbose(env,
7260                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7261                         regno);
7262                 return -EINVAL;
7263         }
7264         if (!map->btf) {
7265                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7266                         map->name);
7267                 return -EINVAL;
7268         }
7269         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7270                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7271                 return -EINVAL;
7272         }
7273         if (map->record->timer_off != val + reg->off) {
7274                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7275                         val + reg->off, map->record->timer_off);
7276                 return -EINVAL;
7277         }
7278         if (meta->map_ptr) {
7279                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7280                 return -EFAULT;
7281         }
7282         meta->map_uid = reg->map_uid;
7283         meta->map_ptr = map;
7284         return 0;
7285 }
7286
7287 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7288                              struct bpf_call_arg_meta *meta)
7289 {
7290         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7291         struct bpf_map *map_ptr = reg->map_ptr;
7292         struct btf_field *kptr_field;
7293         u32 kptr_off;
7294
7295         if (!tnum_is_const(reg->var_off)) {
7296                 verbose(env,
7297                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7298                         regno);
7299                 return -EINVAL;
7300         }
7301         if (!map_ptr->btf) {
7302                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7303                         map_ptr->name);
7304                 return -EINVAL;
7305         }
7306         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7307                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7308                 return -EINVAL;
7309         }
7310
7311         meta->map_ptr = map_ptr;
7312         kptr_off = reg->off + reg->var_off.value;
7313         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7314         if (!kptr_field) {
7315                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7316                 return -EACCES;
7317         }
7318         if (kptr_field->type != BPF_KPTR_REF) {
7319                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7320                 return -EACCES;
7321         }
7322         meta->kptr_field = kptr_field;
7323         return 0;
7324 }
7325
7326 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7327  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7328  *
7329  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7330  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7331  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7332  *
7333  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7334  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7335  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7336  * mutate the view of the dynptr and also possibly destroy it. In the latter
7337  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7338  * memory that dynptr points to.
7339  *
7340  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7341  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7342  * readonly dynptr view yet, hence only the first case is tracked and checked.
7343  *
7344  * This is consistent with how C applies the const modifier to a struct object,
7345  * where the pointer itself inside bpf_dynptr becomes const but not what it
7346  * points to.
7347  *
7348  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7349  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7350  */
7351 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7352                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7353 {
7354         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7355         int err;
7356
7357         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7358          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7359          */
7360         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7361                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7362                 return -EFAULT;
7363         }
7364
7365         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7366          *               constructing a mutable bpf_dynptr object.
7367          *
7368          *               Currently, this is only possible with PTR_TO_STACK
7369          *               pointing to a region of at least 16 bytes which doesn't
7370          *               contain an existing bpf_dynptr.
7371          *
7372          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7373          *               mutated or destroyed. However, the memory it points to
7374          *               may be mutated.
7375          *
7376          *  None       - Points to a initialized dynptr that can be mutated and
7377          *               destroyed, including mutation of the memory it points
7378          *               to.
7379          */
7380         if (arg_type & MEM_UNINIT) {
7381                 int i;
7382
7383                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7384                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7385                         return -EINVAL;
7386                 }
7387
7388                 /* we write BPF_DW bits (8 bytes) at a time */
7389                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7390                         err = check_mem_access(env, insn_idx, regno,
7391                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7392                         if (err)
7393                                 return err;
7394                 }
7395
7396                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7397         } else /* MEM_RDONLY and None case from above */ {
7398                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7399                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7400                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7401                         return -EINVAL;
7402                 }
7403
7404                 if (!is_dynptr_reg_valid_init(env, reg)) {
7405                         verbose(env,
7406                                 "Expected an initialized dynptr as arg #%d\n",
7407                                 regno);
7408                         return -EINVAL;
7409                 }
7410
7411                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7412                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7413                         verbose(env,
7414                                 "Expected a dynptr of type %s as arg #%d\n",
7415                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7416                         return -EINVAL;
7417                 }
7418
7419                 err = mark_dynptr_read(env, reg);
7420         }
7421         return err;
7422 }
7423
7424 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7425 {
7426         struct bpf_func_state *state = func(env, reg);
7427
7428         return state->stack[spi].spilled_ptr.ref_obj_id;
7429 }
7430
7431 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7432 {
7433         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7434 }
7435
7436 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7437 {
7438         return meta->kfunc_flags & KF_ITER_NEW;
7439 }
7440
7441 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7442 {
7443         return meta->kfunc_flags & KF_ITER_NEXT;
7444 }
7445
7446 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7447 {
7448         return meta->kfunc_flags & KF_ITER_DESTROY;
7449 }
7450
7451 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7452 {
7453         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7454          * kfunc is iter state pointer
7455          */
7456         return arg == 0 && is_iter_kfunc(meta);
7457 }
7458
7459 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7460                             struct bpf_kfunc_call_arg_meta *meta)
7461 {
7462         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7463         const struct btf_type *t;
7464         const struct btf_param *arg;
7465         int spi, err, i, nr_slots;
7466         u32 btf_id;
7467
7468         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7469         arg = &btf_params(meta->func_proto)[0];
7470         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7471         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7472         nr_slots = t->size / BPF_REG_SIZE;
7473
7474         if (is_iter_new_kfunc(meta)) {
7475                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7476                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7477                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7478                                 iter_type_str(meta->btf, btf_id), regno);
7479                         return -EINVAL;
7480                 }
7481
7482                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7483                         err = check_mem_access(env, insn_idx, regno,
7484                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7485                         if (err)
7486                                 return err;
7487                 }
7488
7489                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7490                 if (err)
7491                         return err;
7492         } else {
7493                 /* iter_next() or iter_destroy() expect initialized iter state*/
7494                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7495                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7496                                 iter_type_str(meta->btf, btf_id), regno);
7497                         return -EINVAL;
7498                 }
7499
7500                 spi = iter_get_spi(env, reg, nr_slots);
7501                 if (spi < 0)
7502                         return spi;
7503
7504                 err = mark_iter_read(env, reg, spi, nr_slots);
7505                 if (err)
7506                         return err;
7507
7508                 /* remember meta->iter info for process_iter_next_call() */
7509                 meta->iter.spi = spi;
7510                 meta->iter.frameno = reg->frameno;
7511                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7512
7513                 if (is_iter_destroy_kfunc(meta)) {
7514                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7515                         if (err)
7516                                 return err;
7517                 }
7518         }
7519
7520         return 0;
7521 }
7522
7523 /* process_iter_next_call() is called when verifier gets to iterator's next
7524  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7525  * to it as just "iter_next()" in comments below.
7526  *
7527  * BPF verifier relies on a crucial contract for any iter_next()
7528  * implementation: it should *eventually* return NULL, and once that happens
7529  * it should keep returning NULL. That is, once iterator exhausts elements to
7530  * iterate, it should never reset or spuriously return new elements.
7531  *
7532  * With the assumption of such contract, process_iter_next_call() simulates
7533  * a fork in the verifier state to validate loop logic correctness and safety
7534  * without having to simulate infinite amount of iterations.
7535  *
7536  * In current state, we first assume that iter_next() returned NULL and
7537  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7538  * conditions we should not form an infinite loop and should eventually reach
7539  * exit.
7540  *
7541  * Besides that, we also fork current state and enqueue it for later
7542  * verification. In a forked state we keep iterator state as ACTIVE
7543  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7544  * also bump iteration depth to prevent erroneous infinite loop detection
7545  * later on (see iter_active_depths_differ() comment for details). In this
7546  * state we assume that we'll eventually loop back to another iter_next()
7547  * calls (it could be in exactly same location or in some other instruction,
7548  * it doesn't matter, we don't make any unnecessary assumptions about this,
7549  * everything revolves around iterator state in a stack slot, not which
7550  * instruction is calling iter_next()). When that happens, we either will come
7551  * to iter_next() with equivalent state and can conclude that next iteration
7552  * will proceed in exactly the same way as we just verified, so it's safe to
7553  * assume that loop converges. If not, we'll go on another iteration
7554  * simulation with a different input state, until all possible starting states
7555  * are validated or we reach maximum number of instructions limit.
7556  *
7557  * This way, we will either exhaustively discover all possible input states
7558  * that iterator loop can start with and eventually will converge, or we'll
7559  * effectively regress into bounded loop simulation logic and either reach
7560  * maximum number of instructions if loop is not provably convergent, or there
7561  * is some statically known limit on number of iterations (e.g., if there is
7562  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7563  *
7564  * One very subtle but very important aspect is that we *always* simulate NULL
7565  * condition first (as the current state) before we simulate non-NULL case.
7566  * This has to do with intricacies of scalar precision tracking. By simulating
7567  * "exit condition" of iter_next() returning NULL first, we make sure all the
7568  * relevant precision marks *that will be set **after** we exit iterator loop*
7569  * are propagated backwards to common parent state of NULL and non-NULL
7570  * branches. Thanks to that, state equivalence checks done later in forked
7571  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7572  * precision marks are finalized and won't change. Because simulating another
7573  * ACTIVE iterator iteration won't change them (because given same input
7574  * states we'll end up with exactly same output states which we are currently
7575  * comparing; and verification after the loop already propagated back what
7576  * needs to be **additionally** tracked as precise). It's subtle, grok
7577  * precision tracking for more intuitive understanding.
7578  */
7579 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7580                                   struct bpf_kfunc_call_arg_meta *meta)
7581 {
7582         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7583         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7584         struct bpf_reg_state *cur_iter, *queued_iter;
7585         int iter_frameno = meta->iter.frameno;
7586         int iter_spi = meta->iter.spi;
7587
7588         BTF_TYPE_EMIT(struct bpf_iter);
7589
7590         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7591
7592         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7593             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7594                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7595                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7596                 return -EFAULT;
7597         }
7598
7599         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7600                 /* branch out active iter state */
7601                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7602                 if (!queued_st)
7603                         return -ENOMEM;
7604
7605                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7606                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7607                 queued_iter->iter.depth++;
7608
7609                 queued_fr = queued_st->frame[queued_st->curframe];
7610                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7611         }
7612
7613         /* switch to DRAINED state, but keep the depth unchanged */
7614         /* mark current iter state as drained and assume returned NULL */
7615         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7616         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7617
7618         return 0;
7619 }
7620
7621 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7622 {
7623         return type == ARG_CONST_SIZE ||
7624                type == ARG_CONST_SIZE_OR_ZERO;
7625 }
7626
7627 static bool arg_type_is_release(enum bpf_arg_type type)
7628 {
7629         return type & OBJ_RELEASE;
7630 }
7631
7632 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7633 {
7634         return base_type(type) == ARG_PTR_TO_DYNPTR;
7635 }
7636
7637 static int int_ptr_type_to_size(enum bpf_arg_type type)
7638 {
7639         if (type == ARG_PTR_TO_INT)
7640                 return sizeof(u32);
7641         else if (type == ARG_PTR_TO_LONG)
7642                 return sizeof(u64);
7643
7644         return -EINVAL;
7645 }
7646
7647 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7648                                  const struct bpf_call_arg_meta *meta,
7649                                  enum bpf_arg_type *arg_type)
7650 {
7651         if (!meta->map_ptr) {
7652                 /* kernel subsystem misconfigured verifier */
7653                 verbose(env, "invalid map_ptr to access map->type\n");
7654                 return -EACCES;
7655         }
7656
7657         switch (meta->map_ptr->map_type) {
7658         case BPF_MAP_TYPE_SOCKMAP:
7659         case BPF_MAP_TYPE_SOCKHASH:
7660                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7661                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7662                 } else {
7663                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7664                         return -EINVAL;
7665                 }
7666                 break;
7667         case BPF_MAP_TYPE_BLOOM_FILTER:
7668                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7669                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7670                 break;
7671         default:
7672                 break;
7673         }
7674         return 0;
7675 }
7676
7677 struct bpf_reg_types {
7678         const enum bpf_reg_type types[10];
7679         u32 *btf_id;
7680 };
7681
7682 static const struct bpf_reg_types sock_types = {
7683         .types = {
7684                 PTR_TO_SOCK_COMMON,
7685                 PTR_TO_SOCKET,
7686                 PTR_TO_TCP_SOCK,
7687                 PTR_TO_XDP_SOCK,
7688         },
7689 };
7690
7691 #ifdef CONFIG_NET
7692 static const struct bpf_reg_types btf_id_sock_common_types = {
7693         .types = {
7694                 PTR_TO_SOCK_COMMON,
7695                 PTR_TO_SOCKET,
7696                 PTR_TO_TCP_SOCK,
7697                 PTR_TO_XDP_SOCK,
7698                 PTR_TO_BTF_ID,
7699                 PTR_TO_BTF_ID | PTR_TRUSTED,
7700         },
7701         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7702 };
7703 #endif
7704
7705 static const struct bpf_reg_types mem_types = {
7706         .types = {
7707                 PTR_TO_STACK,
7708                 PTR_TO_PACKET,
7709                 PTR_TO_PACKET_META,
7710                 PTR_TO_MAP_KEY,
7711                 PTR_TO_MAP_VALUE,
7712                 PTR_TO_MEM,
7713                 PTR_TO_MEM | MEM_RINGBUF,
7714                 PTR_TO_BUF,
7715                 PTR_TO_BTF_ID | PTR_TRUSTED,
7716         },
7717 };
7718
7719 static const struct bpf_reg_types int_ptr_types = {
7720         .types = {
7721                 PTR_TO_STACK,
7722                 PTR_TO_PACKET,
7723                 PTR_TO_PACKET_META,
7724                 PTR_TO_MAP_KEY,
7725                 PTR_TO_MAP_VALUE,
7726         },
7727 };
7728
7729 static const struct bpf_reg_types spin_lock_types = {
7730         .types = {
7731                 PTR_TO_MAP_VALUE,
7732                 PTR_TO_BTF_ID | MEM_ALLOC,
7733         }
7734 };
7735
7736 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7737 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7738 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7739 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7740 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7741 static const struct bpf_reg_types btf_ptr_types = {
7742         .types = {
7743                 PTR_TO_BTF_ID,
7744                 PTR_TO_BTF_ID | PTR_TRUSTED,
7745                 PTR_TO_BTF_ID | MEM_RCU,
7746         },
7747 };
7748 static const struct bpf_reg_types percpu_btf_ptr_types = {
7749         .types = {
7750                 PTR_TO_BTF_ID | MEM_PERCPU,
7751                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7752         }
7753 };
7754 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7755 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7756 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7757 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7758 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7759 static const struct bpf_reg_types dynptr_types = {
7760         .types = {
7761                 PTR_TO_STACK,
7762                 CONST_PTR_TO_DYNPTR,
7763         }
7764 };
7765
7766 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7767         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7768         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7769         [ARG_CONST_SIZE]                = &scalar_types,
7770         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7771         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7772         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7773         [ARG_PTR_TO_CTX]                = &context_types,
7774         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7775 #ifdef CONFIG_NET
7776         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7777 #endif
7778         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7779         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7780         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7781         [ARG_PTR_TO_MEM]                = &mem_types,
7782         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7783         [ARG_PTR_TO_INT]                = &int_ptr_types,
7784         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7785         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7786         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7787         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7788         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7789         [ARG_PTR_TO_TIMER]              = &timer_types,
7790         [ARG_PTR_TO_KPTR]               = &kptr_types,
7791         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7792 };
7793
7794 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7795                           enum bpf_arg_type arg_type,
7796                           const u32 *arg_btf_id,
7797                           struct bpf_call_arg_meta *meta)
7798 {
7799         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7800         enum bpf_reg_type expected, type = reg->type;
7801         const struct bpf_reg_types *compatible;
7802         int i, j;
7803
7804         compatible = compatible_reg_types[base_type(arg_type)];
7805         if (!compatible) {
7806                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7807                 return -EFAULT;
7808         }
7809
7810         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7811          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7812          *
7813          * Same for MAYBE_NULL:
7814          *
7815          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7816          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7817          *
7818          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7819          *
7820          * Therefore we fold these flags depending on the arg_type before comparison.
7821          */
7822         if (arg_type & MEM_RDONLY)
7823                 type &= ~MEM_RDONLY;
7824         if (arg_type & PTR_MAYBE_NULL)
7825                 type &= ~PTR_MAYBE_NULL;
7826         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7827                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7828
7829         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7830                 type &= ~MEM_ALLOC;
7831
7832         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7833                 expected = compatible->types[i];
7834                 if (expected == NOT_INIT)
7835                         break;
7836
7837                 if (type == expected)
7838                         goto found;
7839         }
7840
7841         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7842         for (j = 0; j + 1 < i; j++)
7843                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7844         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7845         return -EACCES;
7846
7847 found:
7848         if (base_type(reg->type) != PTR_TO_BTF_ID)
7849                 return 0;
7850
7851         if (compatible == &mem_types) {
7852                 if (!(arg_type & MEM_RDONLY)) {
7853                         verbose(env,
7854                                 "%s() may write into memory pointed by R%d type=%s\n",
7855                                 func_id_name(meta->func_id),
7856                                 regno, reg_type_str(env, reg->type));
7857                         return -EACCES;
7858                 }
7859                 return 0;
7860         }
7861
7862         switch ((int)reg->type) {
7863         case PTR_TO_BTF_ID:
7864         case PTR_TO_BTF_ID | PTR_TRUSTED:
7865         case PTR_TO_BTF_ID | MEM_RCU:
7866         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7867         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7868         {
7869                 /* For bpf_sk_release, it needs to match against first member
7870                  * 'struct sock_common', hence make an exception for it. This
7871                  * allows bpf_sk_release to work for multiple socket types.
7872                  */
7873                 bool strict_type_match = arg_type_is_release(arg_type) &&
7874                                          meta->func_id != BPF_FUNC_sk_release;
7875
7876                 if (type_may_be_null(reg->type) &&
7877                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7878                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7879                         return -EACCES;
7880                 }
7881
7882                 if (!arg_btf_id) {
7883                         if (!compatible->btf_id) {
7884                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7885                                 return -EFAULT;
7886                         }
7887                         arg_btf_id = compatible->btf_id;
7888                 }
7889
7890                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7891                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7892                                 return -EACCES;
7893                 } else {
7894                         if (arg_btf_id == BPF_PTR_POISON) {
7895                                 verbose(env, "verifier internal error:");
7896                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7897                                         regno);
7898                                 return -EACCES;
7899                         }
7900
7901                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7902                                                   btf_vmlinux, *arg_btf_id,
7903                                                   strict_type_match)) {
7904                                 verbose(env, "R%d is of type %s but %s is expected\n",
7905                                         regno, btf_type_name(reg->btf, reg->btf_id),
7906                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7907                                 return -EACCES;
7908                         }
7909                 }
7910                 break;
7911         }
7912         case PTR_TO_BTF_ID | MEM_ALLOC:
7913                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7914                     meta->func_id != BPF_FUNC_kptr_xchg) {
7915                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7916                         return -EFAULT;
7917                 }
7918                 /* Handled by helper specific checks */
7919                 break;
7920         case PTR_TO_BTF_ID | MEM_PERCPU:
7921         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7922                 /* Handled by helper specific checks */
7923                 break;
7924         default:
7925                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7926                 return -EFAULT;
7927         }
7928         return 0;
7929 }
7930
7931 static struct btf_field *
7932 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7933 {
7934         struct btf_field *field;
7935         struct btf_record *rec;
7936
7937         rec = reg_btf_record(reg);
7938         if (!rec)
7939                 return NULL;
7940
7941         field = btf_record_find(rec, off, fields);
7942         if (!field)
7943                 return NULL;
7944
7945         return field;
7946 }
7947
7948 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7949                            const struct bpf_reg_state *reg, int regno,
7950                            enum bpf_arg_type arg_type)
7951 {
7952         u32 type = reg->type;
7953
7954         /* When referenced register is passed to release function, its fixed
7955          * offset must be 0.
7956          *
7957          * We will check arg_type_is_release reg has ref_obj_id when storing
7958          * meta->release_regno.
7959          */
7960         if (arg_type_is_release(arg_type)) {
7961                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7962                  * may not directly point to the object being released, but to
7963                  * dynptr pointing to such object, which might be at some offset
7964                  * on the stack. In that case, we simply to fallback to the
7965                  * default handling.
7966                  */
7967                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7968                         return 0;
7969
7970                 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7971                         if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7972                                 return __check_ptr_off_reg(env, reg, regno, true);
7973
7974                         verbose(env, "R%d must have zero offset when passed to release func\n",
7975                                 regno);
7976                         verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7977                                 btf_type_name(reg->btf, reg->btf_id), reg->off);
7978                         return -EINVAL;
7979                 }
7980
7981                 /* Doing check_ptr_off_reg check for the offset will catch this
7982                  * because fixed_off_ok is false, but checking here allows us
7983                  * to give the user a better error message.
7984                  */
7985                 if (reg->off) {
7986                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7987                                 regno);
7988                         return -EINVAL;
7989                 }
7990                 return __check_ptr_off_reg(env, reg, regno, false);
7991         }
7992
7993         switch (type) {
7994         /* Pointer types where both fixed and variable offset is explicitly allowed: */
7995         case PTR_TO_STACK:
7996         case PTR_TO_PACKET:
7997         case PTR_TO_PACKET_META:
7998         case PTR_TO_MAP_KEY:
7999         case PTR_TO_MAP_VALUE:
8000         case PTR_TO_MEM:
8001         case PTR_TO_MEM | MEM_RDONLY:
8002         case PTR_TO_MEM | MEM_RINGBUF:
8003         case PTR_TO_BUF:
8004         case PTR_TO_BUF | MEM_RDONLY:
8005         case SCALAR_VALUE:
8006                 return 0;
8007         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8008          * fixed offset.
8009          */
8010         case PTR_TO_BTF_ID:
8011         case PTR_TO_BTF_ID | MEM_ALLOC:
8012         case PTR_TO_BTF_ID | PTR_TRUSTED:
8013         case PTR_TO_BTF_ID | MEM_RCU:
8014         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8015                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8016                  * its fixed offset must be 0. In the other cases, fixed offset
8017                  * can be non-zero. This was already checked above. So pass
8018                  * fixed_off_ok as true to allow fixed offset for all other
8019                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8020                  * still need to do checks instead of returning.
8021                  */
8022                 return __check_ptr_off_reg(env, reg, regno, true);
8023         default:
8024                 return __check_ptr_off_reg(env, reg, regno, false);
8025         }
8026 }
8027
8028 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8029                                                 const struct bpf_func_proto *fn,
8030                                                 struct bpf_reg_state *regs)
8031 {
8032         struct bpf_reg_state *state = NULL;
8033         int i;
8034
8035         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8036                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8037                         if (state) {
8038                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8039                                 return NULL;
8040                         }
8041                         state = &regs[BPF_REG_1 + i];
8042                 }
8043
8044         if (!state)
8045                 verbose(env, "verifier internal error: no dynptr arg found\n");
8046
8047         return state;
8048 }
8049
8050 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8051 {
8052         struct bpf_func_state *state = func(env, reg);
8053         int spi;
8054
8055         if (reg->type == CONST_PTR_TO_DYNPTR)
8056                 return reg->id;
8057         spi = dynptr_get_spi(env, reg);
8058         if (spi < 0)
8059                 return spi;
8060         return state->stack[spi].spilled_ptr.id;
8061 }
8062
8063 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8064 {
8065         struct bpf_func_state *state = func(env, reg);
8066         int spi;
8067
8068         if (reg->type == CONST_PTR_TO_DYNPTR)
8069                 return reg->ref_obj_id;
8070         spi = dynptr_get_spi(env, reg);
8071         if (spi < 0)
8072                 return spi;
8073         return state->stack[spi].spilled_ptr.ref_obj_id;
8074 }
8075
8076 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8077                                             struct bpf_reg_state *reg)
8078 {
8079         struct bpf_func_state *state = func(env, reg);
8080         int spi;
8081
8082         if (reg->type == CONST_PTR_TO_DYNPTR)
8083                 return reg->dynptr.type;
8084
8085         spi = __get_spi(reg->off);
8086         if (spi < 0) {
8087                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8088                 return BPF_DYNPTR_TYPE_INVALID;
8089         }
8090
8091         return state->stack[spi].spilled_ptr.dynptr.type;
8092 }
8093
8094 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8095                           struct bpf_call_arg_meta *meta,
8096                           const struct bpf_func_proto *fn,
8097                           int insn_idx)
8098 {
8099         u32 regno = BPF_REG_1 + arg;
8100         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8101         enum bpf_arg_type arg_type = fn->arg_type[arg];
8102         enum bpf_reg_type type = reg->type;
8103         u32 *arg_btf_id = NULL;
8104         int err = 0;
8105
8106         if (arg_type == ARG_DONTCARE)
8107                 return 0;
8108
8109         err = check_reg_arg(env, regno, SRC_OP);
8110         if (err)
8111                 return err;
8112
8113         if (arg_type == ARG_ANYTHING) {
8114                 if (is_pointer_value(env, regno)) {
8115                         verbose(env, "R%d leaks addr into helper function\n",
8116                                 regno);
8117                         return -EACCES;
8118                 }
8119                 return 0;
8120         }
8121
8122         if (type_is_pkt_pointer(type) &&
8123             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8124                 verbose(env, "helper access to the packet is not allowed\n");
8125                 return -EACCES;
8126         }
8127
8128         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8129                 err = resolve_map_arg_type(env, meta, &arg_type);
8130                 if (err)
8131                         return err;
8132         }
8133
8134         if (register_is_null(reg) && type_may_be_null(arg_type))
8135                 /* A NULL register has a SCALAR_VALUE type, so skip
8136                  * type checking.
8137                  */
8138                 goto skip_type_check;
8139
8140         /* arg_btf_id and arg_size are in a union. */
8141         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8142             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8143                 arg_btf_id = fn->arg_btf_id[arg];
8144
8145         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8146         if (err)
8147                 return err;
8148
8149         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8150         if (err)
8151                 return err;
8152
8153 skip_type_check:
8154         if (arg_type_is_release(arg_type)) {
8155                 if (arg_type_is_dynptr(arg_type)) {
8156                         struct bpf_func_state *state = func(env, reg);
8157                         int spi;
8158
8159                         /* Only dynptr created on stack can be released, thus
8160                          * the get_spi and stack state checks for spilled_ptr
8161                          * should only be done before process_dynptr_func for
8162                          * PTR_TO_STACK.
8163                          */
8164                         if (reg->type == PTR_TO_STACK) {
8165                                 spi = dynptr_get_spi(env, reg);
8166                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8167                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8168                                         return -EINVAL;
8169                                 }
8170                         } else {
8171                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8172                                 return -EINVAL;
8173                         }
8174                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8175                         verbose(env, "R%d must be referenced when passed to release function\n",
8176                                 regno);
8177                         return -EINVAL;
8178                 }
8179                 if (meta->release_regno) {
8180                         verbose(env, "verifier internal error: more than one release argument\n");
8181                         return -EFAULT;
8182                 }
8183                 meta->release_regno = regno;
8184         }
8185
8186         if (reg->ref_obj_id) {
8187                 if (meta->ref_obj_id) {
8188                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8189                                 regno, reg->ref_obj_id,
8190                                 meta->ref_obj_id);
8191                         return -EFAULT;
8192                 }
8193                 meta->ref_obj_id = reg->ref_obj_id;
8194         }
8195
8196         switch (base_type(arg_type)) {
8197         case ARG_CONST_MAP_PTR:
8198                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8199                 if (meta->map_ptr) {
8200                         /* Use map_uid (which is unique id of inner map) to reject:
8201                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8202                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8203                          * if (inner_map1 && inner_map2) {
8204                          *     timer = bpf_map_lookup_elem(inner_map1);
8205                          *     if (timer)
8206                          *         // mismatch would have been allowed
8207                          *         bpf_timer_init(timer, inner_map2);
8208                          * }
8209                          *
8210                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8211                          */
8212                         if (meta->map_ptr != reg->map_ptr ||
8213                             meta->map_uid != reg->map_uid) {
8214                                 verbose(env,
8215                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8216                                         meta->map_uid, reg->map_uid);
8217                                 return -EINVAL;
8218                         }
8219                 }
8220                 meta->map_ptr = reg->map_ptr;
8221                 meta->map_uid = reg->map_uid;
8222                 break;
8223         case ARG_PTR_TO_MAP_KEY:
8224                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8225                  * check that [key, key + map->key_size) are within
8226                  * stack limits and initialized
8227                  */
8228                 if (!meta->map_ptr) {
8229                         /* in function declaration map_ptr must come before
8230                          * map_key, so that it's verified and known before
8231                          * we have to check map_key here. Otherwise it means
8232                          * that kernel subsystem misconfigured verifier
8233                          */
8234                         verbose(env, "invalid map_ptr to access map->key\n");
8235                         return -EACCES;
8236                 }
8237                 err = check_helper_mem_access(env, regno,
8238                                               meta->map_ptr->key_size, false,
8239                                               NULL);
8240                 break;
8241         case ARG_PTR_TO_MAP_VALUE:
8242                 if (type_may_be_null(arg_type) && register_is_null(reg))
8243                         return 0;
8244
8245                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8246                  * check [value, value + map->value_size) validity
8247                  */
8248                 if (!meta->map_ptr) {
8249                         /* kernel subsystem misconfigured verifier */
8250                         verbose(env, "invalid map_ptr to access map->value\n");
8251                         return -EACCES;
8252                 }
8253                 meta->raw_mode = arg_type & MEM_UNINIT;
8254                 err = check_helper_mem_access(env, regno,
8255                                               meta->map_ptr->value_size, false,
8256                                               meta);
8257                 break;
8258         case ARG_PTR_TO_PERCPU_BTF_ID:
8259                 if (!reg->btf_id) {
8260                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8261                         return -EACCES;
8262                 }
8263                 meta->ret_btf = reg->btf;
8264                 meta->ret_btf_id = reg->btf_id;
8265                 break;
8266         case ARG_PTR_TO_SPIN_LOCK:
8267                 if (in_rbtree_lock_required_cb(env)) {
8268                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8269                         return -EACCES;
8270                 }
8271                 if (meta->func_id == BPF_FUNC_spin_lock) {
8272                         err = process_spin_lock(env, regno, true);
8273                         if (err)
8274                                 return err;
8275                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8276                         err = process_spin_lock(env, regno, false);
8277                         if (err)
8278                                 return err;
8279                 } else {
8280                         verbose(env, "verifier internal error\n");
8281                         return -EFAULT;
8282                 }
8283                 break;
8284         case ARG_PTR_TO_TIMER:
8285                 err = process_timer_func(env, regno, meta);
8286                 if (err)
8287                         return err;
8288                 break;
8289         case ARG_PTR_TO_FUNC:
8290                 meta->subprogno = reg->subprogno;
8291                 break;
8292         case ARG_PTR_TO_MEM:
8293                 /* The access to this pointer is only checked when we hit the
8294                  * next is_mem_size argument below.
8295                  */
8296                 meta->raw_mode = arg_type & MEM_UNINIT;
8297                 if (arg_type & MEM_FIXED_SIZE) {
8298                         err = check_helper_mem_access(env, regno,
8299                                                       fn->arg_size[arg], false,
8300                                                       meta);
8301                 }
8302                 break;
8303         case ARG_CONST_SIZE:
8304                 err = check_mem_size_reg(env, reg, regno, false, meta);
8305                 break;
8306         case ARG_CONST_SIZE_OR_ZERO:
8307                 err = check_mem_size_reg(env, reg, regno, true, meta);
8308                 break;
8309         case ARG_PTR_TO_DYNPTR:
8310                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8311                 if (err)
8312                         return err;
8313                 break;
8314         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8315                 if (!tnum_is_const(reg->var_off)) {
8316                         verbose(env, "R%d is not a known constant'\n",
8317                                 regno);
8318                         return -EACCES;
8319                 }
8320                 meta->mem_size = reg->var_off.value;
8321                 err = mark_chain_precision(env, regno);
8322                 if (err)
8323                         return err;
8324                 break;
8325         case ARG_PTR_TO_INT:
8326         case ARG_PTR_TO_LONG:
8327         {
8328                 int size = int_ptr_type_to_size(arg_type);
8329
8330                 err = check_helper_mem_access(env, regno, size, false, meta);
8331                 if (err)
8332                         return err;
8333                 err = check_ptr_alignment(env, reg, 0, size, true);
8334                 break;
8335         }
8336         case ARG_PTR_TO_CONST_STR:
8337         {
8338                 struct bpf_map *map = reg->map_ptr;
8339                 int map_off;
8340                 u64 map_addr;
8341                 char *str_ptr;
8342
8343                 if (!bpf_map_is_rdonly(map)) {
8344                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8345                         return -EACCES;
8346                 }
8347
8348                 if (!tnum_is_const(reg->var_off)) {
8349                         verbose(env, "R%d is not a constant address'\n", regno);
8350                         return -EACCES;
8351                 }
8352
8353                 if (!map->ops->map_direct_value_addr) {
8354                         verbose(env, "no direct value access support for this map type\n");
8355                         return -EACCES;
8356                 }
8357
8358                 err = check_map_access(env, regno, reg->off,
8359                                        map->value_size - reg->off, false,
8360                                        ACCESS_HELPER);
8361                 if (err)
8362                         return err;
8363
8364                 map_off = reg->off + reg->var_off.value;
8365                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8366                 if (err) {
8367                         verbose(env, "direct value access on string failed\n");
8368                         return err;
8369                 }
8370
8371                 str_ptr = (char *)(long)(map_addr);
8372                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8373                         verbose(env, "string is not zero-terminated\n");
8374                         return -EINVAL;
8375                 }
8376                 break;
8377         }
8378         case ARG_PTR_TO_KPTR:
8379                 err = process_kptr_func(env, regno, meta);
8380                 if (err)
8381                         return err;
8382                 break;
8383         }
8384
8385         return err;
8386 }
8387
8388 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8389 {
8390         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8391         enum bpf_prog_type type = resolve_prog_type(env->prog);
8392
8393         if (func_id != BPF_FUNC_map_update_elem)
8394                 return false;
8395
8396         /* It's not possible to get access to a locked struct sock in these
8397          * contexts, so updating is safe.
8398          */
8399         switch (type) {
8400         case BPF_PROG_TYPE_TRACING:
8401                 if (eatype == BPF_TRACE_ITER)
8402                         return true;
8403                 break;
8404         case BPF_PROG_TYPE_SOCKET_FILTER:
8405         case BPF_PROG_TYPE_SCHED_CLS:
8406         case BPF_PROG_TYPE_SCHED_ACT:
8407         case BPF_PROG_TYPE_XDP:
8408         case BPF_PROG_TYPE_SK_REUSEPORT:
8409         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8410         case BPF_PROG_TYPE_SK_LOOKUP:
8411                 return true;
8412         default:
8413                 break;
8414         }
8415
8416         verbose(env, "cannot update sockmap in this context\n");
8417         return false;
8418 }
8419
8420 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8421 {
8422         return env->prog->jit_requested &&
8423                bpf_jit_supports_subprog_tailcalls();
8424 }
8425
8426 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8427                                         struct bpf_map *map, int func_id)
8428 {
8429         if (!map)
8430                 return 0;
8431
8432         /* We need a two way check, first is from map perspective ... */
8433         switch (map->map_type) {
8434         case BPF_MAP_TYPE_PROG_ARRAY:
8435                 if (func_id != BPF_FUNC_tail_call)
8436                         goto error;
8437                 break;
8438         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8439                 if (func_id != BPF_FUNC_perf_event_read &&
8440                     func_id != BPF_FUNC_perf_event_output &&
8441                     func_id != BPF_FUNC_skb_output &&
8442                     func_id != BPF_FUNC_perf_event_read_value &&
8443                     func_id != BPF_FUNC_xdp_output)
8444                         goto error;
8445                 break;
8446         case BPF_MAP_TYPE_RINGBUF:
8447                 if (func_id != BPF_FUNC_ringbuf_output &&
8448                     func_id != BPF_FUNC_ringbuf_reserve &&
8449                     func_id != BPF_FUNC_ringbuf_query &&
8450                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8451                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8452                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8453                         goto error;
8454                 break;
8455         case BPF_MAP_TYPE_USER_RINGBUF:
8456                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8457                         goto error;
8458                 break;
8459         case BPF_MAP_TYPE_STACK_TRACE:
8460                 if (func_id != BPF_FUNC_get_stackid)
8461                         goto error;
8462                 break;
8463         case BPF_MAP_TYPE_CGROUP_ARRAY:
8464                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8465                     func_id != BPF_FUNC_current_task_under_cgroup)
8466                         goto error;
8467                 break;
8468         case BPF_MAP_TYPE_CGROUP_STORAGE:
8469         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8470                 if (func_id != BPF_FUNC_get_local_storage)
8471                         goto error;
8472                 break;
8473         case BPF_MAP_TYPE_DEVMAP:
8474         case BPF_MAP_TYPE_DEVMAP_HASH:
8475                 if (func_id != BPF_FUNC_redirect_map &&
8476                     func_id != BPF_FUNC_map_lookup_elem)
8477                         goto error;
8478                 break;
8479         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8480          * appear.
8481          */
8482         case BPF_MAP_TYPE_CPUMAP:
8483                 if (func_id != BPF_FUNC_redirect_map)
8484                         goto error;
8485                 break;
8486         case BPF_MAP_TYPE_XSKMAP:
8487                 if (func_id != BPF_FUNC_redirect_map &&
8488                     func_id != BPF_FUNC_map_lookup_elem)
8489                         goto error;
8490                 break;
8491         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8492         case BPF_MAP_TYPE_HASH_OF_MAPS:
8493                 if (func_id != BPF_FUNC_map_lookup_elem)
8494                         goto error;
8495                 break;
8496         case BPF_MAP_TYPE_SOCKMAP:
8497                 if (func_id != BPF_FUNC_sk_redirect_map &&
8498                     func_id != BPF_FUNC_sock_map_update &&
8499                     func_id != BPF_FUNC_map_delete_elem &&
8500                     func_id != BPF_FUNC_msg_redirect_map &&
8501                     func_id != BPF_FUNC_sk_select_reuseport &&
8502                     func_id != BPF_FUNC_map_lookup_elem &&
8503                     !may_update_sockmap(env, func_id))
8504                         goto error;
8505                 break;
8506         case BPF_MAP_TYPE_SOCKHASH:
8507                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8508                     func_id != BPF_FUNC_sock_hash_update &&
8509                     func_id != BPF_FUNC_map_delete_elem &&
8510                     func_id != BPF_FUNC_msg_redirect_hash &&
8511                     func_id != BPF_FUNC_sk_select_reuseport &&
8512                     func_id != BPF_FUNC_map_lookup_elem &&
8513                     !may_update_sockmap(env, func_id))
8514                         goto error;
8515                 break;
8516         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8517                 if (func_id != BPF_FUNC_sk_select_reuseport)
8518                         goto error;
8519                 break;
8520         case BPF_MAP_TYPE_QUEUE:
8521         case BPF_MAP_TYPE_STACK:
8522                 if (func_id != BPF_FUNC_map_peek_elem &&
8523                     func_id != BPF_FUNC_map_pop_elem &&
8524                     func_id != BPF_FUNC_map_push_elem)
8525                         goto error;
8526                 break;
8527         case BPF_MAP_TYPE_SK_STORAGE:
8528                 if (func_id != BPF_FUNC_sk_storage_get &&
8529                     func_id != BPF_FUNC_sk_storage_delete &&
8530                     func_id != BPF_FUNC_kptr_xchg)
8531                         goto error;
8532                 break;
8533         case BPF_MAP_TYPE_INODE_STORAGE:
8534                 if (func_id != BPF_FUNC_inode_storage_get &&
8535                     func_id != BPF_FUNC_inode_storage_delete &&
8536                     func_id != BPF_FUNC_kptr_xchg)
8537                         goto error;
8538                 break;
8539         case BPF_MAP_TYPE_TASK_STORAGE:
8540                 if (func_id != BPF_FUNC_task_storage_get &&
8541                     func_id != BPF_FUNC_task_storage_delete &&
8542                     func_id != BPF_FUNC_kptr_xchg)
8543                         goto error;
8544                 break;
8545         case BPF_MAP_TYPE_CGRP_STORAGE:
8546                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8547                     func_id != BPF_FUNC_cgrp_storage_delete &&
8548                     func_id != BPF_FUNC_kptr_xchg)
8549                         goto error;
8550                 break;
8551         case BPF_MAP_TYPE_BLOOM_FILTER:
8552                 if (func_id != BPF_FUNC_map_peek_elem &&
8553                     func_id != BPF_FUNC_map_push_elem)
8554                         goto error;
8555                 break;
8556         default:
8557                 break;
8558         }
8559
8560         /* ... and second from the function itself. */
8561         switch (func_id) {
8562         case BPF_FUNC_tail_call:
8563                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8564                         goto error;
8565                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8566                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8567                         return -EINVAL;
8568                 }
8569                 break;
8570         case BPF_FUNC_perf_event_read:
8571         case BPF_FUNC_perf_event_output:
8572         case BPF_FUNC_perf_event_read_value:
8573         case BPF_FUNC_skb_output:
8574         case BPF_FUNC_xdp_output:
8575                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8576                         goto error;
8577                 break;
8578         case BPF_FUNC_ringbuf_output:
8579         case BPF_FUNC_ringbuf_reserve:
8580         case BPF_FUNC_ringbuf_query:
8581         case BPF_FUNC_ringbuf_reserve_dynptr:
8582         case BPF_FUNC_ringbuf_submit_dynptr:
8583         case BPF_FUNC_ringbuf_discard_dynptr:
8584                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8585                         goto error;
8586                 break;
8587         case BPF_FUNC_user_ringbuf_drain:
8588                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8589                         goto error;
8590                 break;
8591         case BPF_FUNC_get_stackid:
8592                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8593                         goto error;
8594                 break;
8595         case BPF_FUNC_current_task_under_cgroup:
8596         case BPF_FUNC_skb_under_cgroup:
8597                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8598                         goto error;
8599                 break;
8600         case BPF_FUNC_redirect_map:
8601                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8602                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8603                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8604                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8605                         goto error;
8606                 break;
8607         case BPF_FUNC_sk_redirect_map:
8608         case BPF_FUNC_msg_redirect_map:
8609         case BPF_FUNC_sock_map_update:
8610                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8611                         goto error;
8612                 break;
8613         case BPF_FUNC_sk_redirect_hash:
8614         case BPF_FUNC_msg_redirect_hash:
8615         case BPF_FUNC_sock_hash_update:
8616                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8617                         goto error;
8618                 break;
8619         case BPF_FUNC_get_local_storage:
8620                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8621                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8622                         goto error;
8623                 break;
8624         case BPF_FUNC_sk_select_reuseport:
8625                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8626                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8627                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8628                         goto error;
8629                 break;
8630         case BPF_FUNC_map_pop_elem:
8631                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8632                     map->map_type != BPF_MAP_TYPE_STACK)
8633                         goto error;
8634                 break;
8635         case BPF_FUNC_map_peek_elem:
8636         case BPF_FUNC_map_push_elem:
8637                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8638                     map->map_type != BPF_MAP_TYPE_STACK &&
8639                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8640                         goto error;
8641                 break;
8642         case BPF_FUNC_map_lookup_percpu_elem:
8643                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8644                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8645                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8646                         goto error;
8647                 break;
8648         case BPF_FUNC_sk_storage_get:
8649         case BPF_FUNC_sk_storage_delete:
8650                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8651                         goto error;
8652                 break;
8653         case BPF_FUNC_inode_storage_get:
8654         case BPF_FUNC_inode_storage_delete:
8655                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8656                         goto error;
8657                 break;
8658         case BPF_FUNC_task_storage_get:
8659         case BPF_FUNC_task_storage_delete:
8660                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8661                         goto error;
8662                 break;
8663         case BPF_FUNC_cgrp_storage_get:
8664         case BPF_FUNC_cgrp_storage_delete:
8665                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8666                         goto error;
8667                 break;
8668         default:
8669                 break;
8670         }
8671
8672         return 0;
8673 error:
8674         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8675                 map->map_type, func_id_name(func_id), func_id);
8676         return -EINVAL;
8677 }
8678
8679 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8680 {
8681         int count = 0;
8682
8683         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8684                 count++;
8685         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8686                 count++;
8687         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8688                 count++;
8689         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8690                 count++;
8691         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8692                 count++;
8693
8694         /* We only support one arg being in raw mode at the moment,
8695          * which is sufficient for the helper functions we have
8696          * right now.
8697          */
8698         return count <= 1;
8699 }
8700
8701 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8702 {
8703         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8704         bool has_size = fn->arg_size[arg] != 0;
8705         bool is_next_size = false;
8706
8707         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8708                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8709
8710         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8711                 return is_next_size;
8712
8713         return has_size == is_next_size || is_next_size == is_fixed;
8714 }
8715
8716 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8717 {
8718         /* bpf_xxx(..., buf, len) call will access 'len'
8719          * bytes from memory 'buf'. Both arg types need
8720          * to be paired, so make sure there's no buggy
8721          * helper function specification.
8722          */
8723         if (arg_type_is_mem_size(fn->arg1_type) ||
8724             check_args_pair_invalid(fn, 0) ||
8725             check_args_pair_invalid(fn, 1) ||
8726             check_args_pair_invalid(fn, 2) ||
8727             check_args_pair_invalid(fn, 3) ||
8728             check_args_pair_invalid(fn, 4))
8729                 return false;
8730
8731         return true;
8732 }
8733
8734 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8735 {
8736         int i;
8737
8738         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8739                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8740                         return !!fn->arg_btf_id[i];
8741                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8742                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8743                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8744                     /* arg_btf_id and arg_size are in a union. */
8745                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8746                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8747                         return false;
8748         }
8749
8750         return true;
8751 }
8752
8753 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8754 {
8755         return check_raw_mode_ok(fn) &&
8756                check_arg_pair_ok(fn) &&
8757                check_btf_id_ok(fn) ? 0 : -EINVAL;
8758 }
8759
8760 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8761  * are now invalid, so turn them into unknown SCALAR_VALUE.
8762  *
8763  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8764  * since these slices point to packet data.
8765  */
8766 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8767 {
8768         struct bpf_func_state *state;
8769         struct bpf_reg_state *reg;
8770
8771         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8772                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8773                         mark_reg_invalid(env, reg);
8774         }));
8775 }
8776
8777 enum {
8778         AT_PKT_END = -1,
8779         BEYOND_PKT_END = -2,
8780 };
8781
8782 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8783 {
8784         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8785         struct bpf_reg_state *reg = &state->regs[regn];
8786
8787         if (reg->type != PTR_TO_PACKET)
8788                 /* PTR_TO_PACKET_META is not supported yet */
8789                 return;
8790
8791         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8792          * How far beyond pkt_end it goes is unknown.
8793          * if (!range_open) it's the case of pkt >= pkt_end
8794          * if (range_open) it's the case of pkt > pkt_end
8795          * hence this pointer is at least 1 byte bigger than pkt_end
8796          */
8797         if (range_open)
8798                 reg->range = BEYOND_PKT_END;
8799         else
8800                 reg->range = AT_PKT_END;
8801 }
8802
8803 /* The pointer with the specified id has released its reference to kernel
8804  * resources. Identify all copies of the same pointer and clear the reference.
8805  */
8806 static int release_reference(struct bpf_verifier_env *env,
8807                              int ref_obj_id)
8808 {
8809         struct bpf_func_state *state;
8810         struct bpf_reg_state *reg;
8811         int err;
8812
8813         err = release_reference_state(cur_func(env), ref_obj_id);
8814         if (err)
8815                 return err;
8816
8817         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8818                 if (reg->ref_obj_id == ref_obj_id)
8819                         mark_reg_invalid(env, reg);
8820         }));
8821
8822         return 0;
8823 }
8824
8825 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8826 {
8827         struct bpf_func_state *unused;
8828         struct bpf_reg_state *reg;
8829
8830         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8831                 if (type_is_non_owning_ref(reg->type))
8832                         mark_reg_invalid(env, reg);
8833         }));
8834 }
8835
8836 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8837                                     struct bpf_reg_state *regs)
8838 {
8839         int i;
8840
8841         /* after the call registers r0 - r5 were scratched */
8842         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8843                 mark_reg_not_init(env, regs, caller_saved[i]);
8844                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8845         }
8846 }
8847
8848 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8849                                    struct bpf_func_state *caller,
8850                                    struct bpf_func_state *callee,
8851                                    int insn_idx);
8852
8853 static int set_callee_state(struct bpf_verifier_env *env,
8854                             struct bpf_func_state *caller,
8855                             struct bpf_func_state *callee, int insn_idx);
8856
8857 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8858                              int *insn_idx, int subprog,
8859                              set_callee_state_fn set_callee_state_cb)
8860 {
8861         struct bpf_verifier_state *state = env->cur_state;
8862         struct bpf_func_state *caller, *callee;
8863         int err;
8864
8865         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8866                 verbose(env, "the call stack of %d frames is too deep\n",
8867                         state->curframe + 2);
8868                 return -E2BIG;
8869         }
8870
8871         caller = state->frame[state->curframe];
8872         if (state->frame[state->curframe + 1]) {
8873                 verbose(env, "verifier bug. Frame %d already allocated\n",
8874                         state->curframe + 1);
8875                 return -EFAULT;
8876         }
8877
8878         err = btf_check_subprog_call(env, subprog, caller->regs);
8879         if (err == -EFAULT)
8880                 return err;
8881         if (subprog_is_global(env, subprog)) {
8882                 if (err) {
8883                         verbose(env, "Caller passes invalid args into func#%d\n",
8884                                 subprog);
8885                         return err;
8886                 } else {
8887                         if (env->log.level & BPF_LOG_LEVEL)
8888                                 verbose(env,
8889                                         "Func#%d is global and valid. Skipping.\n",
8890                                         subprog);
8891                         clear_caller_saved_regs(env, caller->regs);
8892
8893                         /* All global functions return a 64-bit SCALAR_VALUE */
8894                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8895                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8896
8897                         /* continue with next insn after call */
8898                         return 0;
8899                 }
8900         }
8901
8902         /* set_callee_state is used for direct subprog calls, but we are
8903          * interested in validating only BPF helpers that can call subprogs as
8904          * callbacks
8905          */
8906         if (set_callee_state_cb != set_callee_state) {
8907                 if (bpf_pseudo_kfunc_call(insn) &&
8908                     !is_callback_calling_kfunc(insn->imm)) {
8909                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8910                                 func_id_name(insn->imm), insn->imm);
8911                         return -EFAULT;
8912                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8913                            !is_callback_calling_function(insn->imm)) { /* helper */
8914                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8915                                 func_id_name(insn->imm), insn->imm);
8916                         return -EFAULT;
8917                 }
8918         }
8919
8920         if (insn->code == (BPF_JMP | BPF_CALL) &&
8921             insn->src_reg == 0 &&
8922             insn->imm == BPF_FUNC_timer_set_callback) {
8923                 struct bpf_verifier_state *async_cb;
8924
8925                 /* there is no real recursion here. timer callbacks are async */
8926                 env->subprog_info[subprog].is_async_cb = true;
8927                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8928                                          *insn_idx, subprog);
8929                 if (!async_cb)
8930                         return -EFAULT;
8931                 callee = async_cb->frame[0];
8932                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8933
8934                 /* Convert bpf_timer_set_callback() args into timer callback args */
8935                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8936                 if (err)
8937                         return err;
8938
8939                 clear_caller_saved_regs(env, caller->regs);
8940                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8941                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8942                 /* continue with next insn after call */
8943                 return 0;
8944         }
8945
8946         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8947         if (!callee)
8948                 return -ENOMEM;
8949         state->frame[state->curframe + 1] = callee;
8950
8951         /* callee cannot access r0, r6 - r9 for reading and has to write
8952          * into its own stack before reading from it.
8953          * callee can read/write into caller's stack
8954          */
8955         init_func_state(env, callee,
8956                         /* remember the callsite, it will be used by bpf_exit */
8957                         *insn_idx /* callsite */,
8958                         state->curframe + 1 /* frameno within this callchain */,
8959                         subprog /* subprog number within this prog */);
8960
8961         /* Transfer references to the callee */
8962         err = copy_reference_state(callee, caller);
8963         if (err)
8964                 goto err_out;
8965
8966         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8967         if (err)
8968                 goto err_out;
8969
8970         clear_caller_saved_regs(env, caller->regs);
8971
8972         /* only increment it after check_reg_arg() finished */
8973         state->curframe++;
8974
8975         /* and go analyze first insn of the callee */
8976         *insn_idx = env->subprog_info[subprog].start - 1;
8977
8978         if (env->log.level & BPF_LOG_LEVEL) {
8979                 verbose(env, "caller:\n");
8980                 print_verifier_state(env, caller, true);
8981                 verbose(env, "callee:\n");
8982                 print_verifier_state(env, callee, true);
8983         }
8984         return 0;
8985
8986 err_out:
8987         free_func_state(callee);
8988         state->frame[state->curframe + 1] = NULL;
8989         return err;
8990 }
8991
8992 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8993                                    struct bpf_func_state *caller,
8994                                    struct bpf_func_state *callee)
8995 {
8996         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8997          *      void *callback_ctx, u64 flags);
8998          * callback_fn(struct bpf_map *map, void *key, void *value,
8999          *      void *callback_ctx);
9000          */
9001         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9002
9003         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9004         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9005         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9006
9007         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9008         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9009         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9010
9011         /* pointer to stack or null */
9012         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9013
9014         /* unused */
9015         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9016         return 0;
9017 }
9018
9019 static int set_callee_state(struct bpf_verifier_env *env,
9020                             struct bpf_func_state *caller,
9021                             struct bpf_func_state *callee, int insn_idx)
9022 {
9023         int i;
9024
9025         /* copy r1 - r5 args that callee can access.  The copy includes parent
9026          * pointers, which connects us up to the liveness chain
9027          */
9028         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9029                 callee->regs[i] = caller->regs[i];
9030         return 0;
9031 }
9032
9033 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9034                            int *insn_idx)
9035 {
9036         int subprog, target_insn;
9037
9038         target_insn = *insn_idx + insn->imm + 1;
9039         subprog = find_subprog(env, target_insn);
9040         if (subprog < 0) {
9041                 verbose(env, "verifier bug. No program starts at insn %d\n",
9042                         target_insn);
9043                 return -EFAULT;
9044         }
9045
9046         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9047 }
9048
9049 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9050                                        struct bpf_func_state *caller,
9051                                        struct bpf_func_state *callee,
9052                                        int insn_idx)
9053 {
9054         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9055         struct bpf_map *map;
9056         int err;
9057
9058         if (bpf_map_ptr_poisoned(insn_aux)) {
9059                 verbose(env, "tail_call abusing map_ptr\n");
9060                 return -EINVAL;
9061         }
9062
9063         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9064         if (!map->ops->map_set_for_each_callback_args ||
9065             !map->ops->map_for_each_callback) {
9066                 verbose(env, "callback function not allowed for map\n");
9067                 return -ENOTSUPP;
9068         }
9069
9070         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9071         if (err)
9072                 return err;
9073
9074         callee->in_callback_fn = true;
9075         callee->callback_ret_range = tnum_range(0, 1);
9076         return 0;
9077 }
9078
9079 static int set_loop_callback_state(struct bpf_verifier_env *env,
9080                                    struct bpf_func_state *caller,
9081                                    struct bpf_func_state *callee,
9082                                    int insn_idx)
9083 {
9084         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9085          *          u64 flags);
9086          * callback_fn(u32 index, void *callback_ctx);
9087          */
9088         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9089         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9090
9091         /* unused */
9092         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9093         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9094         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9095
9096         callee->in_callback_fn = true;
9097         callee->callback_ret_range = tnum_range(0, 1);
9098         return 0;
9099 }
9100
9101 static int set_timer_callback_state(struct bpf_verifier_env *env,
9102                                     struct bpf_func_state *caller,
9103                                     struct bpf_func_state *callee,
9104                                     int insn_idx)
9105 {
9106         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9107
9108         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9109          * callback_fn(struct bpf_map *map, void *key, void *value);
9110          */
9111         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9112         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9113         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9114
9115         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9116         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9117         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9118
9119         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9120         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9121         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9122
9123         /* unused */
9124         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9125         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9126         callee->in_async_callback_fn = true;
9127         callee->callback_ret_range = tnum_range(0, 1);
9128         return 0;
9129 }
9130
9131 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9132                                        struct bpf_func_state *caller,
9133                                        struct bpf_func_state *callee,
9134                                        int insn_idx)
9135 {
9136         /* bpf_find_vma(struct task_struct *task, u64 addr,
9137          *               void *callback_fn, void *callback_ctx, u64 flags)
9138          * (callback_fn)(struct task_struct *task,
9139          *               struct vm_area_struct *vma, void *callback_ctx);
9140          */
9141         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9142
9143         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9144         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9145         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9146         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9147
9148         /* pointer to stack or null */
9149         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9150
9151         /* unused */
9152         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9153         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9154         callee->in_callback_fn = true;
9155         callee->callback_ret_range = tnum_range(0, 1);
9156         return 0;
9157 }
9158
9159 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9160                                            struct bpf_func_state *caller,
9161                                            struct bpf_func_state *callee,
9162                                            int insn_idx)
9163 {
9164         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9165          *                        callback_ctx, u64 flags);
9166          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9167          */
9168         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9169         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9170         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9171
9172         /* unused */
9173         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9174         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9175         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9176
9177         callee->in_callback_fn = true;
9178         callee->callback_ret_range = tnum_range(0, 1);
9179         return 0;
9180 }
9181
9182 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9183                                          struct bpf_func_state *caller,
9184                                          struct bpf_func_state *callee,
9185                                          int insn_idx)
9186 {
9187         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9188          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9189          *
9190          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9191          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9192          * by this point, so look at 'root'
9193          */
9194         struct btf_field *field;
9195
9196         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9197                                       BPF_RB_ROOT);
9198         if (!field || !field->graph_root.value_btf_id)
9199                 return -EFAULT;
9200
9201         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9202         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9203         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9204         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9205
9206         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9207         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9208         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9209         callee->in_callback_fn = true;
9210         callee->callback_ret_range = tnum_range(0, 1);
9211         return 0;
9212 }
9213
9214 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9215
9216 /* Are we currently verifying the callback for a rbtree helper that must
9217  * be called with lock held? If so, no need to complain about unreleased
9218  * lock
9219  */
9220 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9221 {
9222         struct bpf_verifier_state *state = env->cur_state;
9223         struct bpf_insn *insn = env->prog->insnsi;
9224         struct bpf_func_state *callee;
9225         int kfunc_btf_id;
9226
9227         if (!state->curframe)
9228                 return false;
9229
9230         callee = state->frame[state->curframe];
9231
9232         if (!callee->in_callback_fn)
9233                 return false;
9234
9235         kfunc_btf_id = insn[callee->callsite].imm;
9236         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9237 }
9238
9239 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9240 {
9241         struct bpf_verifier_state *state = env->cur_state;
9242         struct bpf_func_state *caller, *callee;
9243         struct bpf_reg_state *r0;
9244         int err;
9245
9246         callee = state->frame[state->curframe];
9247         r0 = &callee->regs[BPF_REG_0];
9248         if (r0->type == PTR_TO_STACK) {
9249                 /* technically it's ok to return caller's stack pointer
9250                  * (or caller's caller's pointer) back to the caller,
9251                  * since these pointers are valid. Only current stack
9252                  * pointer will be invalid as soon as function exits,
9253                  * but let's be conservative
9254                  */
9255                 verbose(env, "cannot return stack pointer to the caller\n");
9256                 return -EINVAL;
9257         }
9258
9259         caller = state->frame[state->curframe - 1];
9260         if (callee->in_callback_fn) {
9261                 /* enforce R0 return value range [0, 1]. */
9262                 struct tnum range = callee->callback_ret_range;
9263
9264                 if (r0->type != SCALAR_VALUE) {
9265                         verbose(env, "R0 not a scalar value\n");
9266                         return -EACCES;
9267                 }
9268                 if (!tnum_in(range, r0->var_off)) {
9269                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9270                         return -EINVAL;
9271                 }
9272         } else {
9273                 /* return to the caller whatever r0 had in the callee */
9274                 caller->regs[BPF_REG_0] = *r0;
9275         }
9276
9277         /* callback_fn frame should have released its own additions to parent's
9278          * reference state at this point, or check_reference_leak would
9279          * complain, hence it must be the same as the caller. There is no need
9280          * to copy it back.
9281          */
9282         if (!callee->in_callback_fn) {
9283                 /* Transfer references to the caller */
9284                 err = copy_reference_state(caller, callee);
9285                 if (err)
9286                         return err;
9287         }
9288
9289         *insn_idx = callee->callsite + 1;
9290         if (env->log.level & BPF_LOG_LEVEL) {
9291                 verbose(env, "returning from callee:\n");
9292                 print_verifier_state(env, callee, true);
9293                 verbose(env, "to caller at %d:\n", *insn_idx);
9294                 print_verifier_state(env, caller, true);
9295         }
9296         /* clear everything in the callee */
9297         free_func_state(callee);
9298         state->frame[state->curframe--] = NULL;
9299         return 0;
9300 }
9301
9302 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9303                                    int func_id,
9304                                    struct bpf_call_arg_meta *meta)
9305 {
9306         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9307
9308         if (ret_type != RET_INTEGER)
9309                 return;
9310
9311         switch (func_id) {
9312         case BPF_FUNC_get_stack:
9313         case BPF_FUNC_get_task_stack:
9314         case BPF_FUNC_probe_read_str:
9315         case BPF_FUNC_probe_read_kernel_str:
9316         case BPF_FUNC_probe_read_user_str:
9317                 ret_reg->smax_value = meta->msize_max_value;
9318                 ret_reg->s32_max_value = meta->msize_max_value;
9319                 ret_reg->smin_value = -MAX_ERRNO;
9320                 ret_reg->s32_min_value = -MAX_ERRNO;
9321                 reg_bounds_sync(ret_reg);
9322                 break;
9323         case BPF_FUNC_get_smp_processor_id:
9324                 ret_reg->umax_value = nr_cpu_ids - 1;
9325                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9326                 ret_reg->smax_value = nr_cpu_ids - 1;
9327                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9328                 ret_reg->umin_value = 0;
9329                 ret_reg->u32_min_value = 0;
9330                 ret_reg->smin_value = 0;
9331                 ret_reg->s32_min_value = 0;
9332                 reg_bounds_sync(ret_reg);
9333                 break;
9334         }
9335 }
9336
9337 static int
9338 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9339                 int func_id, int insn_idx)
9340 {
9341         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9342         struct bpf_map *map = meta->map_ptr;
9343
9344         if (func_id != BPF_FUNC_tail_call &&
9345             func_id != BPF_FUNC_map_lookup_elem &&
9346             func_id != BPF_FUNC_map_update_elem &&
9347             func_id != BPF_FUNC_map_delete_elem &&
9348             func_id != BPF_FUNC_map_push_elem &&
9349             func_id != BPF_FUNC_map_pop_elem &&
9350             func_id != BPF_FUNC_map_peek_elem &&
9351             func_id != BPF_FUNC_for_each_map_elem &&
9352             func_id != BPF_FUNC_redirect_map &&
9353             func_id != BPF_FUNC_map_lookup_percpu_elem)
9354                 return 0;
9355
9356         if (map == NULL) {
9357                 verbose(env, "kernel subsystem misconfigured verifier\n");
9358                 return -EINVAL;
9359         }
9360
9361         /* In case of read-only, some additional restrictions
9362          * need to be applied in order to prevent altering the
9363          * state of the map from program side.
9364          */
9365         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9366             (func_id == BPF_FUNC_map_delete_elem ||
9367              func_id == BPF_FUNC_map_update_elem ||
9368              func_id == BPF_FUNC_map_push_elem ||
9369              func_id == BPF_FUNC_map_pop_elem)) {
9370                 verbose(env, "write into map forbidden\n");
9371                 return -EACCES;
9372         }
9373
9374         if (!BPF_MAP_PTR(aux->map_ptr_state))
9375                 bpf_map_ptr_store(aux, meta->map_ptr,
9376                                   !meta->map_ptr->bypass_spec_v1);
9377         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9378                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9379                                   !meta->map_ptr->bypass_spec_v1);
9380         return 0;
9381 }
9382
9383 static int
9384 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9385                 int func_id, int insn_idx)
9386 {
9387         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9388         struct bpf_reg_state *regs = cur_regs(env), *reg;
9389         struct bpf_map *map = meta->map_ptr;
9390         u64 val, max;
9391         int err;
9392
9393         if (func_id != BPF_FUNC_tail_call)
9394                 return 0;
9395         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9396                 verbose(env, "kernel subsystem misconfigured verifier\n");
9397                 return -EINVAL;
9398         }
9399
9400         reg = &regs[BPF_REG_3];
9401         val = reg->var_off.value;
9402         max = map->max_entries;
9403
9404         if (!(register_is_const(reg) && val < max)) {
9405                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9406                 return 0;
9407         }
9408
9409         err = mark_chain_precision(env, BPF_REG_3);
9410         if (err)
9411                 return err;
9412         if (bpf_map_key_unseen(aux))
9413                 bpf_map_key_store(aux, val);
9414         else if (!bpf_map_key_poisoned(aux) &&
9415                   bpf_map_key_immediate(aux) != val)
9416                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9417         return 0;
9418 }
9419
9420 static int check_reference_leak(struct bpf_verifier_env *env)
9421 {
9422         struct bpf_func_state *state = cur_func(env);
9423         bool refs_lingering = false;
9424         int i;
9425
9426         if (state->frameno && !state->in_callback_fn)
9427                 return 0;
9428
9429         for (i = 0; i < state->acquired_refs; i++) {
9430                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9431                         continue;
9432                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9433                         state->refs[i].id, state->refs[i].insn_idx);
9434                 refs_lingering = true;
9435         }
9436         return refs_lingering ? -EINVAL : 0;
9437 }
9438
9439 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9440                                    struct bpf_reg_state *regs)
9441 {
9442         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9443         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9444         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9445         struct bpf_bprintf_data data = {};
9446         int err, fmt_map_off, num_args;
9447         u64 fmt_addr;
9448         char *fmt;
9449
9450         /* data must be an array of u64 */
9451         if (data_len_reg->var_off.value % 8)
9452                 return -EINVAL;
9453         num_args = data_len_reg->var_off.value / 8;
9454
9455         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9456          * and map_direct_value_addr is set.
9457          */
9458         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9459         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9460                                                   fmt_map_off);
9461         if (err) {
9462                 verbose(env, "verifier bug\n");
9463                 return -EFAULT;
9464         }
9465         fmt = (char *)(long)fmt_addr + fmt_map_off;
9466
9467         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9468          * can focus on validating the format specifiers.
9469          */
9470         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9471         if (err < 0)
9472                 verbose(env, "Invalid format string\n");
9473
9474         return err;
9475 }
9476
9477 static int check_get_func_ip(struct bpf_verifier_env *env)
9478 {
9479         enum bpf_prog_type type = resolve_prog_type(env->prog);
9480         int func_id = BPF_FUNC_get_func_ip;
9481
9482         if (type == BPF_PROG_TYPE_TRACING) {
9483                 if (!bpf_prog_has_trampoline(env->prog)) {
9484                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9485                                 func_id_name(func_id), func_id);
9486                         return -ENOTSUPP;
9487                 }
9488                 return 0;
9489         } else if (type == BPF_PROG_TYPE_KPROBE) {
9490                 return 0;
9491         }
9492
9493         verbose(env, "func %s#%d not supported for program type %d\n",
9494                 func_id_name(func_id), func_id, type);
9495         return -ENOTSUPP;
9496 }
9497
9498 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9499 {
9500         return &env->insn_aux_data[env->insn_idx];
9501 }
9502
9503 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9504 {
9505         struct bpf_reg_state *regs = cur_regs(env);
9506         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9507         bool reg_is_null = register_is_null(reg);
9508
9509         if (reg_is_null)
9510                 mark_chain_precision(env, BPF_REG_4);
9511
9512         return reg_is_null;
9513 }
9514
9515 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9516 {
9517         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9518
9519         if (!state->initialized) {
9520                 state->initialized = 1;
9521                 state->fit_for_inline = loop_flag_is_zero(env);
9522                 state->callback_subprogno = subprogno;
9523                 return;
9524         }
9525
9526         if (!state->fit_for_inline)
9527                 return;
9528
9529         state->fit_for_inline = (loop_flag_is_zero(env) &&
9530                                  state->callback_subprogno == subprogno);
9531 }
9532
9533 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9534                              int *insn_idx_p)
9535 {
9536         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9537         const struct bpf_func_proto *fn = NULL;
9538         enum bpf_return_type ret_type;
9539         enum bpf_type_flag ret_flag;
9540         struct bpf_reg_state *regs;
9541         struct bpf_call_arg_meta meta;
9542         int insn_idx = *insn_idx_p;
9543         bool changes_data;
9544         int i, err, func_id;
9545
9546         /* find function prototype */
9547         func_id = insn->imm;
9548         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9549                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9550                         func_id);
9551                 return -EINVAL;
9552         }
9553
9554         if (env->ops->get_func_proto)
9555                 fn = env->ops->get_func_proto(func_id, env->prog);
9556         if (!fn) {
9557                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9558                         func_id);
9559                 return -EINVAL;
9560         }
9561
9562         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9563         if (!env->prog->gpl_compatible && fn->gpl_only) {
9564                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9565                 return -EINVAL;
9566         }
9567
9568         if (fn->allowed && !fn->allowed(env->prog)) {
9569                 verbose(env, "helper call is not allowed in probe\n");
9570                 return -EINVAL;
9571         }
9572
9573         if (!env->prog->aux->sleepable && fn->might_sleep) {
9574                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9575                 return -EINVAL;
9576         }
9577
9578         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9579         changes_data = bpf_helper_changes_pkt_data(fn->func);
9580         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9581                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9582                         func_id_name(func_id), func_id);
9583                 return -EINVAL;
9584         }
9585
9586         memset(&meta, 0, sizeof(meta));
9587         meta.pkt_access = fn->pkt_access;
9588
9589         err = check_func_proto(fn, func_id);
9590         if (err) {
9591                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9592                         func_id_name(func_id), func_id);
9593                 return err;
9594         }
9595
9596         if (env->cur_state->active_rcu_lock) {
9597                 if (fn->might_sleep) {
9598                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9599                                 func_id_name(func_id), func_id);
9600                         return -EINVAL;
9601                 }
9602
9603                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9604                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9605         }
9606
9607         meta.func_id = func_id;
9608         /* check args */
9609         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9610                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9611                 if (err)
9612                         return err;
9613         }
9614
9615         err = record_func_map(env, &meta, func_id, insn_idx);
9616         if (err)
9617                 return err;
9618
9619         err = record_func_key(env, &meta, func_id, insn_idx);
9620         if (err)
9621                 return err;
9622
9623         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9624          * is inferred from register state.
9625          */
9626         for (i = 0; i < meta.access_size; i++) {
9627                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9628                                        BPF_WRITE, -1, false, false);
9629                 if (err)
9630                         return err;
9631         }
9632
9633         regs = cur_regs(env);
9634
9635         if (meta.release_regno) {
9636                 err = -EINVAL;
9637                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9638                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9639                  * is safe to do directly.
9640                  */
9641                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9642                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9643                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9644                                 return -EFAULT;
9645                         }
9646                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9647                 } else if (meta.ref_obj_id) {
9648                         err = release_reference(env, meta.ref_obj_id);
9649                 } else if (register_is_null(&regs[meta.release_regno])) {
9650                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9651                          * released is NULL, which must be > R0.
9652                          */
9653                         err = 0;
9654                 }
9655                 if (err) {
9656                         verbose(env, "func %s#%d reference has not been acquired before\n",
9657                                 func_id_name(func_id), func_id);
9658                         return err;
9659                 }
9660         }
9661
9662         switch (func_id) {
9663         case BPF_FUNC_tail_call:
9664                 err = check_reference_leak(env);
9665                 if (err) {
9666                         verbose(env, "tail_call would lead to reference leak\n");
9667                         return err;
9668                 }
9669                 break;
9670         case BPF_FUNC_get_local_storage:
9671                 /* check that flags argument in get_local_storage(map, flags) is 0,
9672                  * this is required because get_local_storage() can't return an error.
9673                  */
9674                 if (!register_is_null(&regs[BPF_REG_2])) {
9675                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9676                         return -EINVAL;
9677                 }
9678                 break;
9679         case BPF_FUNC_for_each_map_elem:
9680                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9681                                         set_map_elem_callback_state);
9682                 break;
9683         case BPF_FUNC_timer_set_callback:
9684                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9685                                         set_timer_callback_state);
9686                 break;
9687         case BPF_FUNC_find_vma:
9688                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9689                                         set_find_vma_callback_state);
9690                 break;
9691         case BPF_FUNC_snprintf:
9692                 err = check_bpf_snprintf_call(env, regs);
9693                 break;
9694         case BPF_FUNC_loop:
9695                 update_loop_inline_state(env, meta.subprogno);
9696                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9697                                         set_loop_callback_state);
9698                 break;
9699         case BPF_FUNC_dynptr_from_mem:
9700                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9701                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9702                                 reg_type_str(env, regs[BPF_REG_1].type));
9703                         return -EACCES;
9704                 }
9705                 break;
9706         case BPF_FUNC_set_retval:
9707                 if (prog_type == BPF_PROG_TYPE_LSM &&
9708                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9709                         if (!env->prog->aux->attach_func_proto->type) {
9710                                 /* Make sure programs that attach to void
9711                                  * hooks don't try to modify return value.
9712                                  */
9713                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9714                                 return -EINVAL;
9715                         }
9716                 }
9717                 break;
9718         case BPF_FUNC_dynptr_data:
9719         {
9720                 struct bpf_reg_state *reg;
9721                 int id, ref_obj_id;
9722
9723                 reg = get_dynptr_arg_reg(env, fn, regs);
9724                 if (!reg)
9725                         return -EFAULT;
9726
9727
9728                 if (meta.dynptr_id) {
9729                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9730                         return -EFAULT;
9731                 }
9732                 if (meta.ref_obj_id) {
9733                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9734                         return -EFAULT;
9735                 }
9736
9737                 id = dynptr_id(env, reg);
9738                 if (id < 0) {
9739                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9740                         return id;
9741                 }
9742
9743                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9744                 if (ref_obj_id < 0) {
9745                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9746                         return ref_obj_id;
9747                 }
9748
9749                 meta.dynptr_id = id;
9750                 meta.ref_obj_id = ref_obj_id;
9751
9752                 break;
9753         }
9754         case BPF_FUNC_dynptr_write:
9755         {
9756                 enum bpf_dynptr_type dynptr_type;
9757                 struct bpf_reg_state *reg;
9758
9759                 reg = get_dynptr_arg_reg(env, fn, regs);
9760                 if (!reg)
9761                         return -EFAULT;
9762
9763                 dynptr_type = dynptr_get_type(env, reg);
9764                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9765                         return -EFAULT;
9766
9767                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9768                         /* this will trigger clear_all_pkt_pointers(), which will
9769                          * invalidate all dynptr slices associated with the skb
9770                          */
9771                         changes_data = true;
9772
9773                 break;
9774         }
9775         case BPF_FUNC_user_ringbuf_drain:
9776                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9777                                         set_user_ringbuf_callback_state);
9778                 break;
9779         }
9780
9781         if (err)
9782                 return err;
9783
9784         /* reset caller saved regs */
9785         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9786                 mark_reg_not_init(env, regs, caller_saved[i]);
9787                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9788         }
9789
9790         /* helper call returns 64-bit value. */
9791         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9792
9793         /* update return register (already marked as written above) */
9794         ret_type = fn->ret_type;
9795         ret_flag = type_flag(ret_type);
9796
9797         switch (base_type(ret_type)) {
9798         case RET_INTEGER:
9799                 /* sets type to SCALAR_VALUE */
9800                 mark_reg_unknown(env, regs, BPF_REG_0);
9801                 break;
9802         case RET_VOID:
9803                 regs[BPF_REG_0].type = NOT_INIT;
9804                 break;
9805         case RET_PTR_TO_MAP_VALUE:
9806                 /* There is no offset yet applied, variable or fixed */
9807                 mark_reg_known_zero(env, regs, BPF_REG_0);
9808                 /* remember map_ptr, so that check_map_access()
9809                  * can check 'value_size' boundary of memory access
9810                  * to map element returned from bpf_map_lookup_elem()
9811                  */
9812                 if (meta.map_ptr == NULL) {
9813                         verbose(env,
9814                                 "kernel subsystem misconfigured verifier\n");
9815                         return -EINVAL;
9816                 }
9817                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9818                 regs[BPF_REG_0].map_uid = meta.map_uid;
9819                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9820                 if (!type_may_be_null(ret_type) &&
9821                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9822                         regs[BPF_REG_0].id = ++env->id_gen;
9823                 }
9824                 break;
9825         case RET_PTR_TO_SOCKET:
9826                 mark_reg_known_zero(env, regs, BPF_REG_0);
9827                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9828                 break;
9829         case RET_PTR_TO_SOCK_COMMON:
9830                 mark_reg_known_zero(env, regs, BPF_REG_0);
9831                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9832                 break;
9833         case RET_PTR_TO_TCP_SOCK:
9834                 mark_reg_known_zero(env, regs, BPF_REG_0);
9835                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9836                 break;
9837         case RET_PTR_TO_MEM:
9838                 mark_reg_known_zero(env, regs, BPF_REG_0);
9839                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9840                 regs[BPF_REG_0].mem_size = meta.mem_size;
9841                 break;
9842         case RET_PTR_TO_MEM_OR_BTF_ID:
9843         {
9844                 const struct btf_type *t;
9845
9846                 mark_reg_known_zero(env, regs, BPF_REG_0);
9847                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9848                 if (!btf_type_is_struct(t)) {
9849                         u32 tsize;
9850                         const struct btf_type *ret;
9851                         const char *tname;
9852
9853                         /* resolve the type size of ksym. */
9854                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9855                         if (IS_ERR(ret)) {
9856                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9857                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9858                                         tname, PTR_ERR(ret));
9859                                 return -EINVAL;
9860                         }
9861                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9862                         regs[BPF_REG_0].mem_size = tsize;
9863                 } else {
9864                         /* MEM_RDONLY may be carried from ret_flag, but it
9865                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9866                          * it will confuse the check of PTR_TO_BTF_ID in
9867                          * check_mem_access().
9868                          */
9869                         ret_flag &= ~MEM_RDONLY;
9870
9871                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9872                         regs[BPF_REG_0].btf = meta.ret_btf;
9873                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9874                 }
9875                 break;
9876         }
9877         case RET_PTR_TO_BTF_ID:
9878         {
9879                 struct btf *ret_btf;
9880                 int ret_btf_id;
9881
9882                 mark_reg_known_zero(env, regs, BPF_REG_0);
9883                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9884                 if (func_id == BPF_FUNC_kptr_xchg) {
9885                         ret_btf = meta.kptr_field->kptr.btf;
9886                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9887                         if (!btf_is_kernel(ret_btf))
9888                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9889                 } else {
9890                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9891                                 verbose(env, "verifier internal error:");
9892                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9893                                         func_id_name(func_id));
9894                                 return -EINVAL;
9895                         }
9896                         ret_btf = btf_vmlinux;
9897                         ret_btf_id = *fn->ret_btf_id;
9898                 }
9899                 if (ret_btf_id == 0) {
9900                         verbose(env, "invalid return type %u of func %s#%d\n",
9901                                 base_type(ret_type), func_id_name(func_id),
9902                                 func_id);
9903                         return -EINVAL;
9904                 }
9905                 regs[BPF_REG_0].btf = ret_btf;
9906                 regs[BPF_REG_0].btf_id = ret_btf_id;
9907                 break;
9908         }
9909         default:
9910                 verbose(env, "unknown return type %u of func %s#%d\n",
9911                         base_type(ret_type), func_id_name(func_id), func_id);
9912                 return -EINVAL;
9913         }
9914
9915         if (type_may_be_null(regs[BPF_REG_0].type))
9916                 regs[BPF_REG_0].id = ++env->id_gen;
9917
9918         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9919                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9920                         func_id_name(func_id), func_id);
9921                 return -EFAULT;
9922         }
9923
9924         if (is_dynptr_ref_function(func_id))
9925                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9926
9927         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9928                 /* For release_reference() */
9929                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9930         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9931                 int id = acquire_reference_state(env, insn_idx);
9932
9933                 if (id < 0)
9934                         return id;
9935                 /* For mark_ptr_or_null_reg() */
9936                 regs[BPF_REG_0].id = id;
9937                 /* For release_reference() */
9938                 regs[BPF_REG_0].ref_obj_id = id;
9939         }
9940
9941         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9942
9943         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9944         if (err)
9945                 return err;
9946
9947         if ((func_id == BPF_FUNC_get_stack ||
9948              func_id == BPF_FUNC_get_task_stack) &&
9949             !env->prog->has_callchain_buf) {
9950                 const char *err_str;
9951
9952 #ifdef CONFIG_PERF_EVENTS
9953                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9954                 err_str = "cannot get callchain buffer for func %s#%d\n";
9955 #else
9956                 err = -ENOTSUPP;
9957                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9958 #endif
9959                 if (err) {
9960                         verbose(env, err_str, func_id_name(func_id), func_id);
9961                         return err;
9962                 }
9963
9964                 env->prog->has_callchain_buf = true;
9965         }
9966
9967         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9968                 env->prog->call_get_stack = true;
9969
9970         if (func_id == BPF_FUNC_get_func_ip) {
9971                 if (check_get_func_ip(env))
9972                         return -ENOTSUPP;
9973                 env->prog->call_get_func_ip = true;
9974         }
9975
9976         if (changes_data)
9977                 clear_all_pkt_pointers(env);
9978         return 0;
9979 }
9980
9981 /* mark_btf_func_reg_size() is used when the reg size is determined by
9982  * the BTF func_proto's return value size and argument.
9983  */
9984 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9985                                    size_t reg_size)
9986 {
9987         struct bpf_reg_state *reg = &cur_regs(env)[regno];
9988
9989         if (regno == BPF_REG_0) {
9990                 /* Function return value */
9991                 reg->live |= REG_LIVE_WRITTEN;
9992                 reg->subreg_def = reg_size == sizeof(u64) ?
9993                         DEF_NOT_SUBREG : env->insn_idx + 1;
9994         } else {
9995                 /* Function argument */
9996                 if (reg_size == sizeof(u64)) {
9997                         mark_insn_zext(env, reg);
9998                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9999                 } else {
10000                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10001                 }
10002         }
10003 }
10004
10005 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10006 {
10007         return meta->kfunc_flags & KF_ACQUIRE;
10008 }
10009
10010 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10011 {
10012         return meta->kfunc_flags & KF_RELEASE;
10013 }
10014
10015 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10016 {
10017         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10018 }
10019
10020 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10021 {
10022         return meta->kfunc_flags & KF_SLEEPABLE;
10023 }
10024
10025 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10026 {
10027         return meta->kfunc_flags & KF_DESTRUCTIVE;
10028 }
10029
10030 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10031 {
10032         return meta->kfunc_flags & KF_RCU;
10033 }
10034
10035 static bool __kfunc_param_match_suffix(const struct btf *btf,
10036                                        const struct btf_param *arg,
10037                                        const char *suffix)
10038 {
10039         int suffix_len = strlen(suffix), len;
10040         const char *param_name;
10041
10042         /* In the future, this can be ported to use BTF tagging */
10043         param_name = btf_name_by_offset(btf, arg->name_off);
10044         if (str_is_empty(param_name))
10045                 return false;
10046         len = strlen(param_name);
10047         if (len < suffix_len)
10048                 return false;
10049         param_name += len - suffix_len;
10050         return !strncmp(param_name, suffix, suffix_len);
10051 }
10052
10053 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10054                                   const struct btf_param *arg,
10055                                   const struct bpf_reg_state *reg)
10056 {
10057         const struct btf_type *t;
10058
10059         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10060         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10061                 return false;
10062
10063         return __kfunc_param_match_suffix(btf, arg, "__sz");
10064 }
10065
10066 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10067                                         const struct btf_param *arg,
10068                                         const struct bpf_reg_state *reg)
10069 {
10070         const struct btf_type *t;
10071
10072         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10073         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10074                 return false;
10075
10076         return __kfunc_param_match_suffix(btf, arg, "__szk");
10077 }
10078
10079 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10080 {
10081         return __kfunc_param_match_suffix(btf, arg, "__opt");
10082 }
10083
10084 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10085 {
10086         return __kfunc_param_match_suffix(btf, arg, "__k");
10087 }
10088
10089 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10090 {
10091         return __kfunc_param_match_suffix(btf, arg, "__ign");
10092 }
10093
10094 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10095 {
10096         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10097 }
10098
10099 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10100 {
10101         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10102 }
10103
10104 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10105 {
10106         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10107 }
10108
10109 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10110                                           const struct btf_param *arg,
10111                                           const char *name)
10112 {
10113         int len, target_len = strlen(name);
10114         const char *param_name;
10115
10116         param_name = btf_name_by_offset(btf, arg->name_off);
10117         if (str_is_empty(param_name))
10118                 return false;
10119         len = strlen(param_name);
10120         if (len != target_len)
10121                 return false;
10122         if (strcmp(param_name, name))
10123                 return false;
10124
10125         return true;
10126 }
10127
10128 enum {
10129         KF_ARG_DYNPTR_ID,
10130         KF_ARG_LIST_HEAD_ID,
10131         KF_ARG_LIST_NODE_ID,
10132         KF_ARG_RB_ROOT_ID,
10133         KF_ARG_RB_NODE_ID,
10134 };
10135
10136 BTF_ID_LIST(kf_arg_btf_ids)
10137 BTF_ID(struct, bpf_dynptr_kern)
10138 BTF_ID(struct, bpf_list_head)
10139 BTF_ID(struct, bpf_list_node)
10140 BTF_ID(struct, bpf_rb_root)
10141 BTF_ID(struct, bpf_rb_node)
10142
10143 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10144                                     const struct btf_param *arg, int type)
10145 {
10146         const struct btf_type *t;
10147         u32 res_id;
10148
10149         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10150         if (!t)
10151                 return false;
10152         if (!btf_type_is_ptr(t))
10153                 return false;
10154         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10155         if (!t)
10156                 return false;
10157         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10158 }
10159
10160 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10161 {
10162         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10163 }
10164
10165 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10166 {
10167         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10168 }
10169
10170 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10171 {
10172         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10173 }
10174
10175 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10176 {
10177         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10178 }
10179
10180 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10181 {
10182         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10183 }
10184
10185 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10186                                   const struct btf_param *arg)
10187 {
10188         const struct btf_type *t;
10189
10190         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10191         if (!t)
10192                 return false;
10193
10194         return true;
10195 }
10196
10197 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10198 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10199                                         const struct btf *btf,
10200                                         const struct btf_type *t, int rec)
10201 {
10202         const struct btf_type *member_type;
10203         const struct btf_member *member;
10204         u32 i;
10205
10206         if (!btf_type_is_struct(t))
10207                 return false;
10208
10209         for_each_member(i, t, member) {
10210                 const struct btf_array *array;
10211
10212                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10213                 if (btf_type_is_struct(member_type)) {
10214                         if (rec >= 3) {
10215                                 verbose(env, "max struct nesting depth exceeded\n");
10216                                 return false;
10217                         }
10218                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10219                                 return false;
10220                         continue;
10221                 }
10222                 if (btf_type_is_array(member_type)) {
10223                         array = btf_array(member_type);
10224                         if (!array->nelems)
10225                                 return false;
10226                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10227                         if (!btf_type_is_scalar(member_type))
10228                                 return false;
10229                         continue;
10230                 }
10231                 if (!btf_type_is_scalar(member_type))
10232                         return false;
10233         }
10234         return true;
10235 }
10236
10237 enum kfunc_ptr_arg_type {
10238         KF_ARG_PTR_TO_CTX,
10239         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10240         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10241         KF_ARG_PTR_TO_DYNPTR,
10242         KF_ARG_PTR_TO_ITER,
10243         KF_ARG_PTR_TO_LIST_HEAD,
10244         KF_ARG_PTR_TO_LIST_NODE,
10245         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10246         KF_ARG_PTR_TO_MEM,
10247         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10248         KF_ARG_PTR_TO_CALLBACK,
10249         KF_ARG_PTR_TO_RB_ROOT,
10250         KF_ARG_PTR_TO_RB_NODE,
10251 };
10252
10253 enum special_kfunc_type {
10254         KF_bpf_obj_new_impl,
10255         KF_bpf_obj_drop_impl,
10256         KF_bpf_refcount_acquire_impl,
10257         KF_bpf_list_push_front_impl,
10258         KF_bpf_list_push_back_impl,
10259         KF_bpf_list_pop_front,
10260         KF_bpf_list_pop_back,
10261         KF_bpf_cast_to_kern_ctx,
10262         KF_bpf_rdonly_cast,
10263         KF_bpf_rcu_read_lock,
10264         KF_bpf_rcu_read_unlock,
10265         KF_bpf_rbtree_remove,
10266         KF_bpf_rbtree_add_impl,
10267         KF_bpf_rbtree_first,
10268         KF_bpf_dynptr_from_skb,
10269         KF_bpf_dynptr_from_xdp,
10270         KF_bpf_dynptr_slice,
10271         KF_bpf_dynptr_slice_rdwr,
10272         KF_bpf_dynptr_clone,
10273 };
10274
10275 BTF_SET_START(special_kfunc_set)
10276 BTF_ID(func, bpf_obj_new_impl)
10277 BTF_ID(func, bpf_obj_drop_impl)
10278 BTF_ID(func, bpf_refcount_acquire_impl)
10279 BTF_ID(func, bpf_list_push_front_impl)
10280 BTF_ID(func, bpf_list_push_back_impl)
10281 BTF_ID(func, bpf_list_pop_front)
10282 BTF_ID(func, bpf_list_pop_back)
10283 BTF_ID(func, bpf_cast_to_kern_ctx)
10284 BTF_ID(func, bpf_rdonly_cast)
10285 BTF_ID(func, bpf_rbtree_remove)
10286 BTF_ID(func, bpf_rbtree_add_impl)
10287 BTF_ID(func, bpf_rbtree_first)
10288 BTF_ID(func, bpf_dynptr_from_skb)
10289 BTF_ID(func, bpf_dynptr_from_xdp)
10290 BTF_ID(func, bpf_dynptr_slice)
10291 BTF_ID(func, bpf_dynptr_slice_rdwr)
10292 BTF_ID(func, bpf_dynptr_clone)
10293 BTF_SET_END(special_kfunc_set)
10294
10295 BTF_ID_LIST(special_kfunc_list)
10296 BTF_ID(func, bpf_obj_new_impl)
10297 BTF_ID(func, bpf_obj_drop_impl)
10298 BTF_ID(func, bpf_refcount_acquire_impl)
10299 BTF_ID(func, bpf_list_push_front_impl)
10300 BTF_ID(func, bpf_list_push_back_impl)
10301 BTF_ID(func, bpf_list_pop_front)
10302 BTF_ID(func, bpf_list_pop_back)
10303 BTF_ID(func, bpf_cast_to_kern_ctx)
10304 BTF_ID(func, bpf_rdonly_cast)
10305 BTF_ID(func, bpf_rcu_read_lock)
10306 BTF_ID(func, bpf_rcu_read_unlock)
10307 BTF_ID(func, bpf_rbtree_remove)
10308 BTF_ID(func, bpf_rbtree_add_impl)
10309 BTF_ID(func, bpf_rbtree_first)
10310 BTF_ID(func, bpf_dynptr_from_skb)
10311 BTF_ID(func, bpf_dynptr_from_xdp)
10312 BTF_ID(func, bpf_dynptr_slice)
10313 BTF_ID(func, bpf_dynptr_slice_rdwr)
10314 BTF_ID(func, bpf_dynptr_clone)
10315
10316 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10317 {
10318         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10319             meta->arg_owning_ref) {
10320                 return false;
10321         }
10322
10323         return meta->kfunc_flags & KF_RET_NULL;
10324 }
10325
10326 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10327 {
10328         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10329 }
10330
10331 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10332 {
10333         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10334 }
10335
10336 static enum kfunc_ptr_arg_type
10337 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10338                        struct bpf_kfunc_call_arg_meta *meta,
10339                        const struct btf_type *t, const struct btf_type *ref_t,
10340                        const char *ref_tname, const struct btf_param *args,
10341                        int argno, int nargs)
10342 {
10343         u32 regno = argno + 1;
10344         struct bpf_reg_state *regs = cur_regs(env);
10345         struct bpf_reg_state *reg = &regs[regno];
10346         bool arg_mem_size = false;
10347
10348         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10349                 return KF_ARG_PTR_TO_CTX;
10350
10351         /* In this function, we verify the kfunc's BTF as per the argument type,
10352          * leaving the rest of the verification with respect to the register
10353          * type to our caller. When a set of conditions hold in the BTF type of
10354          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10355          */
10356         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10357                 return KF_ARG_PTR_TO_CTX;
10358
10359         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10360                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10361
10362         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10363                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10364
10365         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10366                 return KF_ARG_PTR_TO_DYNPTR;
10367
10368         if (is_kfunc_arg_iter(meta, argno))
10369                 return KF_ARG_PTR_TO_ITER;
10370
10371         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10372                 return KF_ARG_PTR_TO_LIST_HEAD;
10373
10374         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10375                 return KF_ARG_PTR_TO_LIST_NODE;
10376
10377         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10378                 return KF_ARG_PTR_TO_RB_ROOT;
10379
10380         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10381                 return KF_ARG_PTR_TO_RB_NODE;
10382
10383         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10384                 if (!btf_type_is_struct(ref_t)) {
10385                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10386                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10387                         return -EINVAL;
10388                 }
10389                 return KF_ARG_PTR_TO_BTF_ID;
10390         }
10391
10392         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10393                 return KF_ARG_PTR_TO_CALLBACK;
10394
10395
10396         if (argno + 1 < nargs &&
10397             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10398              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10399                 arg_mem_size = true;
10400
10401         /* This is the catch all argument type of register types supported by
10402          * check_helper_mem_access. However, we only allow when argument type is
10403          * pointer to scalar, or struct composed (recursively) of scalars. When
10404          * arg_mem_size is true, the pointer can be void *.
10405          */
10406         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10407             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10408                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10409                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10410                 return -EINVAL;
10411         }
10412         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10413 }
10414
10415 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10416                                         struct bpf_reg_state *reg,
10417                                         const struct btf_type *ref_t,
10418                                         const char *ref_tname, u32 ref_id,
10419                                         struct bpf_kfunc_call_arg_meta *meta,
10420                                         int argno)
10421 {
10422         const struct btf_type *reg_ref_t;
10423         bool strict_type_match = false;
10424         const struct btf *reg_btf;
10425         const char *reg_ref_tname;
10426         u32 reg_ref_id;
10427
10428         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10429                 reg_btf = reg->btf;
10430                 reg_ref_id = reg->btf_id;
10431         } else {
10432                 reg_btf = btf_vmlinux;
10433                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10434         }
10435
10436         /* Enforce strict type matching for calls to kfuncs that are acquiring
10437          * or releasing a reference, or are no-cast aliases. We do _not_
10438          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10439          * as we want to enable BPF programs to pass types that are bitwise
10440          * equivalent without forcing them to explicitly cast with something
10441          * like bpf_cast_to_kern_ctx().
10442          *
10443          * For example, say we had a type like the following:
10444          *
10445          * struct bpf_cpumask {
10446          *      cpumask_t cpumask;
10447          *      refcount_t usage;
10448          * };
10449          *
10450          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10451          * to a struct cpumask, so it would be safe to pass a struct
10452          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10453          *
10454          * The philosophy here is similar to how we allow scalars of different
10455          * types to be passed to kfuncs as long as the size is the same. The
10456          * only difference here is that we're simply allowing
10457          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10458          * resolve types.
10459          */
10460         if (is_kfunc_acquire(meta) ||
10461             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10462             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10463                 strict_type_match = true;
10464
10465         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10466
10467         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10468         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10469         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10470                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10471                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10472                         btf_type_str(reg_ref_t), reg_ref_tname);
10473                 return -EINVAL;
10474         }
10475         return 0;
10476 }
10477
10478 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10479 {
10480         struct bpf_verifier_state *state = env->cur_state;
10481
10482         if (!state->active_lock.ptr) {
10483                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10484                 return -EFAULT;
10485         }
10486
10487         if (type_flag(reg->type) & NON_OWN_REF) {
10488                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10489                 return -EFAULT;
10490         }
10491
10492         reg->type |= NON_OWN_REF;
10493         return 0;
10494 }
10495
10496 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10497 {
10498         struct bpf_func_state *state, *unused;
10499         struct bpf_reg_state *reg;
10500         int i;
10501
10502         state = cur_func(env);
10503
10504         if (!ref_obj_id) {
10505                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10506                              "owning -> non-owning conversion\n");
10507                 return -EFAULT;
10508         }
10509
10510         for (i = 0; i < state->acquired_refs; i++) {
10511                 if (state->refs[i].id != ref_obj_id)
10512                         continue;
10513
10514                 /* Clear ref_obj_id here so release_reference doesn't clobber
10515                  * the whole reg
10516                  */
10517                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10518                         if (reg->ref_obj_id == ref_obj_id) {
10519                                 reg->ref_obj_id = 0;
10520                                 ref_set_non_owning(env, reg);
10521                         }
10522                 }));
10523                 return 0;
10524         }
10525
10526         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10527         return -EFAULT;
10528 }
10529
10530 /* Implementation details:
10531  *
10532  * Each register points to some region of memory, which we define as an
10533  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10534  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10535  * allocation. The lock and the data it protects are colocated in the same
10536  * memory region.
10537  *
10538  * Hence, everytime a register holds a pointer value pointing to such
10539  * allocation, the verifier preserves a unique reg->id for it.
10540  *
10541  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10542  * bpf_spin_lock is called.
10543  *
10544  * To enable this, lock state in the verifier captures two values:
10545  *      active_lock.ptr = Register's type specific pointer
10546  *      active_lock.id  = A unique ID for each register pointer value
10547  *
10548  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10549  * supported register types.
10550  *
10551  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10552  * allocated objects is the reg->btf pointer.
10553  *
10554  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10555  * can establish the provenance of the map value statically for each distinct
10556  * lookup into such maps. They always contain a single map value hence unique
10557  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10558  *
10559  * So, in case of global variables, they use array maps with max_entries = 1,
10560  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10561  * into the same map value as max_entries is 1, as described above).
10562  *
10563  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10564  * outer map pointer (in verifier context), but each lookup into an inner map
10565  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10566  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10567  * will get different reg->id assigned to each lookup, hence different
10568  * active_lock.id.
10569  *
10570  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10571  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10572  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10573  */
10574 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10575 {
10576         void *ptr;
10577         u32 id;
10578
10579         switch ((int)reg->type) {
10580         case PTR_TO_MAP_VALUE:
10581                 ptr = reg->map_ptr;
10582                 break;
10583         case PTR_TO_BTF_ID | MEM_ALLOC:
10584                 ptr = reg->btf;
10585                 break;
10586         default:
10587                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10588                 return -EFAULT;
10589         }
10590         id = reg->id;
10591
10592         if (!env->cur_state->active_lock.ptr)
10593                 return -EINVAL;
10594         if (env->cur_state->active_lock.ptr != ptr ||
10595             env->cur_state->active_lock.id != id) {
10596                 verbose(env, "held lock and object are not in the same allocation\n");
10597                 return -EINVAL;
10598         }
10599         return 0;
10600 }
10601
10602 static bool is_bpf_list_api_kfunc(u32 btf_id)
10603 {
10604         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10605                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10606                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10607                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10608 }
10609
10610 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10611 {
10612         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10613                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10614                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10615 }
10616
10617 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10618 {
10619         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10620                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10621 }
10622
10623 static bool is_callback_calling_kfunc(u32 btf_id)
10624 {
10625         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10626 }
10627
10628 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10629 {
10630         return is_bpf_rbtree_api_kfunc(btf_id);
10631 }
10632
10633 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10634                                           enum btf_field_type head_field_type,
10635                                           u32 kfunc_btf_id)
10636 {
10637         bool ret;
10638
10639         switch (head_field_type) {
10640         case BPF_LIST_HEAD:
10641                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10642                 break;
10643         case BPF_RB_ROOT:
10644                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10645                 break;
10646         default:
10647                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10648                         btf_field_type_name(head_field_type));
10649                 return false;
10650         }
10651
10652         if (!ret)
10653                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10654                         btf_field_type_name(head_field_type));
10655         return ret;
10656 }
10657
10658 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10659                                           enum btf_field_type node_field_type,
10660                                           u32 kfunc_btf_id)
10661 {
10662         bool ret;
10663
10664         switch (node_field_type) {
10665         case BPF_LIST_NODE:
10666                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10667                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10668                 break;
10669         case BPF_RB_NODE:
10670                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10671                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10672                 break;
10673         default:
10674                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10675                         btf_field_type_name(node_field_type));
10676                 return false;
10677         }
10678
10679         if (!ret)
10680                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10681                         btf_field_type_name(node_field_type));
10682         return ret;
10683 }
10684
10685 static int
10686 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10687                                    struct bpf_reg_state *reg, u32 regno,
10688                                    struct bpf_kfunc_call_arg_meta *meta,
10689                                    enum btf_field_type head_field_type,
10690                                    struct btf_field **head_field)
10691 {
10692         const char *head_type_name;
10693         struct btf_field *field;
10694         struct btf_record *rec;
10695         u32 head_off;
10696
10697         if (meta->btf != btf_vmlinux) {
10698                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10699                 return -EFAULT;
10700         }
10701
10702         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10703                 return -EFAULT;
10704
10705         head_type_name = btf_field_type_name(head_field_type);
10706         if (!tnum_is_const(reg->var_off)) {
10707                 verbose(env,
10708                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10709                         regno, head_type_name);
10710                 return -EINVAL;
10711         }
10712
10713         rec = reg_btf_record(reg);
10714         head_off = reg->off + reg->var_off.value;
10715         field = btf_record_find(rec, head_off, head_field_type);
10716         if (!field) {
10717                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10718                 return -EINVAL;
10719         }
10720
10721         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10722         if (check_reg_allocation_locked(env, reg)) {
10723                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10724                         rec->spin_lock_off, head_type_name);
10725                 return -EINVAL;
10726         }
10727
10728         if (*head_field) {
10729                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10730                 return -EFAULT;
10731         }
10732         *head_field = field;
10733         return 0;
10734 }
10735
10736 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10737                                            struct bpf_reg_state *reg, u32 regno,
10738                                            struct bpf_kfunc_call_arg_meta *meta)
10739 {
10740         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10741                                                           &meta->arg_list_head.field);
10742 }
10743
10744 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10745                                              struct bpf_reg_state *reg, u32 regno,
10746                                              struct bpf_kfunc_call_arg_meta *meta)
10747 {
10748         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10749                                                           &meta->arg_rbtree_root.field);
10750 }
10751
10752 static int
10753 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10754                                    struct bpf_reg_state *reg, u32 regno,
10755                                    struct bpf_kfunc_call_arg_meta *meta,
10756                                    enum btf_field_type head_field_type,
10757                                    enum btf_field_type node_field_type,
10758                                    struct btf_field **node_field)
10759 {
10760         const char *node_type_name;
10761         const struct btf_type *et, *t;
10762         struct btf_field *field;
10763         u32 node_off;
10764
10765         if (meta->btf != btf_vmlinux) {
10766                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10767                 return -EFAULT;
10768         }
10769
10770         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10771                 return -EFAULT;
10772
10773         node_type_name = btf_field_type_name(node_field_type);
10774         if (!tnum_is_const(reg->var_off)) {
10775                 verbose(env,
10776                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10777                         regno, node_type_name);
10778                 return -EINVAL;
10779         }
10780
10781         node_off = reg->off + reg->var_off.value;
10782         field = reg_find_field_offset(reg, node_off, node_field_type);
10783         if (!field || field->offset != node_off) {
10784                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10785                 return -EINVAL;
10786         }
10787
10788         field = *node_field;
10789
10790         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10791         t = btf_type_by_id(reg->btf, reg->btf_id);
10792         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10793                                   field->graph_root.value_btf_id, true)) {
10794                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10795                         "in struct %s, but arg is at offset=%d in struct %s\n",
10796                         btf_field_type_name(head_field_type),
10797                         btf_field_type_name(node_field_type),
10798                         field->graph_root.node_offset,
10799                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10800                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10801                 return -EINVAL;
10802         }
10803         meta->arg_btf = reg->btf;
10804         meta->arg_btf_id = reg->btf_id;
10805
10806         if (node_off != field->graph_root.node_offset) {
10807                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10808                         node_off, btf_field_type_name(node_field_type),
10809                         field->graph_root.node_offset,
10810                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10811                 return -EINVAL;
10812         }
10813
10814         return 0;
10815 }
10816
10817 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10818                                            struct bpf_reg_state *reg, u32 regno,
10819                                            struct bpf_kfunc_call_arg_meta *meta)
10820 {
10821         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10822                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10823                                                   &meta->arg_list_head.field);
10824 }
10825
10826 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10827                                              struct bpf_reg_state *reg, u32 regno,
10828                                              struct bpf_kfunc_call_arg_meta *meta)
10829 {
10830         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10831                                                   BPF_RB_ROOT, BPF_RB_NODE,
10832                                                   &meta->arg_rbtree_root.field);
10833 }
10834
10835 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10836                             int insn_idx)
10837 {
10838         const char *func_name = meta->func_name, *ref_tname;
10839         const struct btf *btf = meta->btf;
10840         const struct btf_param *args;
10841         struct btf_record *rec;
10842         u32 i, nargs;
10843         int ret;
10844
10845         args = (const struct btf_param *)(meta->func_proto + 1);
10846         nargs = btf_type_vlen(meta->func_proto);
10847         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10848                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10849                         MAX_BPF_FUNC_REG_ARGS);
10850                 return -EINVAL;
10851         }
10852
10853         /* Check that BTF function arguments match actual types that the
10854          * verifier sees.
10855          */
10856         for (i = 0; i < nargs; i++) {
10857                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10858                 const struct btf_type *t, *ref_t, *resolve_ret;
10859                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10860                 u32 regno = i + 1, ref_id, type_size;
10861                 bool is_ret_buf_sz = false;
10862                 int kf_arg_type;
10863
10864                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10865
10866                 if (is_kfunc_arg_ignore(btf, &args[i]))
10867                         continue;
10868
10869                 if (btf_type_is_scalar(t)) {
10870                         if (reg->type != SCALAR_VALUE) {
10871                                 verbose(env, "R%d is not a scalar\n", regno);
10872                                 return -EINVAL;
10873                         }
10874
10875                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10876                                 if (meta->arg_constant.found) {
10877                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10878                                         return -EFAULT;
10879                                 }
10880                                 if (!tnum_is_const(reg->var_off)) {
10881                                         verbose(env, "R%d must be a known constant\n", regno);
10882                                         return -EINVAL;
10883                                 }
10884                                 ret = mark_chain_precision(env, regno);
10885                                 if (ret < 0)
10886                                         return ret;
10887                                 meta->arg_constant.found = true;
10888                                 meta->arg_constant.value = reg->var_off.value;
10889                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10890                                 meta->r0_rdonly = true;
10891                                 is_ret_buf_sz = true;
10892                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10893                                 is_ret_buf_sz = true;
10894                         }
10895
10896                         if (is_ret_buf_sz) {
10897                                 if (meta->r0_size) {
10898                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10899                                         return -EINVAL;
10900                                 }
10901
10902                                 if (!tnum_is_const(reg->var_off)) {
10903                                         verbose(env, "R%d is not a const\n", regno);
10904                                         return -EINVAL;
10905                                 }
10906
10907                                 meta->r0_size = reg->var_off.value;
10908                                 ret = mark_chain_precision(env, regno);
10909                                 if (ret)
10910                                         return ret;
10911                         }
10912                         continue;
10913                 }
10914
10915                 if (!btf_type_is_ptr(t)) {
10916                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10917                         return -EINVAL;
10918                 }
10919
10920                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10921                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10922                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10923                         return -EACCES;
10924                 }
10925
10926                 if (reg->ref_obj_id) {
10927                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10928                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10929                                         regno, reg->ref_obj_id,
10930                                         meta->ref_obj_id);
10931                                 return -EFAULT;
10932                         }
10933                         meta->ref_obj_id = reg->ref_obj_id;
10934                         if (is_kfunc_release(meta))
10935                                 meta->release_regno = regno;
10936                 }
10937
10938                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10939                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10940
10941                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10942                 if (kf_arg_type < 0)
10943                         return kf_arg_type;
10944
10945                 switch (kf_arg_type) {
10946                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10947                 case KF_ARG_PTR_TO_BTF_ID:
10948                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10949                                 break;
10950
10951                         if (!is_trusted_reg(reg)) {
10952                                 if (!is_kfunc_rcu(meta)) {
10953                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10954                                         return -EINVAL;
10955                                 }
10956                                 if (!is_rcu_reg(reg)) {
10957                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10958                                         return -EINVAL;
10959                                 }
10960                         }
10961
10962                         fallthrough;
10963                 case KF_ARG_PTR_TO_CTX:
10964                         /* Trusted arguments have the same offset checks as release arguments */
10965                         arg_type |= OBJ_RELEASE;
10966                         break;
10967                 case KF_ARG_PTR_TO_DYNPTR:
10968                 case KF_ARG_PTR_TO_ITER:
10969                 case KF_ARG_PTR_TO_LIST_HEAD:
10970                 case KF_ARG_PTR_TO_LIST_NODE:
10971                 case KF_ARG_PTR_TO_RB_ROOT:
10972                 case KF_ARG_PTR_TO_RB_NODE:
10973                 case KF_ARG_PTR_TO_MEM:
10974                 case KF_ARG_PTR_TO_MEM_SIZE:
10975                 case KF_ARG_PTR_TO_CALLBACK:
10976                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10977                         /* Trusted by default */
10978                         break;
10979                 default:
10980                         WARN_ON_ONCE(1);
10981                         return -EFAULT;
10982                 }
10983
10984                 if (is_kfunc_release(meta) && reg->ref_obj_id)
10985                         arg_type |= OBJ_RELEASE;
10986                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10987                 if (ret < 0)
10988                         return ret;
10989
10990                 switch (kf_arg_type) {
10991                 case KF_ARG_PTR_TO_CTX:
10992                         if (reg->type != PTR_TO_CTX) {
10993                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10994                                 return -EINVAL;
10995                         }
10996
10997                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10998                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10999                                 if (ret < 0)
11000                                         return -EINVAL;
11001                                 meta->ret_btf_id  = ret;
11002                         }
11003                         break;
11004                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11005                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11006                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11007                                 return -EINVAL;
11008                         }
11009                         if (!reg->ref_obj_id) {
11010                                 verbose(env, "allocated object must be referenced\n");
11011                                 return -EINVAL;
11012                         }
11013                         if (meta->btf == btf_vmlinux &&
11014                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11015                                 meta->arg_btf = reg->btf;
11016                                 meta->arg_btf_id = reg->btf_id;
11017                         }
11018                         break;
11019                 case KF_ARG_PTR_TO_DYNPTR:
11020                 {
11021                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11022                         int clone_ref_obj_id = 0;
11023
11024                         if (reg->type != PTR_TO_STACK &&
11025                             reg->type != CONST_PTR_TO_DYNPTR) {
11026                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11027                                 return -EINVAL;
11028                         }
11029
11030                         if (reg->type == CONST_PTR_TO_DYNPTR)
11031                                 dynptr_arg_type |= MEM_RDONLY;
11032
11033                         if (is_kfunc_arg_uninit(btf, &args[i]))
11034                                 dynptr_arg_type |= MEM_UNINIT;
11035
11036                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11037                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11038                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11039                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11040                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11041                                    (dynptr_arg_type & MEM_UNINIT)) {
11042                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11043
11044                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11045                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11046                                         return -EFAULT;
11047                                 }
11048
11049                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11050                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11051                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11052                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11053                                         return -EFAULT;
11054                                 }
11055                         }
11056
11057                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11058                         if (ret < 0)
11059                                 return ret;
11060
11061                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11062                                 int id = dynptr_id(env, reg);
11063
11064                                 if (id < 0) {
11065                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11066                                         return id;
11067                                 }
11068                                 meta->initialized_dynptr.id = id;
11069                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11070                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11071                         }
11072
11073                         break;
11074                 }
11075                 case KF_ARG_PTR_TO_ITER:
11076                         ret = process_iter_arg(env, regno, insn_idx, meta);
11077                         if (ret < 0)
11078                                 return ret;
11079                         break;
11080                 case KF_ARG_PTR_TO_LIST_HEAD:
11081                         if (reg->type != PTR_TO_MAP_VALUE &&
11082                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11083                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11084                                 return -EINVAL;
11085                         }
11086                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11087                                 verbose(env, "allocated object must be referenced\n");
11088                                 return -EINVAL;
11089                         }
11090                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11091                         if (ret < 0)
11092                                 return ret;
11093                         break;
11094                 case KF_ARG_PTR_TO_RB_ROOT:
11095                         if (reg->type != PTR_TO_MAP_VALUE &&
11096                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11097                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11098                                 return -EINVAL;
11099                         }
11100                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11101                                 verbose(env, "allocated object must be referenced\n");
11102                                 return -EINVAL;
11103                         }
11104                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11105                         if (ret < 0)
11106                                 return ret;
11107                         break;
11108                 case KF_ARG_PTR_TO_LIST_NODE:
11109                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11110                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11111                                 return -EINVAL;
11112                         }
11113                         if (!reg->ref_obj_id) {
11114                                 verbose(env, "allocated object must be referenced\n");
11115                                 return -EINVAL;
11116                         }
11117                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11118                         if (ret < 0)
11119                                 return ret;
11120                         break;
11121                 case KF_ARG_PTR_TO_RB_NODE:
11122                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11123                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11124                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11125                                         return -EINVAL;
11126                                 }
11127                                 if (in_rbtree_lock_required_cb(env)) {
11128                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11129                                         return -EINVAL;
11130                                 }
11131                         } else {
11132                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11133                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11134                                         return -EINVAL;
11135                                 }
11136                                 if (!reg->ref_obj_id) {
11137                                         verbose(env, "allocated object must be referenced\n");
11138                                         return -EINVAL;
11139                                 }
11140                         }
11141
11142                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11143                         if (ret < 0)
11144                                 return ret;
11145                         break;
11146                 case KF_ARG_PTR_TO_BTF_ID:
11147                         /* Only base_type is checked, further checks are done here */
11148                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11149                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11150                             !reg2btf_ids[base_type(reg->type)]) {
11151                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11152                                 verbose(env, "expected %s or socket\n",
11153                                         reg_type_str(env, base_type(reg->type) |
11154                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11155                                 return -EINVAL;
11156                         }
11157                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11158                         if (ret < 0)
11159                                 return ret;
11160                         break;
11161                 case KF_ARG_PTR_TO_MEM:
11162                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11163                         if (IS_ERR(resolve_ret)) {
11164                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11165                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11166                                 return -EINVAL;
11167                         }
11168                         ret = check_mem_reg(env, reg, regno, type_size);
11169                         if (ret < 0)
11170                                 return ret;
11171                         break;
11172                 case KF_ARG_PTR_TO_MEM_SIZE:
11173                 {
11174                         struct bpf_reg_state *buff_reg = &regs[regno];
11175                         const struct btf_param *buff_arg = &args[i];
11176                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11177                         const struct btf_param *size_arg = &args[i + 1];
11178
11179                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11180                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11181                                 if (ret < 0) {
11182                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11183                                         return ret;
11184                                 }
11185                         }
11186
11187                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11188                                 if (meta->arg_constant.found) {
11189                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11190                                         return -EFAULT;
11191                                 }
11192                                 if (!tnum_is_const(size_reg->var_off)) {
11193                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11194                                         return -EINVAL;
11195                                 }
11196                                 meta->arg_constant.found = true;
11197                                 meta->arg_constant.value = size_reg->var_off.value;
11198                         }
11199
11200                         /* Skip next '__sz' or '__szk' argument */
11201                         i++;
11202                         break;
11203                 }
11204                 case KF_ARG_PTR_TO_CALLBACK:
11205                         meta->subprogno = reg->subprogno;
11206                         break;
11207                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11208                         if (!type_is_ptr_alloc_obj(reg->type)) {
11209                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11210                                 return -EINVAL;
11211                         }
11212                         if (!type_is_non_owning_ref(reg->type))
11213                                 meta->arg_owning_ref = true;
11214
11215                         rec = reg_btf_record(reg);
11216                         if (!rec) {
11217                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11218                                 return -EFAULT;
11219                         }
11220
11221                         if (rec->refcount_off < 0) {
11222                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11223                                 return -EINVAL;
11224                         }
11225                         if (rec->refcount_off >= 0) {
11226                                 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11227                                 return -EINVAL;
11228                         }
11229                         meta->arg_btf = reg->btf;
11230                         meta->arg_btf_id = reg->btf_id;
11231                         break;
11232                 }
11233         }
11234
11235         if (is_kfunc_release(meta) && !meta->release_regno) {
11236                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11237                         func_name);
11238                 return -EINVAL;
11239         }
11240
11241         return 0;
11242 }
11243
11244 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11245                             struct bpf_insn *insn,
11246                             struct bpf_kfunc_call_arg_meta *meta,
11247                             const char **kfunc_name)
11248 {
11249         const struct btf_type *func, *func_proto;
11250         u32 func_id, *kfunc_flags;
11251         const char *func_name;
11252         struct btf *desc_btf;
11253
11254         if (kfunc_name)
11255                 *kfunc_name = NULL;
11256
11257         if (!insn->imm)
11258                 return -EINVAL;
11259
11260         desc_btf = find_kfunc_desc_btf(env, insn->off);
11261         if (IS_ERR(desc_btf))
11262                 return PTR_ERR(desc_btf);
11263
11264         func_id = insn->imm;
11265         func = btf_type_by_id(desc_btf, func_id);
11266         func_name = btf_name_by_offset(desc_btf, func->name_off);
11267         if (kfunc_name)
11268                 *kfunc_name = func_name;
11269         func_proto = btf_type_by_id(desc_btf, func->type);
11270
11271         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11272         if (!kfunc_flags) {
11273                 return -EACCES;
11274         }
11275
11276         memset(meta, 0, sizeof(*meta));
11277         meta->btf = desc_btf;
11278         meta->func_id = func_id;
11279         meta->kfunc_flags = *kfunc_flags;
11280         meta->func_proto = func_proto;
11281         meta->func_name = func_name;
11282
11283         return 0;
11284 }
11285
11286 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11287                             int *insn_idx_p)
11288 {
11289         const struct btf_type *t, *ptr_type;
11290         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11291         struct bpf_reg_state *regs = cur_regs(env);
11292         const char *func_name, *ptr_type_name;
11293         bool sleepable, rcu_lock, rcu_unlock;
11294         struct bpf_kfunc_call_arg_meta meta;
11295         struct bpf_insn_aux_data *insn_aux;
11296         int err, insn_idx = *insn_idx_p;
11297         const struct btf_param *args;
11298         const struct btf_type *ret_t;
11299         struct btf *desc_btf;
11300
11301         /* skip for now, but return error when we find this in fixup_kfunc_call */
11302         if (!insn->imm)
11303                 return 0;
11304
11305         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11306         if (err == -EACCES && func_name)
11307                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11308         if (err)
11309                 return err;
11310         desc_btf = meta.btf;
11311         insn_aux = &env->insn_aux_data[insn_idx];
11312
11313         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11314
11315         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11316                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11317                 return -EACCES;
11318         }
11319
11320         sleepable = is_kfunc_sleepable(&meta);
11321         if (sleepable && !env->prog->aux->sleepable) {
11322                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11323                 return -EACCES;
11324         }
11325
11326         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11327         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11328
11329         if (env->cur_state->active_rcu_lock) {
11330                 struct bpf_func_state *state;
11331                 struct bpf_reg_state *reg;
11332
11333                 if (rcu_lock) {
11334                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11335                         return -EINVAL;
11336                 } else if (rcu_unlock) {
11337                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11338                                 if (reg->type & MEM_RCU) {
11339                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11340                                         reg->type |= PTR_UNTRUSTED;
11341                                 }
11342                         }));
11343                         env->cur_state->active_rcu_lock = false;
11344                 } else if (sleepable) {
11345                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11346                         return -EACCES;
11347                 }
11348         } else if (rcu_lock) {
11349                 env->cur_state->active_rcu_lock = true;
11350         } else if (rcu_unlock) {
11351                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11352                 return -EINVAL;
11353         }
11354
11355         /* Check the arguments */
11356         err = check_kfunc_args(env, &meta, insn_idx);
11357         if (err < 0)
11358                 return err;
11359         /* In case of release function, we get register number of refcounted
11360          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11361          */
11362         if (meta.release_regno) {
11363                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11364                 if (err) {
11365                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11366                                 func_name, meta.func_id);
11367                         return err;
11368                 }
11369         }
11370
11371         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11372             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11373             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11374                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11375                 insn_aux->insert_off = regs[BPF_REG_2].off;
11376                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11377                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11378                 if (err) {
11379                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11380                                 func_name, meta.func_id);
11381                         return err;
11382                 }
11383
11384                 err = release_reference(env, release_ref_obj_id);
11385                 if (err) {
11386                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11387                                 func_name, meta.func_id);
11388                         return err;
11389                 }
11390         }
11391
11392         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11393                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11394                                         set_rbtree_add_callback_state);
11395                 if (err) {
11396                         verbose(env, "kfunc %s#%d failed callback verification\n",
11397                                 func_name, meta.func_id);
11398                         return err;
11399                 }
11400         }
11401
11402         for (i = 0; i < CALLER_SAVED_REGS; i++)
11403                 mark_reg_not_init(env, regs, caller_saved[i]);
11404
11405         /* Check return type */
11406         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11407
11408         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11409                 /* Only exception is bpf_obj_new_impl */
11410                 if (meta.btf != btf_vmlinux ||
11411                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11412                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11413                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11414                         return -EINVAL;
11415                 }
11416         }
11417
11418         if (btf_type_is_scalar(t)) {
11419                 mark_reg_unknown(env, regs, BPF_REG_0);
11420                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11421         } else if (btf_type_is_ptr(t)) {
11422                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11423
11424                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11425                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11426                                 struct btf *ret_btf;
11427                                 u32 ret_btf_id;
11428
11429                                 if (unlikely(!bpf_global_ma_set))
11430                                         return -ENOMEM;
11431
11432                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11433                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11434                                         return -EINVAL;
11435                                 }
11436
11437                                 ret_btf = env->prog->aux->btf;
11438                                 ret_btf_id = meta.arg_constant.value;
11439
11440                                 /* This may be NULL due to user not supplying a BTF */
11441                                 if (!ret_btf) {
11442                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11443                                         return -EINVAL;
11444                                 }
11445
11446                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11447                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11448                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11449                                         return -EINVAL;
11450                                 }
11451
11452                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11453                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11454                                 regs[BPF_REG_0].btf = ret_btf;
11455                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11456
11457                                 insn_aux->obj_new_size = ret_t->size;
11458                                 insn_aux->kptr_struct_meta =
11459                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11460                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11461                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11462                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11463                                 regs[BPF_REG_0].btf = meta.arg_btf;
11464                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11465
11466                                 insn_aux->kptr_struct_meta =
11467                                         btf_find_struct_meta(meta.arg_btf,
11468                                                              meta.arg_btf_id);
11469                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11470                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11471                                 struct btf_field *field = meta.arg_list_head.field;
11472
11473                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11474                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11475                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11476                                 struct btf_field *field = meta.arg_rbtree_root.field;
11477
11478                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11479                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11480                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11481                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11482                                 regs[BPF_REG_0].btf = desc_btf;
11483                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11484                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11485                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11486                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11487                                         verbose(env,
11488                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11489                                         return -EINVAL;
11490                                 }
11491
11492                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11493                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11494                                 regs[BPF_REG_0].btf = desc_btf;
11495                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11496                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11497                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11498                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11499
11500                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11501
11502                                 if (!meta.arg_constant.found) {
11503                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11504                                         return -EFAULT;
11505                                 }
11506
11507                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11508
11509                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11510                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11511
11512                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11513                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11514                                 } else {
11515                                         /* this will set env->seen_direct_write to true */
11516                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11517                                                 verbose(env, "the prog does not allow writes to packet data\n");
11518                                                 return -EINVAL;
11519                                         }
11520                                 }
11521
11522                                 if (!meta.initialized_dynptr.id) {
11523                                         verbose(env, "verifier internal error: no dynptr id\n");
11524                                         return -EFAULT;
11525                                 }
11526                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11527
11528                                 /* we don't need to set BPF_REG_0's ref obj id
11529                                  * because packet slices are not refcounted (see
11530                                  * dynptr_type_refcounted)
11531                                  */
11532                         } else {
11533                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11534                                         meta.func_name);
11535                                 return -EFAULT;
11536                         }
11537                 } else if (!__btf_type_is_struct(ptr_type)) {
11538                         if (!meta.r0_size) {
11539                                 __u32 sz;
11540
11541                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11542                                         meta.r0_size = sz;
11543                                         meta.r0_rdonly = true;
11544                                 }
11545                         }
11546                         if (!meta.r0_size) {
11547                                 ptr_type_name = btf_name_by_offset(desc_btf,
11548                                                                    ptr_type->name_off);
11549                                 verbose(env,
11550                                         "kernel function %s returns pointer type %s %s is not supported\n",
11551                                         func_name,
11552                                         btf_type_str(ptr_type),
11553                                         ptr_type_name);
11554                                 return -EINVAL;
11555                         }
11556
11557                         mark_reg_known_zero(env, regs, BPF_REG_0);
11558                         regs[BPF_REG_0].type = PTR_TO_MEM;
11559                         regs[BPF_REG_0].mem_size = meta.r0_size;
11560
11561                         if (meta.r0_rdonly)
11562                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11563
11564                         /* Ensures we don't access the memory after a release_reference() */
11565                         if (meta.ref_obj_id)
11566                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11567                 } else {
11568                         mark_reg_known_zero(env, regs, BPF_REG_0);
11569                         regs[BPF_REG_0].btf = desc_btf;
11570                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11571                         regs[BPF_REG_0].btf_id = ptr_type_id;
11572                 }
11573
11574                 if (is_kfunc_ret_null(&meta)) {
11575                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11576                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11577                         regs[BPF_REG_0].id = ++env->id_gen;
11578                 }
11579                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11580                 if (is_kfunc_acquire(&meta)) {
11581                         int id = acquire_reference_state(env, insn_idx);
11582
11583                         if (id < 0)
11584                                 return id;
11585                         if (is_kfunc_ret_null(&meta))
11586                                 regs[BPF_REG_0].id = id;
11587                         regs[BPF_REG_0].ref_obj_id = id;
11588                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11589                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11590                 }
11591
11592                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11593                         regs[BPF_REG_0].id = ++env->id_gen;
11594         } else if (btf_type_is_void(t)) {
11595                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11596                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11597                                 insn_aux->kptr_struct_meta =
11598                                         btf_find_struct_meta(meta.arg_btf,
11599                                                              meta.arg_btf_id);
11600                         }
11601                 }
11602         }
11603
11604         nargs = btf_type_vlen(meta.func_proto);
11605         args = (const struct btf_param *)(meta.func_proto + 1);
11606         for (i = 0; i < nargs; i++) {
11607                 u32 regno = i + 1;
11608
11609                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11610                 if (btf_type_is_ptr(t))
11611                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11612                 else
11613                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11614                         mark_btf_func_reg_size(env, regno, t->size);
11615         }
11616
11617         if (is_iter_next_kfunc(&meta)) {
11618                 err = process_iter_next_call(env, insn_idx, &meta);
11619                 if (err)
11620                         return err;
11621         }
11622
11623         return 0;
11624 }
11625
11626 static bool signed_add_overflows(s64 a, s64 b)
11627 {
11628         /* Do the add in u64, where overflow is well-defined */
11629         s64 res = (s64)((u64)a + (u64)b);
11630
11631         if (b < 0)
11632                 return res > a;
11633         return res < a;
11634 }
11635
11636 static bool signed_add32_overflows(s32 a, s32 b)
11637 {
11638         /* Do the add in u32, where overflow is well-defined */
11639         s32 res = (s32)((u32)a + (u32)b);
11640
11641         if (b < 0)
11642                 return res > a;
11643         return res < a;
11644 }
11645
11646 static bool signed_sub_overflows(s64 a, s64 b)
11647 {
11648         /* Do the sub in u64, where overflow is well-defined */
11649         s64 res = (s64)((u64)a - (u64)b);
11650
11651         if (b < 0)
11652                 return res < a;
11653         return res > a;
11654 }
11655
11656 static bool signed_sub32_overflows(s32 a, s32 b)
11657 {
11658         /* Do the sub in u32, where overflow is well-defined */
11659         s32 res = (s32)((u32)a - (u32)b);
11660
11661         if (b < 0)
11662                 return res < a;
11663         return res > a;
11664 }
11665
11666 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11667                                   const struct bpf_reg_state *reg,
11668                                   enum bpf_reg_type type)
11669 {
11670         bool known = tnum_is_const(reg->var_off);
11671         s64 val = reg->var_off.value;
11672         s64 smin = reg->smin_value;
11673
11674         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11675                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11676                         reg_type_str(env, type), val);
11677                 return false;
11678         }
11679
11680         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11681                 verbose(env, "%s pointer offset %d is not allowed\n",
11682                         reg_type_str(env, type), reg->off);
11683                 return false;
11684         }
11685
11686         if (smin == S64_MIN) {
11687                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11688                         reg_type_str(env, type));
11689                 return false;
11690         }
11691
11692         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11693                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11694                         smin, reg_type_str(env, type));
11695                 return false;
11696         }
11697
11698         return true;
11699 }
11700
11701 enum {
11702         REASON_BOUNDS   = -1,
11703         REASON_TYPE     = -2,
11704         REASON_PATHS    = -3,
11705         REASON_LIMIT    = -4,
11706         REASON_STACK    = -5,
11707 };
11708
11709 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11710                               u32 *alu_limit, bool mask_to_left)
11711 {
11712         u32 max = 0, ptr_limit = 0;
11713
11714         switch (ptr_reg->type) {
11715         case PTR_TO_STACK:
11716                 /* Offset 0 is out-of-bounds, but acceptable start for the
11717                  * left direction, see BPF_REG_FP. Also, unknown scalar
11718                  * offset where we would need to deal with min/max bounds is
11719                  * currently prohibited for unprivileged.
11720                  */
11721                 max = MAX_BPF_STACK + mask_to_left;
11722                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11723                 break;
11724         case PTR_TO_MAP_VALUE:
11725                 max = ptr_reg->map_ptr->value_size;
11726                 ptr_limit = (mask_to_left ?
11727                              ptr_reg->smin_value :
11728                              ptr_reg->umax_value) + ptr_reg->off;
11729                 break;
11730         default:
11731                 return REASON_TYPE;
11732         }
11733
11734         if (ptr_limit >= max)
11735                 return REASON_LIMIT;
11736         *alu_limit = ptr_limit;
11737         return 0;
11738 }
11739
11740 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11741                                     const struct bpf_insn *insn)
11742 {
11743         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11744 }
11745
11746 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11747                                        u32 alu_state, u32 alu_limit)
11748 {
11749         /* If we arrived here from different branches with different
11750          * state or limits to sanitize, then this won't work.
11751          */
11752         if (aux->alu_state &&
11753             (aux->alu_state != alu_state ||
11754              aux->alu_limit != alu_limit))
11755                 return REASON_PATHS;
11756
11757         /* Corresponding fixup done in do_misc_fixups(). */
11758         aux->alu_state = alu_state;
11759         aux->alu_limit = alu_limit;
11760         return 0;
11761 }
11762
11763 static int sanitize_val_alu(struct bpf_verifier_env *env,
11764                             struct bpf_insn *insn)
11765 {
11766         struct bpf_insn_aux_data *aux = cur_aux(env);
11767
11768         if (can_skip_alu_sanitation(env, insn))
11769                 return 0;
11770
11771         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11772 }
11773
11774 static bool sanitize_needed(u8 opcode)
11775 {
11776         return opcode == BPF_ADD || opcode == BPF_SUB;
11777 }
11778
11779 struct bpf_sanitize_info {
11780         struct bpf_insn_aux_data aux;
11781         bool mask_to_left;
11782 };
11783
11784 static struct bpf_verifier_state *
11785 sanitize_speculative_path(struct bpf_verifier_env *env,
11786                           const struct bpf_insn *insn,
11787                           u32 next_idx, u32 curr_idx)
11788 {
11789         struct bpf_verifier_state *branch;
11790         struct bpf_reg_state *regs;
11791
11792         branch = push_stack(env, next_idx, curr_idx, true);
11793         if (branch && insn) {
11794                 regs = branch->frame[branch->curframe]->regs;
11795                 if (BPF_SRC(insn->code) == BPF_K) {
11796                         mark_reg_unknown(env, regs, insn->dst_reg);
11797                 } else if (BPF_SRC(insn->code) == BPF_X) {
11798                         mark_reg_unknown(env, regs, insn->dst_reg);
11799                         mark_reg_unknown(env, regs, insn->src_reg);
11800                 }
11801         }
11802         return branch;
11803 }
11804
11805 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11806                             struct bpf_insn *insn,
11807                             const struct bpf_reg_state *ptr_reg,
11808                             const struct bpf_reg_state *off_reg,
11809                             struct bpf_reg_state *dst_reg,
11810                             struct bpf_sanitize_info *info,
11811                             const bool commit_window)
11812 {
11813         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11814         struct bpf_verifier_state *vstate = env->cur_state;
11815         bool off_is_imm = tnum_is_const(off_reg->var_off);
11816         bool off_is_neg = off_reg->smin_value < 0;
11817         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11818         u8 opcode = BPF_OP(insn->code);
11819         u32 alu_state, alu_limit;
11820         struct bpf_reg_state tmp;
11821         bool ret;
11822         int err;
11823
11824         if (can_skip_alu_sanitation(env, insn))
11825                 return 0;
11826
11827         /* We already marked aux for masking from non-speculative
11828          * paths, thus we got here in the first place. We only care
11829          * to explore bad access from here.
11830          */
11831         if (vstate->speculative)
11832                 goto do_sim;
11833
11834         if (!commit_window) {
11835                 if (!tnum_is_const(off_reg->var_off) &&
11836                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11837                         return REASON_BOUNDS;
11838
11839                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11840                                      (opcode == BPF_SUB && !off_is_neg);
11841         }
11842
11843         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11844         if (err < 0)
11845                 return err;
11846
11847         if (commit_window) {
11848                 /* In commit phase we narrow the masking window based on
11849                  * the observed pointer move after the simulated operation.
11850                  */
11851                 alu_state = info->aux.alu_state;
11852                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11853         } else {
11854                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11855                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11856                 alu_state |= ptr_is_dst_reg ?
11857                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11858
11859                 /* Limit pruning on unknown scalars to enable deep search for
11860                  * potential masking differences from other program paths.
11861                  */
11862                 if (!off_is_imm)
11863                         env->explore_alu_limits = true;
11864         }
11865
11866         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11867         if (err < 0)
11868                 return err;
11869 do_sim:
11870         /* If we're in commit phase, we're done here given we already
11871          * pushed the truncated dst_reg into the speculative verification
11872          * stack.
11873          *
11874          * Also, when register is a known constant, we rewrite register-based
11875          * operation to immediate-based, and thus do not need masking (and as
11876          * a consequence, do not need to simulate the zero-truncation either).
11877          */
11878         if (commit_window || off_is_imm)
11879                 return 0;
11880
11881         /* Simulate and find potential out-of-bounds access under
11882          * speculative execution from truncation as a result of
11883          * masking when off was not within expected range. If off
11884          * sits in dst, then we temporarily need to move ptr there
11885          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11886          * for cases where we use K-based arithmetic in one direction
11887          * and truncated reg-based in the other in order to explore
11888          * bad access.
11889          */
11890         if (!ptr_is_dst_reg) {
11891                 tmp = *dst_reg;
11892                 copy_register_state(dst_reg, ptr_reg);
11893         }
11894         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11895                                         env->insn_idx);
11896         if (!ptr_is_dst_reg && ret)
11897                 *dst_reg = tmp;
11898         return !ret ? REASON_STACK : 0;
11899 }
11900
11901 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11902 {
11903         struct bpf_verifier_state *vstate = env->cur_state;
11904
11905         /* If we simulate paths under speculation, we don't update the
11906          * insn as 'seen' such that when we verify unreachable paths in
11907          * the non-speculative domain, sanitize_dead_code() can still
11908          * rewrite/sanitize them.
11909          */
11910         if (!vstate->speculative)
11911                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11912 }
11913
11914 static int sanitize_err(struct bpf_verifier_env *env,
11915                         const struct bpf_insn *insn, int reason,
11916                         const struct bpf_reg_state *off_reg,
11917                         const struct bpf_reg_state *dst_reg)
11918 {
11919         static const char *err = "pointer arithmetic with it prohibited for !root";
11920         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11921         u32 dst = insn->dst_reg, src = insn->src_reg;
11922
11923         switch (reason) {
11924         case REASON_BOUNDS:
11925                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11926                         off_reg == dst_reg ? dst : src, err);
11927                 break;
11928         case REASON_TYPE:
11929                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11930                         off_reg == dst_reg ? src : dst, err);
11931                 break;
11932         case REASON_PATHS:
11933                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11934                         dst, op, err);
11935                 break;
11936         case REASON_LIMIT:
11937                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11938                         dst, op, err);
11939                 break;
11940         case REASON_STACK:
11941                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11942                         dst, err);
11943                 break;
11944         default:
11945                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11946                         reason);
11947                 break;
11948         }
11949
11950         return -EACCES;
11951 }
11952
11953 /* check that stack access falls within stack limits and that 'reg' doesn't
11954  * have a variable offset.
11955  *
11956  * Variable offset is prohibited for unprivileged mode for simplicity since it
11957  * requires corresponding support in Spectre masking for stack ALU.  See also
11958  * retrieve_ptr_limit().
11959  *
11960  *
11961  * 'off' includes 'reg->off'.
11962  */
11963 static int check_stack_access_for_ptr_arithmetic(
11964                                 struct bpf_verifier_env *env,
11965                                 int regno,
11966                                 const struct bpf_reg_state *reg,
11967                                 int off)
11968 {
11969         if (!tnum_is_const(reg->var_off)) {
11970                 char tn_buf[48];
11971
11972                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11973                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11974                         regno, tn_buf, off);
11975                 return -EACCES;
11976         }
11977
11978         if (off >= 0 || off < -MAX_BPF_STACK) {
11979                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11980                         "prohibited for !root; off=%d\n", regno, off);
11981                 return -EACCES;
11982         }
11983
11984         return 0;
11985 }
11986
11987 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11988                                  const struct bpf_insn *insn,
11989                                  const struct bpf_reg_state *dst_reg)
11990 {
11991         u32 dst = insn->dst_reg;
11992
11993         /* For unprivileged we require that resulting offset must be in bounds
11994          * in order to be able to sanitize access later on.
11995          */
11996         if (env->bypass_spec_v1)
11997                 return 0;
11998
11999         switch (dst_reg->type) {
12000         case PTR_TO_STACK:
12001                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12002                                         dst_reg->off + dst_reg->var_off.value))
12003                         return -EACCES;
12004                 break;
12005         case PTR_TO_MAP_VALUE:
12006                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12007                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12008                                 "prohibited for !root\n", dst);
12009                         return -EACCES;
12010                 }
12011                 break;
12012         default:
12013                 break;
12014         }
12015
12016         return 0;
12017 }
12018
12019 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12020  * Caller should also handle BPF_MOV case separately.
12021  * If we return -EACCES, caller may want to try again treating pointer as a
12022  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12023  */
12024 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12025                                    struct bpf_insn *insn,
12026                                    const struct bpf_reg_state *ptr_reg,
12027                                    const struct bpf_reg_state *off_reg)
12028 {
12029         struct bpf_verifier_state *vstate = env->cur_state;
12030         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12031         struct bpf_reg_state *regs = state->regs, *dst_reg;
12032         bool known = tnum_is_const(off_reg->var_off);
12033         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12034             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12035         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12036             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12037         struct bpf_sanitize_info info = {};
12038         u8 opcode = BPF_OP(insn->code);
12039         u32 dst = insn->dst_reg;
12040         int ret;
12041
12042         dst_reg = &regs[dst];
12043
12044         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12045             smin_val > smax_val || umin_val > umax_val) {
12046                 /* Taint dst register if offset had invalid bounds derived from
12047                  * e.g. dead branches.
12048                  */
12049                 __mark_reg_unknown(env, dst_reg);
12050                 return 0;
12051         }
12052
12053         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12054                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12055                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12056                         __mark_reg_unknown(env, dst_reg);
12057                         return 0;
12058                 }
12059
12060                 verbose(env,
12061                         "R%d 32-bit pointer arithmetic prohibited\n",
12062                         dst);
12063                 return -EACCES;
12064         }
12065
12066         if (ptr_reg->type & PTR_MAYBE_NULL) {
12067                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12068                         dst, reg_type_str(env, ptr_reg->type));
12069                 return -EACCES;
12070         }
12071
12072         switch (base_type(ptr_reg->type)) {
12073         case CONST_PTR_TO_MAP:
12074                 /* smin_val represents the known value */
12075                 if (known && smin_val == 0 && opcode == BPF_ADD)
12076                         break;
12077                 fallthrough;
12078         case PTR_TO_PACKET_END:
12079         case PTR_TO_SOCKET:
12080         case PTR_TO_SOCK_COMMON:
12081         case PTR_TO_TCP_SOCK:
12082         case PTR_TO_XDP_SOCK:
12083                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12084                         dst, reg_type_str(env, ptr_reg->type));
12085                 return -EACCES;
12086         default:
12087                 break;
12088         }
12089
12090         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12091          * The id may be overwritten later if we create a new variable offset.
12092          */
12093         dst_reg->type = ptr_reg->type;
12094         dst_reg->id = ptr_reg->id;
12095
12096         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12097             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12098                 return -EINVAL;
12099
12100         /* pointer types do not carry 32-bit bounds at the moment. */
12101         __mark_reg32_unbounded(dst_reg);
12102
12103         if (sanitize_needed(opcode)) {
12104                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12105                                        &info, false);
12106                 if (ret < 0)
12107                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12108         }
12109
12110         switch (opcode) {
12111         case BPF_ADD:
12112                 /* We can take a fixed offset as long as it doesn't overflow
12113                  * the s32 'off' field
12114                  */
12115                 if (known && (ptr_reg->off + smin_val ==
12116                               (s64)(s32)(ptr_reg->off + smin_val))) {
12117                         /* pointer += K.  Accumulate it into fixed offset */
12118                         dst_reg->smin_value = smin_ptr;
12119                         dst_reg->smax_value = smax_ptr;
12120                         dst_reg->umin_value = umin_ptr;
12121                         dst_reg->umax_value = umax_ptr;
12122                         dst_reg->var_off = ptr_reg->var_off;
12123                         dst_reg->off = ptr_reg->off + smin_val;
12124                         dst_reg->raw = ptr_reg->raw;
12125                         break;
12126                 }
12127                 /* A new variable offset is created.  Note that off_reg->off
12128                  * == 0, since it's a scalar.
12129                  * dst_reg gets the pointer type and since some positive
12130                  * integer value was added to the pointer, give it a new 'id'
12131                  * if it's a PTR_TO_PACKET.
12132                  * this creates a new 'base' pointer, off_reg (variable) gets
12133                  * added into the variable offset, and we copy the fixed offset
12134                  * from ptr_reg.
12135                  */
12136                 if (signed_add_overflows(smin_ptr, smin_val) ||
12137                     signed_add_overflows(smax_ptr, smax_val)) {
12138                         dst_reg->smin_value = S64_MIN;
12139                         dst_reg->smax_value = S64_MAX;
12140                 } else {
12141                         dst_reg->smin_value = smin_ptr + smin_val;
12142                         dst_reg->smax_value = smax_ptr + smax_val;
12143                 }
12144                 if (umin_ptr + umin_val < umin_ptr ||
12145                     umax_ptr + umax_val < umax_ptr) {
12146                         dst_reg->umin_value = 0;
12147                         dst_reg->umax_value = U64_MAX;
12148                 } else {
12149                         dst_reg->umin_value = umin_ptr + umin_val;
12150                         dst_reg->umax_value = umax_ptr + umax_val;
12151                 }
12152                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12153                 dst_reg->off = ptr_reg->off;
12154                 dst_reg->raw = ptr_reg->raw;
12155                 if (reg_is_pkt_pointer(ptr_reg)) {
12156                         dst_reg->id = ++env->id_gen;
12157                         /* something was added to pkt_ptr, set range to zero */
12158                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12159                 }
12160                 break;
12161         case BPF_SUB:
12162                 if (dst_reg == off_reg) {
12163                         /* scalar -= pointer.  Creates an unknown scalar */
12164                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12165                                 dst);
12166                         return -EACCES;
12167                 }
12168                 /* We don't allow subtraction from FP, because (according to
12169                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12170                  * be able to deal with it.
12171                  */
12172                 if (ptr_reg->type == PTR_TO_STACK) {
12173                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12174                                 dst);
12175                         return -EACCES;
12176                 }
12177                 if (known && (ptr_reg->off - smin_val ==
12178                               (s64)(s32)(ptr_reg->off - smin_val))) {
12179                         /* pointer -= K.  Subtract it from fixed offset */
12180                         dst_reg->smin_value = smin_ptr;
12181                         dst_reg->smax_value = smax_ptr;
12182                         dst_reg->umin_value = umin_ptr;
12183                         dst_reg->umax_value = umax_ptr;
12184                         dst_reg->var_off = ptr_reg->var_off;
12185                         dst_reg->id = ptr_reg->id;
12186                         dst_reg->off = ptr_reg->off - smin_val;
12187                         dst_reg->raw = ptr_reg->raw;
12188                         break;
12189                 }
12190                 /* A new variable offset is created.  If the subtrahend is known
12191                  * nonnegative, then any reg->range we had before is still good.
12192                  */
12193                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12194                     signed_sub_overflows(smax_ptr, smin_val)) {
12195                         /* Overflow possible, we know nothing */
12196                         dst_reg->smin_value = S64_MIN;
12197                         dst_reg->smax_value = S64_MAX;
12198                 } else {
12199                         dst_reg->smin_value = smin_ptr - smax_val;
12200                         dst_reg->smax_value = smax_ptr - smin_val;
12201                 }
12202                 if (umin_ptr < umax_val) {
12203                         /* Overflow possible, we know nothing */
12204                         dst_reg->umin_value = 0;
12205                         dst_reg->umax_value = U64_MAX;
12206                 } else {
12207                         /* Cannot overflow (as long as bounds are consistent) */
12208                         dst_reg->umin_value = umin_ptr - umax_val;
12209                         dst_reg->umax_value = umax_ptr - umin_val;
12210                 }
12211                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12212                 dst_reg->off = ptr_reg->off;
12213                 dst_reg->raw = ptr_reg->raw;
12214                 if (reg_is_pkt_pointer(ptr_reg)) {
12215                         dst_reg->id = ++env->id_gen;
12216                         /* something was added to pkt_ptr, set range to zero */
12217                         if (smin_val < 0)
12218                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12219                 }
12220                 break;
12221         case BPF_AND:
12222         case BPF_OR:
12223         case BPF_XOR:
12224                 /* bitwise ops on pointers are troublesome, prohibit. */
12225                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12226                         dst, bpf_alu_string[opcode >> 4]);
12227                 return -EACCES;
12228         default:
12229                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12230                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12231                         dst, bpf_alu_string[opcode >> 4]);
12232                 return -EACCES;
12233         }
12234
12235         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12236                 return -EINVAL;
12237         reg_bounds_sync(dst_reg);
12238         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12239                 return -EACCES;
12240         if (sanitize_needed(opcode)) {
12241                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12242                                        &info, true);
12243                 if (ret < 0)
12244                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12245         }
12246
12247         return 0;
12248 }
12249
12250 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12251                                  struct bpf_reg_state *src_reg)
12252 {
12253         s32 smin_val = src_reg->s32_min_value;
12254         s32 smax_val = src_reg->s32_max_value;
12255         u32 umin_val = src_reg->u32_min_value;
12256         u32 umax_val = src_reg->u32_max_value;
12257
12258         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12259             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12260                 dst_reg->s32_min_value = S32_MIN;
12261                 dst_reg->s32_max_value = S32_MAX;
12262         } else {
12263                 dst_reg->s32_min_value += smin_val;
12264                 dst_reg->s32_max_value += smax_val;
12265         }
12266         if (dst_reg->u32_min_value + umin_val < umin_val ||
12267             dst_reg->u32_max_value + umax_val < umax_val) {
12268                 dst_reg->u32_min_value = 0;
12269                 dst_reg->u32_max_value = U32_MAX;
12270         } else {
12271                 dst_reg->u32_min_value += umin_val;
12272                 dst_reg->u32_max_value += umax_val;
12273         }
12274 }
12275
12276 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12277                                struct bpf_reg_state *src_reg)
12278 {
12279         s64 smin_val = src_reg->smin_value;
12280         s64 smax_val = src_reg->smax_value;
12281         u64 umin_val = src_reg->umin_value;
12282         u64 umax_val = src_reg->umax_value;
12283
12284         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12285             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12286                 dst_reg->smin_value = S64_MIN;
12287                 dst_reg->smax_value = S64_MAX;
12288         } else {
12289                 dst_reg->smin_value += smin_val;
12290                 dst_reg->smax_value += smax_val;
12291         }
12292         if (dst_reg->umin_value + umin_val < umin_val ||
12293             dst_reg->umax_value + umax_val < umax_val) {
12294                 dst_reg->umin_value = 0;
12295                 dst_reg->umax_value = U64_MAX;
12296         } else {
12297                 dst_reg->umin_value += umin_val;
12298                 dst_reg->umax_value += umax_val;
12299         }
12300 }
12301
12302 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12303                                  struct bpf_reg_state *src_reg)
12304 {
12305         s32 smin_val = src_reg->s32_min_value;
12306         s32 smax_val = src_reg->s32_max_value;
12307         u32 umin_val = src_reg->u32_min_value;
12308         u32 umax_val = src_reg->u32_max_value;
12309
12310         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12311             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12312                 /* Overflow possible, we know nothing */
12313                 dst_reg->s32_min_value = S32_MIN;
12314                 dst_reg->s32_max_value = S32_MAX;
12315         } else {
12316                 dst_reg->s32_min_value -= smax_val;
12317                 dst_reg->s32_max_value -= smin_val;
12318         }
12319         if (dst_reg->u32_min_value < umax_val) {
12320                 /* Overflow possible, we know nothing */
12321                 dst_reg->u32_min_value = 0;
12322                 dst_reg->u32_max_value = U32_MAX;
12323         } else {
12324                 /* Cannot overflow (as long as bounds are consistent) */
12325                 dst_reg->u32_min_value -= umax_val;
12326                 dst_reg->u32_max_value -= umin_val;
12327         }
12328 }
12329
12330 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12331                                struct bpf_reg_state *src_reg)
12332 {
12333         s64 smin_val = src_reg->smin_value;
12334         s64 smax_val = src_reg->smax_value;
12335         u64 umin_val = src_reg->umin_value;
12336         u64 umax_val = src_reg->umax_value;
12337
12338         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12339             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12340                 /* Overflow possible, we know nothing */
12341                 dst_reg->smin_value = S64_MIN;
12342                 dst_reg->smax_value = S64_MAX;
12343         } else {
12344                 dst_reg->smin_value -= smax_val;
12345                 dst_reg->smax_value -= smin_val;
12346         }
12347         if (dst_reg->umin_value < umax_val) {
12348                 /* Overflow possible, we know nothing */
12349                 dst_reg->umin_value = 0;
12350                 dst_reg->umax_value = U64_MAX;
12351         } else {
12352                 /* Cannot overflow (as long as bounds are consistent) */
12353                 dst_reg->umin_value -= umax_val;
12354                 dst_reg->umax_value -= umin_val;
12355         }
12356 }
12357
12358 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12359                                  struct bpf_reg_state *src_reg)
12360 {
12361         s32 smin_val = src_reg->s32_min_value;
12362         u32 umin_val = src_reg->u32_min_value;
12363         u32 umax_val = src_reg->u32_max_value;
12364
12365         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12366                 /* Ain't nobody got time to multiply that sign */
12367                 __mark_reg32_unbounded(dst_reg);
12368                 return;
12369         }
12370         /* Both values are positive, so we can work with unsigned and
12371          * copy the result to signed (unless it exceeds S32_MAX).
12372          */
12373         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12374                 /* Potential overflow, we know nothing */
12375                 __mark_reg32_unbounded(dst_reg);
12376                 return;
12377         }
12378         dst_reg->u32_min_value *= umin_val;
12379         dst_reg->u32_max_value *= umax_val;
12380         if (dst_reg->u32_max_value > S32_MAX) {
12381                 /* Overflow possible, we know nothing */
12382                 dst_reg->s32_min_value = S32_MIN;
12383                 dst_reg->s32_max_value = S32_MAX;
12384         } else {
12385                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12386                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12387         }
12388 }
12389
12390 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12391                                struct bpf_reg_state *src_reg)
12392 {
12393         s64 smin_val = src_reg->smin_value;
12394         u64 umin_val = src_reg->umin_value;
12395         u64 umax_val = src_reg->umax_value;
12396
12397         if (smin_val < 0 || dst_reg->smin_value < 0) {
12398                 /* Ain't nobody got time to multiply that sign */
12399                 __mark_reg64_unbounded(dst_reg);
12400                 return;
12401         }
12402         /* Both values are positive, so we can work with unsigned and
12403          * copy the result to signed (unless it exceeds S64_MAX).
12404          */
12405         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12406                 /* Potential overflow, we know nothing */
12407                 __mark_reg64_unbounded(dst_reg);
12408                 return;
12409         }
12410         dst_reg->umin_value *= umin_val;
12411         dst_reg->umax_value *= umax_val;
12412         if (dst_reg->umax_value > S64_MAX) {
12413                 /* Overflow possible, we know nothing */
12414                 dst_reg->smin_value = S64_MIN;
12415                 dst_reg->smax_value = S64_MAX;
12416         } else {
12417                 dst_reg->smin_value = dst_reg->umin_value;
12418                 dst_reg->smax_value = dst_reg->umax_value;
12419         }
12420 }
12421
12422 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12423                                  struct bpf_reg_state *src_reg)
12424 {
12425         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12426         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12427         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12428         s32 smin_val = src_reg->s32_min_value;
12429         u32 umax_val = src_reg->u32_max_value;
12430
12431         if (src_known && dst_known) {
12432                 __mark_reg32_known(dst_reg, var32_off.value);
12433                 return;
12434         }
12435
12436         /* We get our minimum from the var_off, since that's inherently
12437          * bitwise.  Our maximum is the minimum of the operands' maxima.
12438          */
12439         dst_reg->u32_min_value = var32_off.value;
12440         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12441         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12442                 /* Lose signed bounds when ANDing negative numbers,
12443                  * ain't nobody got time for that.
12444                  */
12445                 dst_reg->s32_min_value = S32_MIN;
12446                 dst_reg->s32_max_value = S32_MAX;
12447         } else {
12448                 /* ANDing two positives gives a positive, so safe to
12449                  * cast result into s64.
12450                  */
12451                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12452                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12453         }
12454 }
12455
12456 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12457                                struct bpf_reg_state *src_reg)
12458 {
12459         bool src_known = tnum_is_const(src_reg->var_off);
12460         bool dst_known = tnum_is_const(dst_reg->var_off);
12461         s64 smin_val = src_reg->smin_value;
12462         u64 umax_val = src_reg->umax_value;
12463
12464         if (src_known && dst_known) {
12465                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12466                 return;
12467         }
12468
12469         /* We get our minimum from the var_off, since that's inherently
12470          * bitwise.  Our maximum is the minimum of the operands' maxima.
12471          */
12472         dst_reg->umin_value = dst_reg->var_off.value;
12473         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12474         if (dst_reg->smin_value < 0 || smin_val < 0) {
12475                 /* Lose signed bounds when ANDing negative numbers,
12476                  * ain't nobody got time for that.
12477                  */
12478                 dst_reg->smin_value = S64_MIN;
12479                 dst_reg->smax_value = S64_MAX;
12480         } else {
12481                 /* ANDing two positives gives a positive, so safe to
12482                  * cast result into s64.
12483                  */
12484                 dst_reg->smin_value = dst_reg->umin_value;
12485                 dst_reg->smax_value = dst_reg->umax_value;
12486         }
12487         /* We may learn something more from the var_off */
12488         __update_reg_bounds(dst_reg);
12489 }
12490
12491 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12492                                 struct bpf_reg_state *src_reg)
12493 {
12494         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12495         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12496         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12497         s32 smin_val = src_reg->s32_min_value;
12498         u32 umin_val = src_reg->u32_min_value;
12499
12500         if (src_known && dst_known) {
12501                 __mark_reg32_known(dst_reg, var32_off.value);
12502                 return;
12503         }
12504
12505         /* We get our maximum from the var_off, and our minimum is the
12506          * maximum of the operands' minima
12507          */
12508         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12509         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12510         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12511                 /* Lose signed bounds when ORing negative numbers,
12512                  * ain't nobody got time for that.
12513                  */
12514                 dst_reg->s32_min_value = S32_MIN;
12515                 dst_reg->s32_max_value = S32_MAX;
12516         } else {
12517                 /* ORing two positives gives a positive, so safe to
12518                  * cast result into s64.
12519                  */
12520                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12521                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12522         }
12523 }
12524
12525 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12526                               struct bpf_reg_state *src_reg)
12527 {
12528         bool src_known = tnum_is_const(src_reg->var_off);
12529         bool dst_known = tnum_is_const(dst_reg->var_off);
12530         s64 smin_val = src_reg->smin_value;
12531         u64 umin_val = src_reg->umin_value;
12532
12533         if (src_known && dst_known) {
12534                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12535                 return;
12536         }
12537
12538         /* We get our maximum from the var_off, and our minimum is the
12539          * maximum of the operands' minima
12540          */
12541         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12542         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12543         if (dst_reg->smin_value < 0 || smin_val < 0) {
12544                 /* Lose signed bounds when ORing negative numbers,
12545                  * ain't nobody got time for that.
12546                  */
12547                 dst_reg->smin_value = S64_MIN;
12548                 dst_reg->smax_value = S64_MAX;
12549         } else {
12550                 /* ORing two positives gives a positive, so safe to
12551                  * cast result into s64.
12552                  */
12553                 dst_reg->smin_value = dst_reg->umin_value;
12554                 dst_reg->smax_value = dst_reg->umax_value;
12555         }
12556         /* We may learn something more from the var_off */
12557         __update_reg_bounds(dst_reg);
12558 }
12559
12560 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12561                                  struct bpf_reg_state *src_reg)
12562 {
12563         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12564         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12565         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12566         s32 smin_val = src_reg->s32_min_value;
12567
12568         if (src_known && dst_known) {
12569                 __mark_reg32_known(dst_reg, var32_off.value);
12570                 return;
12571         }
12572
12573         /* We get both minimum and maximum from the var32_off. */
12574         dst_reg->u32_min_value = var32_off.value;
12575         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12576
12577         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12578                 /* XORing two positive sign numbers gives a positive,
12579                  * so safe to cast u32 result into s32.
12580                  */
12581                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12582                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12583         } else {
12584                 dst_reg->s32_min_value = S32_MIN;
12585                 dst_reg->s32_max_value = S32_MAX;
12586         }
12587 }
12588
12589 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12590                                struct bpf_reg_state *src_reg)
12591 {
12592         bool src_known = tnum_is_const(src_reg->var_off);
12593         bool dst_known = tnum_is_const(dst_reg->var_off);
12594         s64 smin_val = src_reg->smin_value;
12595
12596         if (src_known && dst_known) {
12597                 /* dst_reg->var_off.value has been updated earlier */
12598                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12599                 return;
12600         }
12601
12602         /* We get both minimum and maximum from the var_off. */
12603         dst_reg->umin_value = dst_reg->var_off.value;
12604         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12605
12606         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12607                 /* XORing two positive sign numbers gives a positive,
12608                  * so safe to cast u64 result into s64.
12609                  */
12610                 dst_reg->smin_value = dst_reg->umin_value;
12611                 dst_reg->smax_value = dst_reg->umax_value;
12612         } else {
12613                 dst_reg->smin_value = S64_MIN;
12614                 dst_reg->smax_value = S64_MAX;
12615         }
12616
12617         __update_reg_bounds(dst_reg);
12618 }
12619
12620 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12621                                    u64 umin_val, u64 umax_val)
12622 {
12623         /* We lose all sign bit information (except what we can pick
12624          * up from var_off)
12625          */
12626         dst_reg->s32_min_value = S32_MIN;
12627         dst_reg->s32_max_value = S32_MAX;
12628         /* If we might shift our top bit out, then we know nothing */
12629         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12630                 dst_reg->u32_min_value = 0;
12631                 dst_reg->u32_max_value = U32_MAX;
12632         } else {
12633                 dst_reg->u32_min_value <<= umin_val;
12634                 dst_reg->u32_max_value <<= umax_val;
12635         }
12636 }
12637
12638 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12639                                  struct bpf_reg_state *src_reg)
12640 {
12641         u32 umax_val = src_reg->u32_max_value;
12642         u32 umin_val = src_reg->u32_min_value;
12643         /* u32 alu operation will zext upper bits */
12644         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12645
12646         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12647         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12648         /* Not required but being careful mark reg64 bounds as unknown so
12649          * that we are forced to pick them up from tnum and zext later and
12650          * if some path skips this step we are still safe.
12651          */
12652         __mark_reg64_unbounded(dst_reg);
12653         __update_reg32_bounds(dst_reg);
12654 }
12655
12656 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12657                                    u64 umin_val, u64 umax_val)
12658 {
12659         /* Special case <<32 because it is a common compiler pattern to sign
12660          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12661          * positive we know this shift will also be positive so we can track
12662          * bounds correctly. Otherwise we lose all sign bit information except
12663          * what we can pick up from var_off. Perhaps we can generalize this
12664          * later to shifts of any length.
12665          */
12666         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12667                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12668         else
12669                 dst_reg->smax_value = S64_MAX;
12670
12671         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12672                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12673         else
12674                 dst_reg->smin_value = S64_MIN;
12675
12676         /* If we might shift our top bit out, then we know nothing */
12677         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12678                 dst_reg->umin_value = 0;
12679                 dst_reg->umax_value = U64_MAX;
12680         } else {
12681                 dst_reg->umin_value <<= umin_val;
12682                 dst_reg->umax_value <<= umax_val;
12683         }
12684 }
12685
12686 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12687                                struct bpf_reg_state *src_reg)
12688 {
12689         u64 umax_val = src_reg->umax_value;
12690         u64 umin_val = src_reg->umin_value;
12691
12692         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12693         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12694         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12695
12696         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12697         /* We may learn something more from the var_off */
12698         __update_reg_bounds(dst_reg);
12699 }
12700
12701 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12702                                  struct bpf_reg_state *src_reg)
12703 {
12704         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12705         u32 umax_val = src_reg->u32_max_value;
12706         u32 umin_val = src_reg->u32_min_value;
12707
12708         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12709          * be negative, then either:
12710          * 1) src_reg might be zero, so the sign bit of the result is
12711          *    unknown, so we lose our signed bounds
12712          * 2) it's known negative, thus the unsigned bounds capture the
12713          *    signed bounds
12714          * 3) the signed bounds cross zero, so they tell us nothing
12715          *    about the result
12716          * If the value in dst_reg is known nonnegative, then again the
12717          * unsigned bounds capture the signed bounds.
12718          * Thus, in all cases it suffices to blow away our signed bounds
12719          * and rely on inferring new ones from the unsigned bounds and
12720          * var_off of the result.
12721          */
12722         dst_reg->s32_min_value = S32_MIN;
12723         dst_reg->s32_max_value = S32_MAX;
12724
12725         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12726         dst_reg->u32_min_value >>= umax_val;
12727         dst_reg->u32_max_value >>= umin_val;
12728
12729         __mark_reg64_unbounded(dst_reg);
12730         __update_reg32_bounds(dst_reg);
12731 }
12732
12733 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12734                                struct bpf_reg_state *src_reg)
12735 {
12736         u64 umax_val = src_reg->umax_value;
12737         u64 umin_val = src_reg->umin_value;
12738
12739         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12740          * be negative, then either:
12741          * 1) src_reg might be zero, so the sign bit of the result is
12742          *    unknown, so we lose our signed bounds
12743          * 2) it's known negative, thus the unsigned bounds capture the
12744          *    signed bounds
12745          * 3) the signed bounds cross zero, so they tell us nothing
12746          *    about the result
12747          * If the value in dst_reg is known nonnegative, then again the
12748          * unsigned bounds capture the signed bounds.
12749          * Thus, in all cases it suffices to blow away our signed bounds
12750          * and rely on inferring new ones from the unsigned bounds and
12751          * var_off of the result.
12752          */
12753         dst_reg->smin_value = S64_MIN;
12754         dst_reg->smax_value = S64_MAX;
12755         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12756         dst_reg->umin_value >>= umax_val;
12757         dst_reg->umax_value >>= umin_val;
12758
12759         /* Its not easy to operate on alu32 bounds here because it depends
12760          * on bits being shifted in. Take easy way out and mark unbounded
12761          * so we can recalculate later from tnum.
12762          */
12763         __mark_reg32_unbounded(dst_reg);
12764         __update_reg_bounds(dst_reg);
12765 }
12766
12767 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12768                                   struct bpf_reg_state *src_reg)
12769 {
12770         u64 umin_val = src_reg->u32_min_value;
12771
12772         /* Upon reaching here, src_known is true and
12773          * umax_val is equal to umin_val.
12774          */
12775         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12776         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12777
12778         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12779
12780         /* blow away the dst_reg umin_value/umax_value and rely on
12781          * dst_reg var_off to refine the result.
12782          */
12783         dst_reg->u32_min_value = 0;
12784         dst_reg->u32_max_value = U32_MAX;
12785
12786         __mark_reg64_unbounded(dst_reg);
12787         __update_reg32_bounds(dst_reg);
12788 }
12789
12790 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12791                                 struct bpf_reg_state *src_reg)
12792 {
12793         u64 umin_val = src_reg->umin_value;
12794
12795         /* Upon reaching here, src_known is true and umax_val is equal
12796          * to umin_val.
12797          */
12798         dst_reg->smin_value >>= umin_val;
12799         dst_reg->smax_value >>= umin_val;
12800
12801         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12802
12803         /* blow away the dst_reg umin_value/umax_value and rely on
12804          * dst_reg var_off to refine the result.
12805          */
12806         dst_reg->umin_value = 0;
12807         dst_reg->umax_value = U64_MAX;
12808
12809         /* Its not easy to operate on alu32 bounds here because it depends
12810          * on bits being shifted in from upper 32-bits. Take easy way out
12811          * and mark unbounded so we can recalculate later from tnum.
12812          */
12813         __mark_reg32_unbounded(dst_reg);
12814         __update_reg_bounds(dst_reg);
12815 }
12816
12817 /* WARNING: This function does calculations on 64-bit values, but the actual
12818  * execution may occur on 32-bit values. Therefore, things like bitshifts
12819  * need extra checks in the 32-bit case.
12820  */
12821 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12822                                       struct bpf_insn *insn,
12823                                       struct bpf_reg_state *dst_reg,
12824                                       struct bpf_reg_state src_reg)
12825 {
12826         struct bpf_reg_state *regs = cur_regs(env);
12827         u8 opcode = BPF_OP(insn->code);
12828         bool src_known;
12829         s64 smin_val, smax_val;
12830         u64 umin_val, umax_val;
12831         s32 s32_min_val, s32_max_val;
12832         u32 u32_min_val, u32_max_val;
12833         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12834         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12835         int ret;
12836
12837         smin_val = src_reg.smin_value;
12838         smax_val = src_reg.smax_value;
12839         umin_val = src_reg.umin_value;
12840         umax_val = src_reg.umax_value;
12841
12842         s32_min_val = src_reg.s32_min_value;
12843         s32_max_val = src_reg.s32_max_value;
12844         u32_min_val = src_reg.u32_min_value;
12845         u32_max_val = src_reg.u32_max_value;
12846
12847         if (alu32) {
12848                 src_known = tnum_subreg_is_const(src_reg.var_off);
12849                 if ((src_known &&
12850                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12851                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12852                         /* Taint dst register if offset had invalid bounds
12853                          * derived from e.g. dead branches.
12854                          */
12855                         __mark_reg_unknown(env, dst_reg);
12856                         return 0;
12857                 }
12858         } else {
12859                 src_known = tnum_is_const(src_reg.var_off);
12860                 if ((src_known &&
12861                      (smin_val != smax_val || umin_val != umax_val)) ||
12862                     smin_val > smax_val || umin_val > umax_val) {
12863                         /* Taint dst register if offset had invalid bounds
12864                          * derived from e.g. dead branches.
12865                          */
12866                         __mark_reg_unknown(env, dst_reg);
12867                         return 0;
12868                 }
12869         }
12870
12871         if (!src_known &&
12872             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12873                 __mark_reg_unknown(env, dst_reg);
12874                 return 0;
12875         }
12876
12877         if (sanitize_needed(opcode)) {
12878                 ret = sanitize_val_alu(env, insn);
12879                 if (ret < 0)
12880                         return sanitize_err(env, insn, ret, NULL, NULL);
12881         }
12882
12883         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12884          * There are two classes of instructions: The first class we track both
12885          * alu32 and alu64 sign/unsigned bounds independently this provides the
12886          * greatest amount of precision when alu operations are mixed with jmp32
12887          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12888          * and BPF_OR. This is possible because these ops have fairly easy to
12889          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12890          * See alu32 verifier tests for examples. The second class of
12891          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12892          * with regards to tracking sign/unsigned bounds because the bits may
12893          * cross subreg boundaries in the alu64 case. When this happens we mark
12894          * the reg unbounded in the subreg bound space and use the resulting
12895          * tnum to calculate an approximation of the sign/unsigned bounds.
12896          */
12897         switch (opcode) {
12898         case BPF_ADD:
12899                 scalar32_min_max_add(dst_reg, &src_reg);
12900                 scalar_min_max_add(dst_reg, &src_reg);
12901                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12902                 break;
12903         case BPF_SUB:
12904                 scalar32_min_max_sub(dst_reg, &src_reg);
12905                 scalar_min_max_sub(dst_reg, &src_reg);
12906                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12907                 break;
12908         case BPF_MUL:
12909                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12910                 scalar32_min_max_mul(dst_reg, &src_reg);
12911                 scalar_min_max_mul(dst_reg, &src_reg);
12912                 break;
12913         case BPF_AND:
12914                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12915                 scalar32_min_max_and(dst_reg, &src_reg);
12916                 scalar_min_max_and(dst_reg, &src_reg);
12917                 break;
12918         case BPF_OR:
12919                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12920                 scalar32_min_max_or(dst_reg, &src_reg);
12921                 scalar_min_max_or(dst_reg, &src_reg);
12922                 break;
12923         case BPF_XOR:
12924                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12925                 scalar32_min_max_xor(dst_reg, &src_reg);
12926                 scalar_min_max_xor(dst_reg, &src_reg);
12927                 break;
12928         case BPF_LSH:
12929                 if (umax_val >= insn_bitness) {
12930                         /* Shifts greater than 31 or 63 are undefined.
12931                          * This includes shifts by a negative number.
12932                          */
12933                         mark_reg_unknown(env, regs, insn->dst_reg);
12934                         break;
12935                 }
12936                 if (alu32)
12937                         scalar32_min_max_lsh(dst_reg, &src_reg);
12938                 else
12939                         scalar_min_max_lsh(dst_reg, &src_reg);
12940                 break;
12941         case BPF_RSH:
12942                 if (umax_val >= insn_bitness) {
12943                         /* Shifts greater than 31 or 63 are undefined.
12944                          * This includes shifts by a negative number.
12945                          */
12946                         mark_reg_unknown(env, regs, insn->dst_reg);
12947                         break;
12948                 }
12949                 if (alu32)
12950                         scalar32_min_max_rsh(dst_reg, &src_reg);
12951                 else
12952                         scalar_min_max_rsh(dst_reg, &src_reg);
12953                 break;
12954         case BPF_ARSH:
12955                 if (umax_val >= insn_bitness) {
12956                         /* Shifts greater than 31 or 63 are undefined.
12957                          * This includes shifts by a negative number.
12958                          */
12959                         mark_reg_unknown(env, regs, insn->dst_reg);
12960                         break;
12961                 }
12962                 if (alu32)
12963                         scalar32_min_max_arsh(dst_reg, &src_reg);
12964                 else
12965                         scalar_min_max_arsh(dst_reg, &src_reg);
12966                 break;
12967         default:
12968                 mark_reg_unknown(env, regs, insn->dst_reg);
12969                 break;
12970         }
12971
12972         /* ALU32 ops are zero extended into 64bit register */
12973         if (alu32)
12974                 zext_32_to_64(dst_reg);
12975         reg_bounds_sync(dst_reg);
12976         return 0;
12977 }
12978
12979 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12980  * and var_off.
12981  */
12982 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12983                                    struct bpf_insn *insn)
12984 {
12985         struct bpf_verifier_state *vstate = env->cur_state;
12986         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12987         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12988         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12989         u8 opcode = BPF_OP(insn->code);
12990         int err;
12991
12992         dst_reg = &regs[insn->dst_reg];
12993         src_reg = NULL;
12994         if (dst_reg->type != SCALAR_VALUE)
12995                 ptr_reg = dst_reg;
12996         else
12997                 /* Make sure ID is cleared otherwise dst_reg min/max could be
12998                  * incorrectly propagated into other registers by find_equal_scalars()
12999                  */
13000                 dst_reg->id = 0;
13001         if (BPF_SRC(insn->code) == BPF_X) {
13002                 src_reg = &regs[insn->src_reg];
13003                 if (src_reg->type != SCALAR_VALUE) {
13004                         if (dst_reg->type != SCALAR_VALUE) {
13005                                 /* Combining two pointers by any ALU op yields
13006                                  * an arbitrary scalar. Disallow all math except
13007                                  * pointer subtraction
13008                                  */
13009                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13010                                         mark_reg_unknown(env, regs, insn->dst_reg);
13011                                         return 0;
13012                                 }
13013                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13014                                         insn->dst_reg,
13015                                         bpf_alu_string[opcode >> 4]);
13016                                 return -EACCES;
13017                         } else {
13018                                 /* scalar += pointer
13019                                  * This is legal, but we have to reverse our
13020                                  * src/dest handling in computing the range
13021                                  */
13022                                 err = mark_chain_precision(env, insn->dst_reg);
13023                                 if (err)
13024                                         return err;
13025                                 return adjust_ptr_min_max_vals(env, insn,
13026                                                                src_reg, dst_reg);
13027                         }
13028                 } else if (ptr_reg) {
13029                         /* pointer += scalar */
13030                         err = mark_chain_precision(env, insn->src_reg);
13031                         if (err)
13032                                 return err;
13033                         return adjust_ptr_min_max_vals(env, insn,
13034                                                        dst_reg, src_reg);
13035                 } else if (dst_reg->precise) {
13036                         /* if dst_reg is precise, src_reg should be precise as well */
13037                         err = mark_chain_precision(env, insn->src_reg);
13038                         if (err)
13039                                 return err;
13040                 }
13041         } else {
13042                 /* Pretend the src is a reg with a known value, since we only
13043                  * need to be able to read from this state.
13044                  */
13045                 off_reg.type = SCALAR_VALUE;
13046                 __mark_reg_known(&off_reg, insn->imm);
13047                 src_reg = &off_reg;
13048                 if (ptr_reg) /* pointer += K */
13049                         return adjust_ptr_min_max_vals(env, insn,
13050                                                        ptr_reg, src_reg);
13051         }
13052
13053         /* Got here implies adding two SCALAR_VALUEs */
13054         if (WARN_ON_ONCE(ptr_reg)) {
13055                 print_verifier_state(env, state, true);
13056                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13057                 return -EINVAL;
13058         }
13059         if (WARN_ON(!src_reg)) {
13060                 print_verifier_state(env, state, true);
13061                 verbose(env, "verifier internal error: no src_reg\n");
13062                 return -EINVAL;
13063         }
13064         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13065 }
13066
13067 /* check validity of 32-bit and 64-bit arithmetic operations */
13068 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13069 {
13070         struct bpf_reg_state *regs = cur_regs(env);
13071         u8 opcode = BPF_OP(insn->code);
13072         int err;
13073
13074         if (opcode == BPF_END || opcode == BPF_NEG) {
13075                 if (opcode == BPF_NEG) {
13076                         if (BPF_SRC(insn->code) != BPF_K ||
13077                             insn->src_reg != BPF_REG_0 ||
13078                             insn->off != 0 || insn->imm != 0) {
13079                                 verbose(env, "BPF_NEG uses reserved fields\n");
13080                                 return -EINVAL;
13081                         }
13082                 } else {
13083                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13084                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13085                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13086                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13087                                 verbose(env, "BPF_END uses reserved fields\n");
13088                                 return -EINVAL;
13089                         }
13090                 }
13091
13092                 /* check src operand */
13093                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13094                 if (err)
13095                         return err;
13096
13097                 if (is_pointer_value(env, insn->dst_reg)) {
13098                         verbose(env, "R%d pointer arithmetic prohibited\n",
13099                                 insn->dst_reg);
13100                         return -EACCES;
13101                 }
13102
13103                 /* check dest operand */
13104                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13105                 if (err)
13106                         return err;
13107
13108         } else if (opcode == BPF_MOV) {
13109
13110                 if (BPF_SRC(insn->code) == BPF_X) {
13111                         if (insn->imm != 0) {
13112                                 verbose(env, "BPF_MOV uses reserved fields\n");
13113                                 return -EINVAL;
13114                         }
13115
13116                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13117                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13118                                         verbose(env, "BPF_MOV uses reserved fields\n");
13119                                         return -EINVAL;
13120                                 }
13121                         } else {
13122                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13123                                     insn->off != 32) {
13124                                         verbose(env, "BPF_MOV uses reserved fields\n");
13125                                         return -EINVAL;
13126                                 }
13127                         }
13128
13129                         /* check src operand */
13130                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13131                         if (err)
13132                                 return err;
13133                 } else {
13134                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13135                                 verbose(env, "BPF_MOV uses reserved fields\n");
13136                                 return -EINVAL;
13137                         }
13138                 }
13139
13140                 /* check dest operand, mark as required later */
13141                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13142                 if (err)
13143                         return err;
13144
13145                 if (BPF_SRC(insn->code) == BPF_X) {
13146                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13147                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13148                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13149                                        !tnum_is_const(src_reg->var_off);
13150
13151                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13152                                 if (insn->off == 0) {
13153                                         /* case: R1 = R2
13154                                          * copy register state to dest reg
13155                                          */
13156                                         if (need_id)
13157                                                 /* Assign src and dst registers the same ID
13158                                                  * that will be used by find_equal_scalars()
13159                                                  * to propagate min/max range.
13160                                                  */
13161                                                 src_reg->id = ++env->id_gen;
13162                                         copy_register_state(dst_reg, src_reg);
13163                                         dst_reg->live |= REG_LIVE_WRITTEN;
13164                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13165                                 } else {
13166                                         /* case: R1 = (s8, s16 s32)R2 */
13167                                         bool no_sext;
13168
13169                                         no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13170                                         if (no_sext && need_id)
13171                                                 src_reg->id = ++env->id_gen;
13172                                         copy_register_state(dst_reg, src_reg);
13173                                         if (!no_sext)
13174                                                 dst_reg->id = 0;
13175                                         coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13176                                         dst_reg->live |= REG_LIVE_WRITTEN;
13177                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13178                                 }
13179                         } else {
13180                                 /* R1 = (u32) R2 */
13181                                 if (is_pointer_value(env, insn->src_reg)) {
13182                                         verbose(env,
13183                                                 "R%d partial copy of pointer\n",
13184                                                 insn->src_reg);
13185                                         return -EACCES;
13186                                 } else if (src_reg->type == SCALAR_VALUE) {
13187                                         if (insn->off == 0) {
13188                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13189
13190                                                 if (is_src_reg_u32 && need_id)
13191                                                         src_reg->id = ++env->id_gen;
13192                                                 copy_register_state(dst_reg, src_reg);
13193                                                 /* Make sure ID is cleared if src_reg is not in u32
13194                                                  * range otherwise dst_reg min/max could be incorrectly
13195                                                  * propagated into src_reg by find_equal_scalars()
13196                                                  */
13197                                                 if (!is_src_reg_u32)
13198                                                         dst_reg->id = 0;
13199                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13200                                                 dst_reg->subreg_def = env->insn_idx + 1;
13201                                         } else {
13202                                                 /* case: W1 = (s8, s16)W2 */
13203                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13204
13205                                                 if (no_sext && need_id)
13206                                                         src_reg->id = ++env->id_gen;
13207                                                 copy_register_state(dst_reg, src_reg);
13208                                                 if (!no_sext)
13209                                                         dst_reg->id = 0;
13210                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13211                                                 dst_reg->subreg_def = env->insn_idx + 1;
13212                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13213                                         }
13214                                 } else {
13215                                         mark_reg_unknown(env, regs,
13216                                                          insn->dst_reg);
13217                                 }
13218                                 zext_32_to_64(dst_reg);
13219                                 reg_bounds_sync(dst_reg);
13220                         }
13221                 } else {
13222                         /* case: R = imm
13223                          * remember the value we stored into this reg
13224                          */
13225                         /* clear any state __mark_reg_known doesn't set */
13226                         mark_reg_unknown(env, regs, insn->dst_reg);
13227                         regs[insn->dst_reg].type = SCALAR_VALUE;
13228                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13229                                 __mark_reg_known(regs + insn->dst_reg,
13230                                                  insn->imm);
13231                         } else {
13232                                 __mark_reg_known(regs + insn->dst_reg,
13233                                                  (u32)insn->imm);
13234                         }
13235                 }
13236
13237         } else if (opcode > BPF_END) {
13238                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13239                 return -EINVAL;
13240
13241         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13242
13243                 if (BPF_SRC(insn->code) == BPF_X) {
13244                         if (insn->imm != 0 || insn->off > 1 ||
13245                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13246                                 verbose(env, "BPF_ALU uses reserved fields\n");
13247                                 return -EINVAL;
13248                         }
13249                         /* check src1 operand */
13250                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13251                         if (err)
13252                                 return err;
13253                 } else {
13254                         if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13255                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13256                                 verbose(env, "BPF_ALU uses reserved fields\n");
13257                                 return -EINVAL;
13258                         }
13259                 }
13260
13261                 /* check src2 operand */
13262                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13263                 if (err)
13264                         return err;
13265
13266                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13267                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13268                         verbose(env, "div by zero\n");
13269                         return -EINVAL;
13270                 }
13271
13272                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13273                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13274                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13275
13276                         if (insn->imm < 0 || insn->imm >= size) {
13277                                 verbose(env, "invalid shift %d\n", insn->imm);
13278                                 return -EINVAL;
13279                         }
13280                 }
13281
13282                 /* check dest operand */
13283                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13284                 if (err)
13285                         return err;
13286
13287                 return adjust_reg_min_max_vals(env, insn);
13288         }
13289
13290         return 0;
13291 }
13292
13293 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13294                                    struct bpf_reg_state *dst_reg,
13295                                    enum bpf_reg_type type,
13296                                    bool range_right_open)
13297 {
13298         struct bpf_func_state *state;
13299         struct bpf_reg_state *reg;
13300         int new_range;
13301
13302         if (dst_reg->off < 0 ||
13303             (dst_reg->off == 0 && range_right_open))
13304                 /* This doesn't give us any range */
13305                 return;
13306
13307         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13308             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13309                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13310                  * than pkt_end, but that's because it's also less than pkt.
13311                  */
13312                 return;
13313
13314         new_range = dst_reg->off;
13315         if (range_right_open)
13316                 new_range++;
13317
13318         /* Examples for register markings:
13319          *
13320          * pkt_data in dst register:
13321          *
13322          *   r2 = r3;
13323          *   r2 += 8;
13324          *   if (r2 > pkt_end) goto <handle exception>
13325          *   <access okay>
13326          *
13327          *   r2 = r3;
13328          *   r2 += 8;
13329          *   if (r2 < pkt_end) goto <access okay>
13330          *   <handle exception>
13331          *
13332          *   Where:
13333          *     r2 == dst_reg, pkt_end == src_reg
13334          *     r2=pkt(id=n,off=8,r=0)
13335          *     r3=pkt(id=n,off=0,r=0)
13336          *
13337          * pkt_data in src register:
13338          *
13339          *   r2 = r3;
13340          *   r2 += 8;
13341          *   if (pkt_end >= r2) goto <access okay>
13342          *   <handle exception>
13343          *
13344          *   r2 = r3;
13345          *   r2 += 8;
13346          *   if (pkt_end <= r2) goto <handle exception>
13347          *   <access okay>
13348          *
13349          *   Where:
13350          *     pkt_end == dst_reg, r2 == src_reg
13351          *     r2=pkt(id=n,off=8,r=0)
13352          *     r3=pkt(id=n,off=0,r=0)
13353          *
13354          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13355          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13356          * and [r3, r3 + 8-1) respectively is safe to access depending on
13357          * the check.
13358          */
13359
13360         /* If our ids match, then we must have the same max_value.  And we
13361          * don't care about the other reg's fixed offset, since if it's too big
13362          * the range won't allow anything.
13363          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13364          */
13365         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13366                 if (reg->type == type && reg->id == dst_reg->id)
13367                         /* keep the maximum range already checked */
13368                         reg->range = max(reg->range, new_range);
13369         }));
13370 }
13371
13372 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13373 {
13374         struct tnum subreg = tnum_subreg(reg->var_off);
13375         s32 sval = (s32)val;
13376
13377         switch (opcode) {
13378         case BPF_JEQ:
13379                 if (tnum_is_const(subreg))
13380                         return !!tnum_equals_const(subreg, val);
13381                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13382                         return 0;
13383                 break;
13384         case BPF_JNE:
13385                 if (tnum_is_const(subreg))
13386                         return !tnum_equals_const(subreg, val);
13387                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13388                         return 1;
13389                 break;
13390         case BPF_JSET:
13391                 if ((~subreg.mask & subreg.value) & val)
13392                         return 1;
13393                 if (!((subreg.mask | subreg.value) & val))
13394                         return 0;
13395                 break;
13396         case BPF_JGT:
13397                 if (reg->u32_min_value > val)
13398                         return 1;
13399                 else if (reg->u32_max_value <= val)
13400                         return 0;
13401                 break;
13402         case BPF_JSGT:
13403                 if (reg->s32_min_value > sval)
13404                         return 1;
13405                 else if (reg->s32_max_value <= sval)
13406                         return 0;
13407                 break;
13408         case BPF_JLT:
13409                 if (reg->u32_max_value < val)
13410                         return 1;
13411                 else if (reg->u32_min_value >= val)
13412                         return 0;
13413                 break;
13414         case BPF_JSLT:
13415                 if (reg->s32_max_value < sval)
13416                         return 1;
13417                 else if (reg->s32_min_value >= sval)
13418                         return 0;
13419                 break;
13420         case BPF_JGE:
13421                 if (reg->u32_min_value >= val)
13422                         return 1;
13423                 else if (reg->u32_max_value < val)
13424                         return 0;
13425                 break;
13426         case BPF_JSGE:
13427                 if (reg->s32_min_value >= sval)
13428                         return 1;
13429                 else if (reg->s32_max_value < sval)
13430                         return 0;
13431                 break;
13432         case BPF_JLE:
13433                 if (reg->u32_max_value <= val)
13434                         return 1;
13435                 else if (reg->u32_min_value > val)
13436                         return 0;
13437                 break;
13438         case BPF_JSLE:
13439                 if (reg->s32_max_value <= sval)
13440                         return 1;
13441                 else if (reg->s32_min_value > sval)
13442                         return 0;
13443                 break;
13444         }
13445
13446         return -1;
13447 }
13448
13449
13450 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13451 {
13452         s64 sval = (s64)val;
13453
13454         switch (opcode) {
13455         case BPF_JEQ:
13456                 if (tnum_is_const(reg->var_off))
13457                         return !!tnum_equals_const(reg->var_off, val);
13458                 else if (val < reg->umin_value || val > reg->umax_value)
13459                         return 0;
13460                 break;
13461         case BPF_JNE:
13462                 if (tnum_is_const(reg->var_off))
13463                         return !tnum_equals_const(reg->var_off, val);
13464                 else if (val < reg->umin_value || val > reg->umax_value)
13465                         return 1;
13466                 break;
13467         case BPF_JSET:
13468                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13469                         return 1;
13470                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13471                         return 0;
13472                 break;
13473         case BPF_JGT:
13474                 if (reg->umin_value > val)
13475                         return 1;
13476                 else if (reg->umax_value <= val)
13477                         return 0;
13478                 break;
13479         case BPF_JSGT:
13480                 if (reg->smin_value > sval)
13481                         return 1;
13482                 else if (reg->smax_value <= sval)
13483                         return 0;
13484                 break;
13485         case BPF_JLT:
13486                 if (reg->umax_value < val)
13487                         return 1;
13488                 else if (reg->umin_value >= val)
13489                         return 0;
13490                 break;
13491         case BPF_JSLT:
13492                 if (reg->smax_value < sval)
13493                         return 1;
13494                 else if (reg->smin_value >= sval)
13495                         return 0;
13496                 break;
13497         case BPF_JGE:
13498                 if (reg->umin_value >= val)
13499                         return 1;
13500                 else if (reg->umax_value < val)
13501                         return 0;
13502                 break;
13503         case BPF_JSGE:
13504                 if (reg->smin_value >= sval)
13505                         return 1;
13506                 else if (reg->smax_value < sval)
13507                         return 0;
13508                 break;
13509         case BPF_JLE:
13510                 if (reg->umax_value <= val)
13511                         return 1;
13512                 else if (reg->umin_value > val)
13513                         return 0;
13514                 break;
13515         case BPF_JSLE:
13516                 if (reg->smax_value <= sval)
13517                         return 1;
13518                 else if (reg->smin_value > sval)
13519                         return 0;
13520                 break;
13521         }
13522
13523         return -1;
13524 }
13525
13526 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13527  * and return:
13528  *  1 - branch will be taken and "goto target" will be executed
13529  *  0 - branch will not be taken and fall-through to next insn
13530  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13531  *      range [0,10]
13532  */
13533 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13534                            bool is_jmp32)
13535 {
13536         if (__is_pointer_value(false, reg)) {
13537                 if (!reg_not_null(reg))
13538                         return -1;
13539
13540                 /* If pointer is valid tests against zero will fail so we can
13541                  * use this to direct branch taken.
13542                  */
13543                 if (val != 0)
13544                         return -1;
13545
13546                 switch (opcode) {
13547                 case BPF_JEQ:
13548                         return 0;
13549                 case BPF_JNE:
13550                         return 1;
13551                 default:
13552                         return -1;
13553                 }
13554         }
13555
13556         if (is_jmp32)
13557                 return is_branch32_taken(reg, val, opcode);
13558         return is_branch64_taken(reg, val, opcode);
13559 }
13560
13561 static int flip_opcode(u32 opcode)
13562 {
13563         /* How can we transform "a <op> b" into "b <op> a"? */
13564         static const u8 opcode_flip[16] = {
13565                 /* these stay the same */
13566                 [BPF_JEQ  >> 4] = BPF_JEQ,
13567                 [BPF_JNE  >> 4] = BPF_JNE,
13568                 [BPF_JSET >> 4] = BPF_JSET,
13569                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13570                 [BPF_JGE  >> 4] = BPF_JLE,
13571                 [BPF_JGT  >> 4] = BPF_JLT,
13572                 [BPF_JLE  >> 4] = BPF_JGE,
13573                 [BPF_JLT  >> 4] = BPF_JGT,
13574                 [BPF_JSGE >> 4] = BPF_JSLE,
13575                 [BPF_JSGT >> 4] = BPF_JSLT,
13576                 [BPF_JSLE >> 4] = BPF_JSGE,
13577                 [BPF_JSLT >> 4] = BPF_JSGT
13578         };
13579         return opcode_flip[opcode >> 4];
13580 }
13581
13582 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13583                                    struct bpf_reg_state *src_reg,
13584                                    u8 opcode)
13585 {
13586         struct bpf_reg_state *pkt;
13587
13588         if (src_reg->type == PTR_TO_PACKET_END) {
13589                 pkt = dst_reg;
13590         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13591                 pkt = src_reg;
13592                 opcode = flip_opcode(opcode);
13593         } else {
13594                 return -1;
13595         }
13596
13597         if (pkt->range >= 0)
13598                 return -1;
13599
13600         switch (opcode) {
13601         case BPF_JLE:
13602                 /* pkt <= pkt_end */
13603                 fallthrough;
13604         case BPF_JGT:
13605                 /* pkt > pkt_end */
13606                 if (pkt->range == BEYOND_PKT_END)
13607                         /* pkt has at last one extra byte beyond pkt_end */
13608                         return opcode == BPF_JGT;
13609                 break;
13610         case BPF_JLT:
13611                 /* pkt < pkt_end */
13612                 fallthrough;
13613         case BPF_JGE:
13614                 /* pkt >= pkt_end */
13615                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13616                         return opcode == BPF_JGE;
13617                 break;
13618         }
13619         return -1;
13620 }
13621
13622 /* Adjusts the register min/max values in the case that the dst_reg is the
13623  * variable register that we are working on, and src_reg is a constant or we're
13624  * simply doing a BPF_K check.
13625  * In JEQ/JNE cases we also adjust the var_off values.
13626  */
13627 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13628                             struct bpf_reg_state *false_reg,
13629                             u64 val, u32 val32,
13630                             u8 opcode, bool is_jmp32)
13631 {
13632         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13633         struct tnum false_64off = false_reg->var_off;
13634         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13635         struct tnum true_64off = true_reg->var_off;
13636         s64 sval = (s64)val;
13637         s32 sval32 = (s32)val32;
13638
13639         /* If the dst_reg is a pointer, we can't learn anything about its
13640          * variable offset from the compare (unless src_reg were a pointer into
13641          * the same object, but we don't bother with that.
13642          * Since false_reg and true_reg have the same type by construction, we
13643          * only need to check one of them for pointerness.
13644          */
13645         if (__is_pointer_value(false, false_reg))
13646                 return;
13647
13648         switch (opcode) {
13649         /* JEQ/JNE comparison doesn't change the register equivalence.
13650          *
13651          * r1 = r2;
13652          * if (r1 == 42) goto label;
13653          * ...
13654          * label: // here both r1 and r2 are known to be 42.
13655          *
13656          * Hence when marking register as known preserve it's ID.
13657          */
13658         case BPF_JEQ:
13659                 if (is_jmp32) {
13660                         __mark_reg32_known(true_reg, val32);
13661                         true_32off = tnum_subreg(true_reg->var_off);
13662                 } else {
13663                         ___mark_reg_known(true_reg, val);
13664                         true_64off = true_reg->var_off;
13665                 }
13666                 break;
13667         case BPF_JNE:
13668                 if (is_jmp32) {
13669                         __mark_reg32_known(false_reg, val32);
13670                         false_32off = tnum_subreg(false_reg->var_off);
13671                 } else {
13672                         ___mark_reg_known(false_reg, val);
13673                         false_64off = false_reg->var_off;
13674                 }
13675                 break;
13676         case BPF_JSET:
13677                 if (is_jmp32) {
13678                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13679                         if (is_power_of_2(val32))
13680                                 true_32off = tnum_or(true_32off,
13681                                                      tnum_const(val32));
13682                 } else {
13683                         false_64off = tnum_and(false_64off, tnum_const(~val));
13684                         if (is_power_of_2(val))
13685                                 true_64off = tnum_or(true_64off,
13686                                                      tnum_const(val));
13687                 }
13688                 break;
13689         case BPF_JGE:
13690         case BPF_JGT:
13691         {
13692                 if (is_jmp32) {
13693                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13694                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13695
13696                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13697                                                        false_umax);
13698                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13699                                                       true_umin);
13700                 } else {
13701                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13702                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13703
13704                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13705                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13706                 }
13707                 break;
13708         }
13709         case BPF_JSGE:
13710         case BPF_JSGT:
13711         {
13712                 if (is_jmp32) {
13713                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13714                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13715
13716                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13717                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13718                 } else {
13719                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13720                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13721
13722                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13723                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13724                 }
13725                 break;
13726         }
13727         case BPF_JLE:
13728         case BPF_JLT:
13729         {
13730                 if (is_jmp32) {
13731                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13732                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13733
13734                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13735                                                        false_umin);
13736                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13737                                                       true_umax);
13738                 } else {
13739                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13740                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13741
13742                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13743                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13744                 }
13745                 break;
13746         }
13747         case BPF_JSLE:
13748         case BPF_JSLT:
13749         {
13750                 if (is_jmp32) {
13751                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13752                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13753
13754                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13755                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13756                 } else {
13757                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13758                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13759
13760                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13761                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13762                 }
13763                 break;
13764         }
13765         default:
13766                 return;
13767         }
13768
13769         if (is_jmp32) {
13770                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13771                                              tnum_subreg(false_32off));
13772                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13773                                             tnum_subreg(true_32off));
13774                 __reg_combine_32_into_64(false_reg);
13775                 __reg_combine_32_into_64(true_reg);
13776         } else {
13777                 false_reg->var_off = false_64off;
13778                 true_reg->var_off = true_64off;
13779                 __reg_combine_64_into_32(false_reg);
13780                 __reg_combine_64_into_32(true_reg);
13781         }
13782 }
13783
13784 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13785  * the variable reg.
13786  */
13787 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13788                                 struct bpf_reg_state *false_reg,
13789                                 u64 val, u32 val32,
13790                                 u8 opcode, bool is_jmp32)
13791 {
13792         opcode = flip_opcode(opcode);
13793         /* This uses zero as "not present in table"; luckily the zero opcode,
13794          * BPF_JA, can't get here.
13795          */
13796         if (opcode)
13797                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13798 }
13799
13800 /* Regs are known to be equal, so intersect their min/max/var_off */
13801 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13802                                   struct bpf_reg_state *dst_reg)
13803 {
13804         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13805                                                         dst_reg->umin_value);
13806         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13807                                                         dst_reg->umax_value);
13808         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13809                                                         dst_reg->smin_value);
13810         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13811                                                         dst_reg->smax_value);
13812         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13813                                                              dst_reg->var_off);
13814         reg_bounds_sync(src_reg);
13815         reg_bounds_sync(dst_reg);
13816 }
13817
13818 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13819                                 struct bpf_reg_state *true_dst,
13820                                 struct bpf_reg_state *false_src,
13821                                 struct bpf_reg_state *false_dst,
13822                                 u8 opcode)
13823 {
13824         switch (opcode) {
13825         case BPF_JEQ:
13826                 __reg_combine_min_max(true_src, true_dst);
13827                 break;
13828         case BPF_JNE:
13829                 __reg_combine_min_max(false_src, false_dst);
13830                 break;
13831         }
13832 }
13833
13834 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13835                                  struct bpf_reg_state *reg, u32 id,
13836                                  bool is_null)
13837 {
13838         if (type_may_be_null(reg->type) && reg->id == id &&
13839             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13840                 /* Old offset (both fixed and variable parts) should have been
13841                  * known-zero, because we don't allow pointer arithmetic on
13842                  * pointers that might be NULL. If we see this happening, don't
13843                  * convert the register.
13844                  *
13845                  * But in some cases, some helpers that return local kptrs
13846                  * advance offset for the returned pointer. In those cases, it
13847                  * is fine to expect to see reg->off.
13848                  */
13849                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13850                         return;
13851                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13852                     WARN_ON_ONCE(reg->off))
13853                         return;
13854
13855                 if (is_null) {
13856                         reg->type = SCALAR_VALUE;
13857                         /* We don't need id and ref_obj_id from this point
13858                          * onwards anymore, thus we should better reset it,
13859                          * so that state pruning has chances to take effect.
13860                          */
13861                         reg->id = 0;
13862                         reg->ref_obj_id = 0;
13863
13864                         return;
13865                 }
13866
13867                 mark_ptr_not_null_reg(reg);
13868
13869                 if (!reg_may_point_to_spin_lock(reg)) {
13870                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13871                          * in release_reference().
13872                          *
13873                          * reg->id is still used by spin_lock ptr. Other
13874                          * than spin_lock ptr type, reg->id can be reset.
13875                          */
13876                         reg->id = 0;
13877                 }
13878         }
13879 }
13880
13881 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13882  * be folded together at some point.
13883  */
13884 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13885                                   bool is_null)
13886 {
13887         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13888         struct bpf_reg_state *regs = state->regs, *reg;
13889         u32 ref_obj_id = regs[regno].ref_obj_id;
13890         u32 id = regs[regno].id;
13891
13892         if (ref_obj_id && ref_obj_id == id && is_null)
13893                 /* regs[regno] is in the " == NULL" branch.
13894                  * No one could have freed the reference state before
13895                  * doing the NULL check.
13896                  */
13897                 WARN_ON_ONCE(release_reference_state(state, id));
13898
13899         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13900                 mark_ptr_or_null_reg(state, reg, id, is_null);
13901         }));
13902 }
13903
13904 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13905                                    struct bpf_reg_state *dst_reg,
13906                                    struct bpf_reg_state *src_reg,
13907                                    struct bpf_verifier_state *this_branch,
13908                                    struct bpf_verifier_state *other_branch)
13909 {
13910         if (BPF_SRC(insn->code) != BPF_X)
13911                 return false;
13912
13913         /* Pointers are always 64-bit. */
13914         if (BPF_CLASS(insn->code) == BPF_JMP32)
13915                 return false;
13916
13917         switch (BPF_OP(insn->code)) {
13918         case BPF_JGT:
13919                 if ((dst_reg->type == PTR_TO_PACKET &&
13920                      src_reg->type == PTR_TO_PACKET_END) ||
13921                     (dst_reg->type == PTR_TO_PACKET_META &&
13922                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13923                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13924                         find_good_pkt_pointers(this_branch, dst_reg,
13925                                                dst_reg->type, false);
13926                         mark_pkt_end(other_branch, insn->dst_reg, true);
13927                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13928                             src_reg->type == PTR_TO_PACKET) ||
13929                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13930                             src_reg->type == PTR_TO_PACKET_META)) {
13931                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13932                         find_good_pkt_pointers(other_branch, src_reg,
13933                                                src_reg->type, true);
13934                         mark_pkt_end(this_branch, insn->src_reg, false);
13935                 } else {
13936                         return false;
13937                 }
13938                 break;
13939         case BPF_JLT:
13940                 if ((dst_reg->type == PTR_TO_PACKET &&
13941                      src_reg->type == PTR_TO_PACKET_END) ||
13942                     (dst_reg->type == PTR_TO_PACKET_META &&
13943                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13944                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13945                         find_good_pkt_pointers(other_branch, dst_reg,
13946                                                dst_reg->type, true);
13947                         mark_pkt_end(this_branch, insn->dst_reg, false);
13948                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13949                             src_reg->type == PTR_TO_PACKET) ||
13950                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13951                             src_reg->type == PTR_TO_PACKET_META)) {
13952                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13953                         find_good_pkt_pointers(this_branch, src_reg,
13954                                                src_reg->type, false);
13955                         mark_pkt_end(other_branch, insn->src_reg, true);
13956                 } else {
13957                         return false;
13958                 }
13959                 break;
13960         case BPF_JGE:
13961                 if ((dst_reg->type == PTR_TO_PACKET &&
13962                      src_reg->type == PTR_TO_PACKET_END) ||
13963                     (dst_reg->type == PTR_TO_PACKET_META &&
13964                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13965                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13966                         find_good_pkt_pointers(this_branch, dst_reg,
13967                                                dst_reg->type, true);
13968                         mark_pkt_end(other_branch, insn->dst_reg, false);
13969                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13970                             src_reg->type == PTR_TO_PACKET) ||
13971                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13972                             src_reg->type == PTR_TO_PACKET_META)) {
13973                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13974                         find_good_pkt_pointers(other_branch, src_reg,
13975                                                src_reg->type, false);
13976                         mark_pkt_end(this_branch, insn->src_reg, true);
13977                 } else {
13978                         return false;
13979                 }
13980                 break;
13981         case BPF_JLE:
13982                 if ((dst_reg->type == PTR_TO_PACKET &&
13983                      src_reg->type == PTR_TO_PACKET_END) ||
13984                     (dst_reg->type == PTR_TO_PACKET_META &&
13985                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13986                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13987                         find_good_pkt_pointers(other_branch, dst_reg,
13988                                                dst_reg->type, false);
13989                         mark_pkt_end(this_branch, insn->dst_reg, true);
13990                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13991                             src_reg->type == PTR_TO_PACKET) ||
13992                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13993                             src_reg->type == PTR_TO_PACKET_META)) {
13994                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13995                         find_good_pkt_pointers(this_branch, src_reg,
13996                                                src_reg->type, true);
13997                         mark_pkt_end(other_branch, insn->src_reg, false);
13998                 } else {
13999                         return false;
14000                 }
14001                 break;
14002         default:
14003                 return false;
14004         }
14005
14006         return true;
14007 }
14008
14009 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14010                                struct bpf_reg_state *known_reg)
14011 {
14012         struct bpf_func_state *state;
14013         struct bpf_reg_state *reg;
14014
14015         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14016                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14017                         copy_register_state(reg, known_reg);
14018         }));
14019 }
14020
14021 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14022                              struct bpf_insn *insn, int *insn_idx)
14023 {
14024         struct bpf_verifier_state *this_branch = env->cur_state;
14025         struct bpf_verifier_state *other_branch;
14026         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14027         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14028         struct bpf_reg_state *eq_branch_regs;
14029         u8 opcode = BPF_OP(insn->code);
14030         bool is_jmp32;
14031         int pred = -1;
14032         int err;
14033
14034         /* Only conditional jumps are expected to reach here. */
14035         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14036                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14037                 return -EINVAL;
14038         }
14039
14040         if (BPF_SRC(insn->code) == BPF_X) {
14041                 if (insn->imm != 0) {
14042                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14043                         return -EINVAL;
14044                 }
14045
14046                 /* check src1 operand */
14047                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14048                 if (err)
14049                         return err;
14050
14051                 if (is_pointer_value(env, insn->src_reg)) {
14052                         verbose(env, "R%d pointer comparison prohibited\n",
14053                                 insn->src_reg);
14054                         return -EACCES;
14055                 }
14056                 src_reg = &regs[insn->src_reg];
14057         } else {
14058                 if (insn->src_reg != BPF_REG_0) {
14059                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14060                         return -EINVAL;
14061                 }
14062         }
14063
14064         /* check src2 operand */
14065         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14066         if (err)
14067                 return err;
14068
14069         dst_reg = &regs[insn->dst_reg];
14070         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14071
14072         if (BPF_SRC(insn->code) == BPF_K) {
14073                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14074         } else if (src_reg->type == SCALAR_VALUE &&
14075                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14076                 pred = is_branch_taken(dst_reg,
14077                                        tnum_subreg(src_reg->var_off).value,
14078                                        opcode,
14079                                        is_jmp32);
14080         } else if (src_reg->type == SCALAR_VALUE &&
14081                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14082                 pred = is_branch_taken(dst_reg,
14083                                        src_reg->var_off.value,
14084                                        opcode,
14085                                        is_jmp32);
14086         } else if (dst_reg->type == SCALAR_VALUE &&
14087                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14088                 pred = is_branch_taken(src_reg,
14089                                        tnum_subreg(dst_reg->var_off).value,
14090                                        flip_opcode(opcode),
14091                                        is_jmp32);
14092         } else if (dst_reg->type == SCALAR_VALUE &&
14093                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14094                 pred = is_branch_taken(src_reg,
14095                                        dst_reg->var_off.value,
14096                                        flip_opcode(opcode),
14097                                        is_jmp32);
14098         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14099                    reg_is_pkt_pointer_any(src_reg) &&
14100                    !is_jmp32) {
14101                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14102         }
14103
14104         if (pred >= 0) {
14105                 /* If we get here with a dst_reg pointer type it is because
14106                  * above is_branch_taken() special cased the 0 comparison.
14107                  */
14108                 if (!__is_pointer_value(false, dst_reg))
14109                         err = mark_chain_precision(env, insn->dst_reg);
14110                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14111                     !__is_pointer_value(false, src_reg))
14112                         err = mark_chain_precision(env, insn->src_reg);
14113                 if (err)
14114                         return err;
14115         }
14116
14117         if (pred == 1) {
14118                 /* Only follow the goto, ignore fall-through. If needed, push
14119                  * the fall-through branch for simulation under speculative
14120                  * execution.
14121                  */
14122                 if (!env->bypass_spec_v1 &&
14123                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14124                                                *insn_idx))
14125                         return -EFAULT;
14126                 *insn_idx += insn->off;
14127                 return 0;
14128         } else if (pred == 0) {
14129                 /* Only follow the fall-through branch, since that's where the
14130                  * program will go. If needed, push the goto branch for
14131                  * simulation under speculative execution.
14132                  */
14133                 if (!env->bypass_spec_v1 &&
14134                     !sanitize_speculative_path(env, insn,
14135                                                *insn_idx + insn->off + 1,
14136                                                *insn_idx))
14137                         return -EFAULT;
14138                 return 0;
14139         }
14140
14141         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14142                                   false);
14143         if (!other_branch)
14144                 return -EFAULT;
14145         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14146
14147         /* detect if we are comparing against a constant value so we can adjust
14148          * our min/max values for our dst register.
14149          * this is only legit if both are scalars (or pointers to the same
14150          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14151          * because otherwise the different base pointers mean the offsets aren't
14152          * comparable.
14153          */
14154         if (BPF_SRC(insn->code) == BPF_X) {
14155                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14156
14157                 if (dst_reg->type == SCALAR_VALUE &&
14158                     src_reg->type == SCALAR_VALUE) {
14159                         if (tnum_is_const(src_reg->var_off) ||
14160                             (is_jmp32 &&
14161                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14162                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14163                                                 dst_reg,
14164                                                 src_reg->var_off.value,
14165                                                 tnum_subreg(src_reg->var_off).value,
14166                                                 opcode, is_jmp32);
14167                         else if (tnum_is_const(dst_reg->var_off) ||
14168                                  (is_jmp32 &&
14169                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14170                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14171                                                     src_reg,
14172                                                     dst_reg->var_off.value,
14173                                                     tnum_subreg(dst_reg->var_off).value,
14174                                                     opcode, is_jmp32);
14175                         else if (!is_jmp32 &&
14176                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14177                                 /* Comparing for equality, we can combine knowledge */
14178                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14179                                                     &other_branch_regs[insn->dst_reg],
14180                                                     src_reg, dst_reg, opcode);
14181                         if (src_reg->id &&
14182                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14183                                 find_equal_scalars(this_branch, src_reg);
14184                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14185                         }
14186
14187                 }
14188         } else if (dst_reg->type == SCALAR_VALUE) {
14189                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14190                                         dst_reg, insn->imm, (u32)insn->imm,
14191                                         opcode, is_jmp32);
14192         }
14193
14194         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14195             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14196                 find_equal_scalars(this_branch, dst_reg);
14197                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14198         }
14199
14200         /* if one pointer register is compared to another pointer
14201          * register check if PTR_MAYBE_NULL could be lifted.
14202          * E.g. register A - maybe null
14203          *      register B - not null
14204          * for JNE A, B, ... - A is not null in the false branch;
14205          * for JEQ A, B, ... - A is not null in the true branch.
14206          *
14207          * Since PTR_TO_BTF_ID points to a kernel struct that does
14208          * not need to be null checked by the BPF program, i.e.,
14209          * could be null even without PTR_MAYBE_NULL marking, so
14210          * only propagate nullness when neither reg is that type.
14211          */
14212         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14213             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14214             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14215             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14216             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14217                 eq_branch_regs = NULL;
14218                 switch (opcode) {
14219                 case BPF_JEQ:
14220                         eq_branch_regs = other_branch_regs;
14221                         break;
14222                 case BPF_JNE:
14223                         eq_branch_regs = regs;
14224                         break;
14225                 default:
14226                         /* do nothing */
14227                         break;
14228                 }
14229                 if (eq_branch_regs) {
14230                         if (type_may_be_null(src_reg->type))
14231                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14232                         else
14233                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14234                 }
14235         }
14236
14237         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14238          * NOTE: these optimizations below are related with pointer comparison
14239          *       which will never be JMP32.
14240          */
14241         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14242             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14243             type_may_be_null(dst_reg->type)) {
14244                 /* Mark all identical registers in each branch as either
14245                  * safe or unknown depending R == 0 or R != 0 conditional.
14246                  */
14247                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14248                                       opcode == BPF_JNE);
14249                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14250                                       opcode == BPF_JEQ);
14251         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14252                                            this_branch, other_branch) &&
14253                    is_pointer_value(env, insn->dst_reg)) {
14254                 verbose(env, "R%d pointer comparison prohibited\n",
14255                         insn->dst_reg);
14256                 return -EACCES;
14257         }
14258         if (env->log.level & BPF_LOG_LEVEL)
14259                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14260         return 0;
14261 }
14262
14263 /* verify BPF_LD_IMM64 instruction */
14264 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14265 {
14266         struct bpf_insn_aux_data *aux = cur_aux(env);
14267         struct bpf_reg_state *regs = cur_regs(env);
14268         struct bpf_reg_state *dst_reg;
14269         struct bpf_map *map;
14270         int err;
14271
14272         if (BPF_SIZE(insn->code) != BPF_DW) {
14273                 verbose(env, "invalid BPF_LD_IMM insn\n");
14274                 return -EINVAL;
14275         }
14276         if (insn->off != 0) {
14277                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14278                 return -EINVAL;
14279         }
14280
14281         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14282         if (err)
14283                 return err;
14284
14285         dst_reg = &regs[insn->dst_reg];
14286         if (insn->src_reg == 0) {
14287                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14288
14289                 dst_reg->type = SCALAR_VALUE;
14290                 __mark_reg_known(&regs[insn->dst_reg], imm);
14291                 return 0;
14292         }
14293
14294         /* All special src_reg cases are listed below. From this point onwards
14295          * we either succeed and assign a corresponding dst_reg->type after
14296          * zeroing the offset, or fail and reject the program.
14297          */
14298         mark_reg_known_zero(env, regs, insn->dst_reg);
14299
14300         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14301                 dst_reg->type = aux->btf_var.reg_type;
14302                 switch (base_type(dst_reg->type)) {
14303                 case PTR_TO_MEM:
14304                         dst_reg->mem_size = aux->btf_var.mem_size;
14305                         break;
14306                 case PTR_TO_BTF_ID:
14307                         dst_reg->btf = aux->btf_var.btf;
14308                         dst_reg->btf_id = aux->btf_var.btf_id;
14309                         break;
14310                 default:
14311                         verbose(env, "bpf verifier is misconfigured\n");
14312                         return -EFAULT;
14313                 }
14314                 return 0;
14315         }
14316
14317         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14318                 struct bpf_prog_aux *aux = env->prog->aux;
14319                 u32 subprogno = find_subprog(env,
14320                                              env->insn_idx + insn->imm + 1);
14321
14322                 if (!aux->func_info) {
14323                         verbose(env, "missing btf func_info\n");
14324                         return -EINVAL;
14325                 }
14326                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14327                         verbose(env, "callback function not static\n");
14328                         return -EINVAL;
14329                 }
14330
14331                 dst_reg->type = PTR_TO_FUNC;
14332                 dst_reg->subprogno = subprogno;
14333                 return 0;
14334         }
14335
14336         map = env->used_maps[aux->map_index];
14337         dst_reg->map_ptr = map;
14338
14339         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14340             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14341                 dst_reg->type = PTR_TO_MAP_VALUE;
14342                 dst_reg->off = aux->map_off;
14343                 WARN_ON_ONCE(map->max_entries != 1);
14344                 /* We want reg->id to be same (0) as map_value is not distinct */
14345         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14346                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14347                 dst_reg->type = CONST_PTR_TO_MAP;
14348         } else {
14349                 verbose(env, "bpf verifier is misconfigured\n");
14350                 return -EINVAL;
14351         }
14352
14353         return 0;
14354 }
14355
14356 static bool may_access_skb(enum bpf_prog_type type)
14357 {
14358         switch (type) {
14359         case BPF_PROG_TYPE_SOCKET_FILTER:
14360         case BPF_PROG_TYPE_SCHED_CLS:
14361         case BPF_PROG_TYPE_SCHED_ACT:
14362                 return true;
14363         default:
14364                 return false;
14365         }
14366 }
14367
14368 /* verify safety of LD_ABS|LD_IND instructions:
14369  * - they can only appear in the programs where ctx == skb
14370  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14371  *   preserve R6-R9, and store return value into R0
14372  *
14373  * Implicit input:
14374  *   ctx == skb == R6 == CTX
14375  *
14376  * Explicit input:
14377  *   SRC == any register
14378  *   IMM == 32-bit immediate
14379  *
14380  * Output:
14381  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14382  */
14383 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14384 {
14385         struct bpf_reg_state *regs = cur_regs(env);
14386         static const int ctx_reg = BPF_REG_6;
14387         u8 mode = BPF_MODE(insn->code);
14388         int i, err;
14389
14390         if (!may_access_skb(resolve_prog_type(env->prog))) {
14391                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14392                 return -EINVAL;
14393         }
14394
14395         if (!env->ops->gen_ld_abs) {
14396                 verbose(env, "bpf verifier is misconfigured\n");
14397                 return -EINVAL;
14398         }
14399
14400         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14401             BPF_SIZE(insn->code) == BPF_DW ||
14402             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14403                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14404                 return -EINVAL;
14405         }
14406
14407         /* check whether implicit source operand (register R6) is readable */
14408         err = check_reg_arg(env, ctx_reg, SRC_OP);
14409         if (err)
14410                 return err;
14411
14412         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14413          * gen_ld_abs() may terminate the program at runtime, leading to
14414          * reference leak.
14415          */
14416         err = check_reference_leak(env);
14417         if (err) {
14418                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14419                 return err;
14420         }
14421
14422         if (env->cur_state->active_lock.ptr) {
14423                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14424                 return -EINVAL;
14425         }
14426
14427         if (env->cur_state->active_rcu_lock) {
14428                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14429                 return -EINVAL;
14430         }
14431
14432         if (regs[ctx_reg].type != PTR_TO_CTX) {
14433                 verbose(env,
14434                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14435                 return -EINVAL;
14436         }
14437
14438         if (mode == BPF_IND) {
14439                 /* check explicit source operand */
14440                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14441                 if (err)
14442                         return err;
14443         }
14444
14445         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14446         if (err < 0)
14447                 return err;
14448
14449         /* reset caller saved regs to unreadable */
14450         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14451                 mark_reg_not_init(env, regs, caller_saved[i]);
14452                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14453         }
14454
14455         /* mark destination R0 register as readable, since it contains
14456          * the value fetched from the packet.
14457          * Already marked as written above.
14458          */
14459         mark_reg_unknown(env, regs, BPF_REG_0);
14460         /* ld_abs load up to 32-bit skb data. */
14461         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14462         return 0;
14463 }
14464
14465 static int check_return_code(struct bpf_verifier_env *env)
14466 {
14467         struct tnum enforce_attach_type_range = tnum_unknown;
14468         const struct bpf_prog *prog = env->prog;
14469         struct bpf_reg_state *reg;
14470         struct tnum range = tnum_range(0, 1);
14471         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14472         int err;
14473         struct bpf_func_state *frame = env->cur_state->frame[0];
14474         const bool is_subprog = frame->subprogno;
14475
14476         /* LSM and struct_ops func-ptr's return type could be "void" */
14477         if (!is_subprog) {
14478                 switch (prog_type) {
14479                 case BPF_PROG_TYPE_LSM:
14480                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14481                                 /* See below, can be 0 or 0-1 depending on hook. */
14482                                 break;
14483                         fallthrough;
14484                 case BPF_PROG_TYPE_STRUCT_OPS:
14485                         if (!prog->aux->attach_func_proto->type)
14486                                 return 0;
14487                         break;
14488                 default:
14489                         break;
14490                 }
14491         }
14492
14493         /* eBPF calling convention is such that R0 is used
14494          * to return the value from eBPF program.
14495          * Make sure that it's readable at this time
14496          * of bpf_exit, which means that program wrote
14497          * something into it earlier
14498          */
14499         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14500         if (err)
14501                 return err;
14502
14503         if (is_pointer_value(env, BPF_REG_0)) {
14504                 verbose(env, "R0 leaks addr as return value\n");
14505                 return -EACCES;
14506         }
14507
14508         reg = cur_regs(env) + BPF_REG_0;
14509
14510         if (frame->in_async_callback_fn) {
14511                 /* enforce return zero from async callbacks like timer */
14512                 if (reg->type != SCALAR_VALUE) {
14513                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14514                                 reg_type_str(env, reg->type));
14515                         return -EINVAL;
14516                 }
14517
14518                 if (!tnum_in(tnum_const(0), reg->var_off)) {
14519                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14520                         return -EINVAL;
14521                 }
14522                 return 0;
14523         }
14524
14525         if (is_subprog) {
14526                 if (reg->type != SCALAR_VALUE) {
14527                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14528                                 reg_type_str(env, reg->type));
14529                         return -EINVAL;
14530                 }
14531                 return 0;
14532         }
14533
14534         switch (prog_type) {
14535         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14536                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14537                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14538                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14539                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14540                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14541                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14542                         range = tnum_range(1, 1);
14543                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14544                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14545                         range = tnum_range(0, 3);
14546                 break;
14547         case BPF_PROG_TYPE_CGROUP_SKB:
14548                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14549                         range = tnum_range(0, 3);
14550                         enforce_attach_type_range = tnum_range(2, 3);
14551                 }
14552                 break;
14553         case BPF_PROG_TYPE_CGROUP_SOCK:
14554         case BPF_PROG_TYPE_SOCK_OPS:
14555         case BPF_PROG_TYPE_CGROUP_DEVICE:
14556         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14557         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14558                 break;
14559         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14560                 if (!env->prog->aux->attach_btf_id)
14561                         return 0;
14562                 range = tnum_const(0);
14563                 break;
14564         case BPF_PROG_TYPE_TRACING:
14565                 switch (env->prog->expected_attach_type) {
14566                 case BPF_TRACE_FENTRY:
14567                 case BPF_TRACE_FEXIT:
14568                         range = tnum_const(0);
14569                         break;
14570                 case BPF_TRACE_RAW_TP:
14571                 case BPF_MODIFY_RETURN:
14572                         return 0;
14573                 case BPF_TRACE_ITER:
14574                         break;
14575                 default:
14576                         return -ENOTSUPP;
14577                 }
14578                 break;
14579         case BPF_PROG_TYPE_SK_LOOKUP:
14580                 range = tnum_range(SK_DROP, SK_PASS);
14581                 break;
14582
14583         case BPF_PROG_TYPE_LSM:
14584                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14585                         /* Regular BPF_PROG_TYPE_LSM programs can return
14586                          * any value.
14587                          */
14588                         return 0;
14589                 }
14590                 if (!env->prog->aux->attach_func_proto->type) {
14591                         /* Make sure programs that attach to void
14592                          * hooks don't try to modify return value.
14593                          */
14594                         range = tnum_range(1, 1);
14595                 }
14596                 break;
14597
14598         case BPF_PROG_TYPE_NETFILTER:
14599                 range = tnum_range(NF_DROP, NF_ACCEPT);
14600                 break;
14601         case BPF_PROG_TYPE_EXT:
14602                 /* freplace program can return anything as its return value
14603                  * depends on the to-be-replaced kernel func or bpf program.
14604                  */
14605         default:
14606                 return 0;
14607         }
14608
14609         if (reg->type != SCALAR_VALUE) {
14610                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14611                         reg_type_str(env, reg->type));
14612                 return -EINVAL;
14613         }
14614
14615         if (!tnum_in(range, reg->var_off)) {
14616                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14617                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14618                     prog_type == BPF_PROG_TYPE_LSM &&
14619                     !prog->aux->attach_func_proto->type)
14620                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14621                 return -EINVAL;
14622         }
14623
14624         if (!tnum_is_unknown(enforce_attach_type_range) &&
14625             tnum_in(enforce_attach_type_range, reg->var_off))
14626                 env->prog->enforce_expected_attach_type = 1;
14627         return 0;
14628 }
14629
14630 /* non-recursive DFS pseudo code
14631  * 1  procedure DFS-iterative(G,v):
14632  * 2      label v as discovered
14633  * 3      let S be a stack
14634  * 4      S.push(v)
14635  * 5      while S is not empty
14636  * 6            t <- S.peek()
14637  * 7            if t is what we're looking for:
14638  * 8                return t
14639  * 9            for all edges e in G.adjacentEdges(t) do
14640  * 10               if edge e is already labelled
14641  * 11                   continue with the next edge
14642  * 12               w <- G.adjacentVertex(t,e)
14643  * 13               if vertex w is not discovered and not explored
14644  * 14                   label e as tree-edge
14645  * 15                   label w as discovered
14646  * 16                   S.push(w)
14647  * 17                   continue at 5
14648  * 18               else if vertex w is discovered
14649  * 19                   label e as back-edge
14650  * 20               else
14651  * 21                   // vertex w is explored
14652  * 22                   label e as forward- or cross-edge
14653  * 23           label t as explored
14654  * 24           S.pop()
14655  *
14656  * convention:
14657  * 0x10 - discovered
14658  * 0x11 - discovered and fall-through edge labelled
14659  * 0x12 - discovered and fall-through and branch edges labelled
14660  * 0x20 - explored
14661  */
14662
14663 enum {
14664         DISCOVERED = 0x10,
14665         EXPLORED = 0x20,
14666         FALLTHROUGH = 1,
14667         BRANCH = 2,
14668 };
14669
14670 static u32 state_htab_size(struct bpf_verifier_env *env)
14671 {
14672         return env->prog->len;
14673 }
14674
14675 static struct bpf_verifier_state_list **explored_state(
14676                                         struct bpf_verifier_env *env,
14677                                         int idx)
14678 {
14679         struct bpf_verifier_state *cur = env->cur_state;
14680         struct bpf_func_state *state = cur->frame[cur->curframe];
14681
14682         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14683 }
14684
14685 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14686 {
14687         env->insn_aux_data[idx].prune_point = true;
14688 }
14689
14690 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14691 {
14692         return env->insn_aux_data[insn_idx].prune_point;
14693 }
14694
14695 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14696 {
14697         env->insn_aux_data[idx].force_checkpoint = true;
14698 }
14699
14700 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14701 {
14702         return env->insn_aux_data[insn_idx].force_checkpoint;
14703 }
14704
14705
14706 enum {
14707         DONE_EXPLORING = 0,
14708         KEEP_EXPLORING = 1,
14709 };
14710
14711 /* t, w, e - match pseudo-code above:
14712  * t - index of current instruction
14713  * w - next instruction
14714  * e - edge
14715  */
14716 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14717                      bool loop_ok)
14718 {
14719         int *insn_stack = env->cfg.insn_stack;
14720         int *insn_state = env->cfg.insn_state;
14721
14722         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14723                 return DONE_EXPLORING;
14724
14725         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14726                 return DONE_EXPLORING;
14727
14728         if (w < 0 || w >= env->prog->len) {
14729                 verbose_linfo(env, t, "%d: ", t);
14730                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14731                 return -EINVAL;
14732         }
14733
14734         if (e == BRANCH) {
14735                 /* mark branch target for state pruning */
14736                 mark_prune_point(env, w);
14737                 mark_jmp_point(env, w);
14738         }
14739
14740         if (insn_state[w] == 0) {
14741                 /* tree-edge */
14742                 insn_state[t] = DISCOVERED | e;
14743                 insn_state[w] = DISCOVERED;
14744                 if (env->cfg.cur_stack >= env->prog->len)
14745                         return -E2BIG;
14746                 insn_stack[env->cfg.cur_stack++] = w;
14747                 return KEEP_EXPLORING;
14748         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14749                 if (loop_ok && env->bpf_capable)
14750                         return DONE_EXPLORING;
14751                 verbose_linfo(env, t, "%d: ", t);
14752                 verbose_linfo(env, w, "%d: ", w);
14753                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14754                 return -EINVAL;
14755         } else if (insn_state[w] == EXPLORED) {
14756                 /* forward- or cross-edge */
14757                 insn_state[t] = DISCOVERED | e;
14758         } else {
14759                 verbose(env, "insn state internal bug\n");
14760                 return -EFAULT;
14761         }
14762         return DONE_EXPLORING;
14763 }
14764
14765 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14766                                 struct bpf_verifier_env *env,
14767                                 bool visit_callee)
14768 {
14769         int ret;
14770
14771         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14772         if (ret)
14773                 return ret;
14774
14775         mark_prune_point(env, t + 1);
14776         /* when we exit from subprog, we need to record non-linear history */
14777         mark_jmp_point(env, t + 1);
14778
14779         if (visit_callee) {
14780                 mark_prune_point(env, t);
14781                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14782                                 /* It's ok to allow recursion from CFG point of
14783                                  * view. __check_func_call() will do the actual
14784                                  * check.
14785                                  */
14786                                 bpf_pseudo_func(insns + t));
14787         }
14788         return ret;
14789 }
14790
14791 /* Visits the instruction at index t and returns one of the following:
14792  *  < 0 - an error occurred
14793  *  DONE_EXPLORING - the instruction was fully explored
14794  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14795  */
14796 static int visit_insn(int t, struct bpf_verifier_env *env)
14797 {
14798         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14799         int ret, off;
14800
14801         if (bpf_pseudo_func(insn))
14802                 return visit_func_call_insn(t, insns, env, true);
14803
14804         /* All non-branch instructions have a single fall-through edge. */
14805         if (BPF_CLASS(insn->code) != BPF_JMP &&
14806             BPF_CLASS(insn->code) != BPF_JMP32)
14807                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14808
14809         switch (BPF_OP(insn->code)) {
14810         case BPF_EXIT:
14811                 return DONE_EXPLORING;
14812
14813         case BPF_CALL:
14814                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14815                         /* Mark this call insn as a prune point to trigger
14816                          * is_state_visited() check before call itself is
14817                          * processed by __check_func_call(). Otherwise new
14818                          * async state will be pushed for further exploration.
14819                          */
14820                         mark_prune_point(env, t);
14821                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14822                         struct bpf_kfunc_call_arg_meta meta;
14823
14824                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14825                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14826                                 mark_prune_point(env, t);
14827                                 /* Checking and saving state checkpoints at iter_next() call
14828                                  * is crucial for fast convergence of open-coded iterator loop
14829                                  * logic, so we need to force it. If we don't do that,
14830                                  * is_state_visited() might skip saving a checkpoint, causing
14831                                  * unnecessarily long sequence of not checkpointed
14832                                  * instructions and jumps, leading to exhaustion of jump
14833                                  * history buffer, and potentially other undesired outcomes.
14834                                  * It is expected that with correct open-coded iterators
14835                                  * convergence will happen quickly, so we don't run a risk of
14836                                  * exhausting memory.
14837                                  */
14838                                 mark_force_checkpoint(env, t);
14839                         }
14840                 }
14841                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14842
14843         case BPF_JA:
14844                 if (BPF_SRC(insn->code) != BPF_K)
14845                         return -EINVAL;
14846
14847                 if (BPF_CLASS(insn->code) == BPF_JMP)
14848                         off = insn->off;
14849                 else
14850                         off = insn->imm;
14851
14852                 /* unconditional jump with single edge */
14853                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env,
14854                                 true);
14855                 if (ret)
14856                         return ret;
14857
14858                 mark_prune_point(env, t + off + 1);
14859                 mark_jmp_point(env, t + off + 1);
14860
14861                 return ret;
14862
14863         default:
14864                 /* conditional jump with two edges */
14865                 mark_prune_point(env, t);
14866
14867                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14868                 if (ret)
14869                         return ret;
14870
14871                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14872         }
14873 }
14874
14875 /* non-recursive depth-first-search to detect loops in BPF program
14876  * loop == back-edge in directed graph
14877  */
14878 static int check_cfg(struct bpf_verifier_env *env)
14879 {
14880         int insn_cnt = env->prog->len;
14881         int *insn_stack, *insn_state;
14882         int ret = 0;
14883         int i;
14884
14885         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14886         if (!insn_state)
14887                 return -ENOMEM;
14888
14889         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14890         if (!insn_stack) {
14891                 kvfree(insn_state);
14892                 return -ENOMEM;
14893         }
14894
14895         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14896         insn_stack[0] = 0; /* 0 is the first instruction */
14897         env->cfg.cur_stack = 1;
14898
14899         while (env->cfg.cur_stack > 0) {
14900                 int t = insn_stack[env->cfg.cur_stack - 1];
14901
14902                 ret = visit_insn(t, env);
14903                 switch (ret) {
14904                 case DONE_EXPLORING:
14905                         insn_state[t] = EXPLORED;
14906                         env->cfg.cur_stack--;
14907                         break;
14908                 case KEEP_EXPLORING:
14909                         break;
14910                 default:
14911                         if (ret > 0) {
14912                                 verbose(env, "visit_insn internal bug\n");
14913                                 ret = -EFAULT;
14914                         }
14915                         goto err_free;
14916                 }
14917         }
14918
14919         if (env->cfg.cur_stack < 0) {
14920                 verbose(env, "pop stack internal bug\n");
14921                 ret = -EFAULT;
14922                 goto err_free;
14923         }
14924
14925         for (i = 0; i < insn_cnt; i++) {
14926                 if (insn_state[i] != EXPLORED) {
14927                         verbose(env, "unreachable insn %d\n", i);
14928                         ret = -EINVAL;
14929                         goto err_free;
14930                 }
14931         }
14932         ret = 0; /* cfg looks good */
14933
14934 err_free:
14935         kvfree(insn_state);
14936         kvfree(insn_stack);
14937         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14938         return ret;
14939 }
14940
14941 static int check_abnormal_return(struct bpf_verifier_env *env)
14942 {
14943         int i;
14944
14945         for (i = 1; i < env->subprog_cnt; i++) {
14946                 if (env->subprog_info[i].has_ld_abs) {
14947                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14948                         return -EINVAL;
14949                 }
14950                 if (env->subprog_info[i].has_tail_call) {
14951                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14952                         return -EINVAL;
14953                 }
14954         }
14955         return 0;
14956 }
14957
14958 /* The minimum supported BTF func info size */
14959 #define MIN_BPF_FUNCINFO_SIZE   8
14960 #define MAX_FUNCINFO_REC_SIZE   252
14961
14962 static int check_btf_func(struct bpf_verifier_env *env,
14963                           const union bpf_attr *attr,
14964                           bpfptr_t uattr)
14965 {
14966         const struct btf_type *type, *func_proto, *ret_type;
14967         u32 i, nfuncs, urec_size, min_size;
14968         u32 krec_size = sizeof(struct bpf_func_info);
14969         struct bpf_func_info *krecord;
14970         struct bpf_func_info_aux *info_aux = NULL;
14971         struct bpf_prog *prog;
14972         const struct btf *btf;
14973         bpfptr_t urecord;
14974         u32 prev_offset = 0;
14975         bool scalar_return;
14976         int ret = -ENOMEM;
14977
14978         nfuncs = attr->func_info_cnt;
14979         if (!nfuncs) {
14980                 if (check_abnormal_return(env))
14981                         return -EINVAL;
14982                 return 0;
14983         }
14984
14985         if (nfuncs != env->subprog_cnt) {
14986                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14987                 return -EINVAL;
14988         }
14989
14990         urec_size = attr->func_info_rec_size;
14991         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14992             urec_size > MAX_FUNCINFO_REC_SIZE ||
14993             urec_size % sizeof(u32)) {
14994                 verbose(env, "invalid func info rec size %u\n", urec_size);
14995                 return -EINVAL;
14996         }
14997
14998         prog = env->prog;
14999         btf = prog->aux->btf;
15000
15001         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15002         min_size = min_t(u32, krec_size, urec_size);
15003
15004         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15005         if (!krecord)
15006                 return -ENOMEM;
15007         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15008         if (!info_aux)
15009                 goto err_free;
15010
15011         for (i = 0; i < nfuncs; i++) {
15012                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15013                 if (ret) {
15014                         if (ret == -E2BIG) {
15015                                 verbose(env, "nonzero tailing record in func info");
15016                                 /* set the size kernel expects so loader can zero
15017                                  * out the rest of the record.
15018                                  */
15019                                 if (copy_to_bpfptr_offset(uattr,
15020                                                           offsetof(union bpf_attr, func_info_rec_size),
15021                                                           &min_size, sizeof(min_size)))
15022                                         ret = -EFAULT;
15023                         }
15024                         goto err_free;
15025                 }
15026
15027                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15028                         ret = -EFAULT;
15029                         goto err_free;
15030                 }
15031
15032                 /* check insn_off */
15033                 ret = -EINVAL;
15034                 if (i == 0) {
15035                         if (krecord[i].insn_off) {
15036                                 verbose(env,
15037                                         "nonzero insn_off %u for the first func info record",
15038                                         krecord[i].insn_off);
15039                                 goto err_free;
15040                         }
15041                 } else if (krecord[i].insn_off <= prev_offset) {
15042                         verbose(env,
15043                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15044                                 krecord[i].insn_off, prev_offset);
15045                         goto err_free;
15046                 }
15047
15048                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15049                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15050                         goto err_free;
15051                 }
15052
15053                 /* check type_id */
15054                 type = btf_type_by_id(btf, krecord[i].type_id);
15055                 if (!type || !btf_type_is_func(type)) {
15056                         verbose(env, "invalid type id %d in func info",
15057                                 krecord[i].type_id);
15058                         goto err_free;
15059                 }
15060                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15061
15062                 func_proto = btf_type_by_id(btf, type->type);
15063                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15064                         /* btf_func_check() already verified it during BTF load */
15065                         goto err_free;
15066                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15067                 scalar_return =
15068                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15069                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15070                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15071                         goto err_free;
15072                 }
15073                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15074                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15075                         goto err_free;
15076                 }
15077
15078                 prev_offset = krecord[i].insn_off;
15079                 bpfptr_add(&urecord, urec_size);
15080         }
15081
15082         prog->aux->func_info = krecord;
15083         prog->aux->func_info_cnt = nfuncs;
15084         prog->aux->func_info_aux = info_aux;
15085         return 0;
15086
15087 err_free:
15088         kvfree(krecord);
15089         kfree(info_aux);
15090         return ret;
15091 }
15092
15093 static void adjust_btf_func(struct bpf_verifier_env *env)
15094 {
15095         struct bpf_prog_aux *aux = env->prog->aux;
15096         int i;
15097
15098         if (!aux->func_info)
15099                 return;
15100
15101         for (i = 0; i < env->subprog_cnt; i++)
15102                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15103 }
15104
15105 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15106 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15107
15108 static int check_btf_line(struct bpf_verifier_env *env,
15109                           const union bpf_attr *attr,
15110                           bpfptr_t uattr)
15111 {
15112         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15113         struct bpf_subprog_info *sub;
15114         struct bpf_line_info *linfo;
15115         struct bpf_prog *prog;
15116         const struct btf *btf;
15117         bpfptr_t ulinfo;
15118         int err;
15119
15120         nr_linfo = attr->line_info_cnt;
15121         if (!nr_linfo)
15122                 return 0;
15123         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15124                 return -EINVAL;
15125
15126         rec_size = attr->line_info_rec_size;
15127         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15128             rec_size > MAX_LINEINFO_REC_SIZE ||
15129             rec_size & (sizeof(u32) - 1))
15130                 return -EINVAL;
15131
15132         /* Need to zero it in case the userspace may
15133          * pass in a smaller bpf_line_info object.
15134          */
15135         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15136                          GFP_KERNEL | __GFP_NOWARN);
15137         if (!linfo)
15138                 return -ENOMEM;
15139
15140         prog = env->prog;
15141         btf = prog->aux->btf;
15142
15143         s = 0;
15144         sub = env->subprog_info;
15145         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15146         expected_size = sizeof(struct bpf_line_info);
15147         ncopy = min_t(u32, expected_size, rec_size);
15148         for (i = 0; i < nr_linfo; i++) {
15149                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15150                 if (err) {
15151                         if (err == -E2BIG) {
15152                                 verbose(env, "nonzero tailing record in line_info");
15153                                 if (copy_to_bpfptr_offset(uattr,
15154                                                           offsetof(union bpf_attr, line_info_rec_size),
15155                                                           &expected_size, sizeof(expected_size)))
15156                                         err = -EFAULT;
15157                         }
15158                         goto err_free;
15159                 }
15160
15161                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15162                         err = -EFAULT;
15163                         goto err_free;
15164                 }
15165
15166                 /*
15167                  * Check insn_off to ensure
15168                  * 1) strictly increasing AND
15169                  * 2) bounded by prog->len
15170                  *
15171                  * The linfo[0].insn_off == 0 check logically falls into
15172                  * the later "missing bpf_line_info for func..." case
15173                  * because the first linfo[0].insn_off must be the
15174                  * first sub also and the first sub must have
15175                  * subprog_info[0].start == 0.
15176                  */
15177                 if ((i && linfo[i].insn_off <= prev_offset) ||
15178                     linfo[i].insn_off >= prog->len) {
15179                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15180                                 i, linfo[i].insn_off, prev_offset,
15181                                 prog->len);
15182                         err = -EINVAL;
15183                         goto err_free;
15184                 }
15185
15186                 if (!prog->insnsi[linfo[i].insn_off].code) {
15187                         verbose(env,
15188                                 "Invalid insn code at line_info[%u].insn_off\n",
15189                                 i);
15190                         err = -EINVAL;
15191                         goto err_free;
15192                 }
15193
15194                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15195                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15196                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15197                         err = -EINVAL;
15198                         goto err_free;
15199                 }
15200
15201                 if (s != env->subprog_cnt) {
15202                         if (linfo[i].insn_off == sub[s].start) {
15203                                 sub[s].linfo_idx = i;
15204                                 s++;
15205                         } else if (sub[s].start < linfo[i].insn_off) {
15206                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15207                                 err = -EINVAL;
15208                                 goto err_free;
15209                         }
15210                 }
15211
15212                 prev_offset = linfo[i].insn_off;
15213                 bpfptr_add(&ulinfo, rec_size);
15214         }
15215
15216         if (s != env->subprog_cnt) {
15217                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15218                         env->subprog_cnt - s, s);
15219                 err = -EINVAL;
15220                 goto err_free;
15221         }
15222
15223         prog->aux->linfo = linfo;
15224         prog->aux->nr_linfo = nr_linfo;
15225
15226         return 0;
15227
15228 err_free:
15229         kvfree(linfo);
15230         return err;
15231 }
15232
15233 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15234 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15235
15236 static int check_core_relo(struct bpf_verifier_env *env,
15237                            const union bpf_attr *attr,
15238                            bpfptr_t uattr)
15239 {
15240         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15241         struct bpf_core_relo core_relo = {};
15242         struct bpf_prog *prog = env->prog;
15243         const struct btf *btf = prog->aux->btf;
15244         struct bpf_core_ctx ctx = {
15245                 .log = &env->log,
15246                 .btf = btf,
15247         };
15248         bpfptr_t u_core_relo;
15249         int err;
15250
15251         nr_core_relo = attr->core_relo_cnt;
15252         if (!nr_core_relo)
15253                 return 0;
15254         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15255                 return -EINVAL;
15256
15257         rec_size = attr->core_relo_rec_size;
15258         if (rec_size < MIN_CORE_RELO_SIZE ||
15259             rec_size > MAX_CORE_RELO_SIZE ||
15260             rec_size % sizeof(u32))
15261                 return -EINVAL;
15262
15263         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15264         expected_size = sizeof(struct bpf_core_relo);
15265         ncopy = min_t(u32, expected_size, rec_size);
15266
15267         /* Unlike func_info and line_info, copy and apply each CO-RE
15268          * relocation record one at a time.
15269          */
15270         for (i = 0; i < nr_core_relo; i++) {
15271                 /* future proofing when sizeof(bpf_core_relo) changes */
15272                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15273                 if (err) {
15274                         if (err == -E2BIG) {
15275                                 verbose(env, "nonzero tailing record in core_relo");
15276                                 if (copy_to_bpfptr_offset(uattr,
15277                                                           offsetof(union bpf_attr, core_relo_rec_size),
15278                                                           &expected_size, sizeof(expected_size)))
15279                                         err = -EFAULT;
15280                         }
15281                         break;
15282                 }
15283
15284                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15285                         err = -EFAULT;
15286                         break;
15287                 }
15288
15289                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15290                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15291                                 i, core_relo.insn_off, prog->len);
15292                         err = -EINVAL;
15293                         break;
15294                 }
15295
15296                 err = bpf_core_apply(&ctx, &core_relo, i,
15297                                      &prog->insnsi[core_relo.insn_off / 8]);
15298                 if (err)
15299                         break;
15300                 bpfptr_add(&u_core_relo, rec_size);
15301         }
15302         return err;
15303 }
15304
15305 static int check_btf_info(struct bpf_verifier_env *env,
15306                           const union bpf_attr *attr,
15307                           bpfptr_t uattr)
15308 {
15309         struct btf *btf;
15310         int err;
15311
15312         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15313                 if (check_abnormal_return(env))
15314                         return -EINVAL;
15315                 return 0;
15316         }
15317
15318         btf = btf_get_by_fd(attr->prog_btf_fd);
15319         if (IS_ERR(btf))
15320                 return PTR_ERR(btf);
15321         if (btf_is_kernel(btf)) {
15322                 btf_put(btf);
15323                 return -EACCES;
15324         }
15325         env->prog->aux->btf = btf;
15326
15327         err = check_btf_func(env, attr, uattr);
15328         if (err)
15329                 return err;
15330
15331         err = check_btf_line(env, attr, uattr);
15332         if (err)
15333                 return err;
15334
15335         err = check_core_relo(env, attr, uattr);
15336         if (err)
15337                 return err;
15338
15339         return 0;
15340 }
15341
15342 /* check %cur's range satisfies %old's */
15343 static bool range_within(struct bpf_reg_state *old,
15344                          struct bpf_reg_state *cur)
15345 {
15346         return old->umin_value <= cur->umin_value &&
15347                old->umax_value >= cur->umax_value &&
15348                old->smin_value <= cur->smin_value &&
15349                old->smax_value >= cur->smax_value &&
15350                old->u32_min_value <= cur->u32_min_value &&
15351                old->u32_max_value >= cur->u32_max_value &&
15352                old->s32_min_value <= cur->s32_min_value &&
15353                old->s32_max_value >= cur->s32_max_value;
15354 }
15355
15356 /* If in the old state two registers had the same id, then they need to have
15357  * the same id in the new state as well.  But that id could be different from
15358  * the old state, so we need to track the mapping from old to new ids.
15359  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15360  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15361  * regs with a different old id could still have new id 9, we don't care about
15362  * that.
15363  * So we look through our idmap to see if this old id has been seen before.  If
15364  * so, we require the new id to match; otherwise, we add the id pair to the map.
15365  */
15366 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15367 {
15368         struct bpf_id_pair *map = idmap->map;
15369         unsigned int i;
15370
15371         /* either both IDs should be set or both should be zero */
15372         if (!!old_id != !!cur_id)
15373                 return false;
15374
15375         if (old_id == 0) /* cur_id == 0 as well */
15376                 return true;
15377
15378         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15379                 if (!map[i].old) {
15380                         /* Reached an empty slot; haven't seen this id before */
15381                         map[i].old = old_id;
15382                         map[i].cur = cur_id;
15383                         return true;
15384                 }
15385                 if (map[i].old == old_id)
15386                         return map[i].cur == cur_id;
15387                 if (map[i].cur == cur_id)
15388                         return false;
15389         }
15390         /* We ran out of idmap slots, which should be impossible */
15391         WARN_ON_ONCE(1);
15392         return false;
15393 }
15394
15395 /* Similar to check_ids(), but allocate a unique temporary ID
15396  * for 'old_id' or 'cur_id' of zero.
15397  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15398  */
15399 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15400 {
15401         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15402         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15403
15404         return check_ids(old_id, cur_id, idmap);
15405 }
15406
15407 static void clean_func_state(struct bpf_verifier_env *env,
15408                              struct bpf_func_state *st)
15409 {
15410         enum bpf_reg_liveness live;
15411         int i, j;
15412
15413         for (i = 0; i < BPF_REG_FP; i++) {
15414                 live = st->regs[i].live;
15415                 /* liveness must not touch this register anymore */
15416                 st->regs[i].live |= REG_LIVE_DONE;
15417                 if (!(live & REG_LIVE_READ))
15418                         /* since the register is unused, clear its state
15419                          * to make further comparison simpler
15420                          */
15421                         __mark_reg_not_init(env, &st->regs[i]);
15422         }
15423
15424         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15425                 live = st->stack[i].spilled_ptr.live;
15426                 /* liveness must not touch this stack slot anymore */
15427                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15428                 if (!(live & REG_LIVE_READ)) {
15429                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15430                         for (j = 0; j < BPF_REG_SIZE; j++)
15431                                 st->stack[i].slot_type[j] = STACK_INVALID;
15432                 }
15433         }
15434 }
15435
15436 static void clean_verifier_state(struct bpf_verifier_env *env,
15437                                  struct bpf_verifier_state *st)
15438 {
15439         int i;
15440
15441         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15442                 /* all regs in this state in all frames were already marked */
15443                 return;
15444
15445         for (i = 0; i <= st->curframe; i++)
15446                 clean_func_state(env, st->frame[i]);
15447 }
15448
15449 /* the parentage chains form a tree.
15450  * the verifier states are added to state lists at given insn and
15451  * pushed into state stack for future exploration.
15452  * when the verifier reaches bpf_exit insn some of the verifer states
15453  * stored in the state lists have their final liveness state already,
15454  * but a lot of states will get revised from liveness point of view when
15455  * the verifier explores other branches.
15456  * Example:
15457  * 1: r0 = 1
15458  * 2: if r1 == 100 goto pc+1
15459  * 3: r0 = 2
15460  * 4: exit
15461  * when the verifier reaches exit insn the register r0 in the state list of
15462  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15463  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15464  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15465  *
15466  * Since the verifier pushes the branch states as it sees them while exploring
15467  * the program the condition of walking the branch instruction for the second
15468  * time means that all states below this branch were already explored and
15469  * their final liveness marks are already propagated.
15470  * Hence when the verifier completes the search of state list in is_state_visited()
15471  * we can call this clean_live_states() function to mark all liveness states
15472  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15473  * will not be used.
15474  * This function also clears the registers and stack for states that !READ
15475  * to simplify state merging.
15476  *
15477  * Important note here that walking the same branch instruction in the callee
15478  * doesn't meant that the states are DONE. The verifier has to compare
15479  * the callsites
15480  */
15481 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15482                               struct bpf_verifier_state *cur)
15483 {
15484         struct bpf_verifier_state_list *sl;
15485         int i;
15486
15487         sl = *explored_state(env, insn);
15488         while (sl) {
15489                 if (sl->state.branches)
15490                         goto next;
15491                 if (sl->state.insn_idx != insn ||
15492                     sl->state.curframe != cur->curframe)
15493                         goto next;
15494                 for (i = 0; i <= cur->curframe; i++)
15495                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15496                                 goto next;
15497                 clean_verifier_state(env, &sl->state);
15498 next:
15499                 sl = sl->next;
15500         }
15501 }
15502
15503 static bool regs_exact(const struct bpf_reg_state *rold,
15504                        const struct bpf_reg_state *rcur,
15505                        struct bpf_idmap *idmap)
15506 {
15507         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15508                check_ids(rold->id, rcur->id, idmap) &&
15509                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15510 }
15511
15512 /* Returns true if (rold safe implies rcur safe) */
15513 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15514                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15515 {
15516         if (!(rold->live & REG_LIVE_READ))
15517                 /* explored state didn't use this */
15518                 return true;
15519         if (rold->type == NOT_INIT)
15520                 /* explored state can't have used this */
15521                 return true;
15522         if (rcur->type == NOT_INIT)
15523                 return false;
15524
15525         /* Enforce that register types have to match exactly, including their
15526          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15527          * rule.
15528          *
15529          * One can make a point that using a pointer register as unbounded
15530          * SCALAR would be technically acceptable, but this could lead to
15531          * pointer leaks because scalars are allowed to leak while pointers
15532          * are not. We could make this safe in special cases if root is
15533          * calling us, but it's probably not worth the hassle.
15534          *
15535          * Also, register types that are *not* MAYBE_NULL could technically be
15536          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15537          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15538          * to the same map).
15539          * However, if the old MAYBE_NULL register then got NULL checked,
15540          * doing so could have affected others with the same id, and we can't
15541          * check for that because we lost the id when we converted to
15542          * a non-MAYBE_NULL variant.
15543          * So, as a general rule we don't allow mixing MAYBE_NULL and
15544          * non-MAYBE_NULL registers as well.
15545          */
15546         if (rold->type != rcur->type)
15547                 return false;
15548
15549         switch (base_type(rold->type)) {
15550         case SCALAR_VALUE:
15551                 if (env->explore_alu_limits) {
15552                         /* explore_alu_limits disables tnum_in() and range_within()
15553                          * logic and requires everything to be strict
15554                          */
15555                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15556                                check_scalar_ids(rold->id, rcur->id, idmap);
15557                 }
15558                 if (!rold->precise)
15559                         return true;
15560                 /* Why check_ids() for scalar registers?
15561                  *
15562                  * Consider the following BPF code:
15563                  *   1: r6 = ... unbound scalar, ID=a ...
15564                  *   2: r7 = ... unbound scalar, ID=b ...
15565                  *   3: if (r6 > r7) goto +1
15566                  *   4: r6 = r7
15567                  *   5: if (r6 > X) goto ...
15568                  *   6: ... memory operation using r7 ...
15569                  *
15570                  * First verification path is [1-6]:
15571                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15572                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15573                  *   r7 <= X, because r6 and r7 share same id.
15574                  * Next verification path is [1-4, 6].
15575                  *
15576                  * Instruction (6) would be reached in two states:
15577                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15578                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15579                  *
15580                  * Use check_ids() to distinguish these states.
15581                  * ---
15582                  * Also verify that new value satisfies old value range knowledge.
15583                  */
15584                 return range_within(rold, rcur) &&
15585                        tnum_in(rold->var_off, rcur->var_off) &&
15586                        check_scalar_ids(rold->id, rcur->id, idmap);
15587         case PTR_TO_MAP_KEY:
15588         case PTR_TO_MAP_VALUE:
15589         case PTR_TO_MEM:
15590         case PTR_TO_BUF:
15591         case PTR_TO_TP_BUFFER:
15592                 /* If the new min/max/var_off satisfy the old ones and
15593                  * everything else matches, we are OK.
15594                  */
15595                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15596                        range_within(rold, rcur) &&
15597                        tnum_in(rold->var_off, rcur->var_off) &&
15598                        check_ids(rold->id, rcur->id, idmap) &&
15599                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15600         case PTR_TO_PACKET_META:
15601         case PTR_TO_PACKET:
15602                 /* We must have at least as much range as the old ptr
15603                  * did, so that any accesses which were safe before are
15604                  * still safe.  This is true even if old range < old off,
15605                  * since someone could have accessed through (ptr - k), or
15606                  * even done ptr -= k in a register, to get a safe access.
15607                  */
15608                 if (rold->range > rcur->range)
15609                         return false;
15610                 /* If the offsets don't match, we can't trust our alignment;
15611                  * nor can we be sure that we won't fall out of range.
15612                  */
15613                 if (rold->off != rcur->off)
15614                         return false;
15615                 /* id relations must be preserved */
15616                 if (!check_ids(rold->id, rcur->id, idmap))
15617                         return false;
15618                 /* new val must satisfy old val knowledge */
15619                 return range_within(rold, rcur) &&
15620                        tnum_in(rold->var_off, rcur->var_off);
15621         case PTR_TO_STACK:
15622                 /* two stack pointers are equal only if they're pointing to
15623                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15624                  */
15625                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15626         default:
15627                 return regs_exact(rold, rcur, idmap);
15628         }
15629 }
15630
15631 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15632                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15633 {
15634         int i, spi;
15635
15636         /* walk slots of the explored stack and ignore any additional
15637          * slots in the current stack, since explored(safe) state
15638          * didn't use them
15639          */
15640         for (i = 0; i < old->allocated_stack; i++) {
15641                 struct bpf_reg_state *old_reg, *cur_reg;
15642
15643                 spi = i / BPF_REG_SIZE;
15644
15645                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15646                         i += BPF_REG_SIZE - 1;
15647                         /* explored state didn't use this */
15648                         continue;
15649                 }
15650
15651                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15652                         continue;
15653
15654                 if (env->allow_uninit_stack &&
15655                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15656                         continue;
15657
15658                 /* explored stack has more populated slots than current stack
15659                  * and these slots were used
15660                  */
15661                 if (i >= cur->allocated_stack)
15662                         return false;
15663
15664                 /* if old state was safe with misc data in the stack
15665                  * it will be safe with zero-initialized stack.
15666                  * The opposite is not true
15667                  */
15668                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15669                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15670                         continue;
15671                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15672                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15673                         /* Ex: old explored (safe) state has STACK_SPILL in
15674                          * this stack slot, but current has STACK_MISC ->
15675                          * this verifier states are not equivalent,
15676                          * return false to continue verification of this path
15677                          */
15678                         return false;
15679                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15680                         continue;
15681                 /* Both old and cur are having same slot_type */
15682                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15683                 case STACK_SPILL:
15684                         /* when explored and current stack slot are both storing
15685                          * spilled registers, check that stored pointers types
15686                          * are the same as well.
15687                          * Ex: explored safe path could have stored
15688                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15689                          * but current path has stored:
15690                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15691                          * such verifier states are not equivalent.
15692                          * return false to continue verification of this path
15693                          */
15694                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15695                                      &cur->stack[spi].spilled_ptr, idmap))
15696                                 return false;
15697                         break;
15698                 case STACK_DYNPTR:
15699                         old_reg = &old->stack[spi].spilled_ptr;
15700                         cur_reg = &cur->stack[spi].spilled_ptr;
15701                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15702                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15703                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15704                                 return false;
15705                         break;
15706                 case STACK_ITER:
15707                         old_reg = &old->stack[spi].spilled_ptr;
15708                         cur_reg = &cur->stack[spi].spilled_ptr;
15709                         /* iter.depth is not compared between states as it
15710                          * doesn't matter for correctness and would otherwise
15711                          * prevent convergence; we maintain it only to prevent
15712                          * infinite loop check triggering, see
15713                          * iter_active_depths_differ()
15714                          */
15715                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15716                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15717                             old_reg->iter.state != cur_reg->iter.state ||
15718                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15719                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15720                                 return false;
15721                         break;
15722                 case STACK_MISC:
15723                 case STACK_ZERO:
15724                 case STACK_INVALID:
15725                         continue;
15726                 /* Ensure that new unhandled slot types return false by default */
15727                 default:
15728                         return false;
15729                 }
15730         }
15731         return true;
15732 }
15733
15734 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15735                     struct bpf_idmap *idmap)
15736 {
15737         int i;
15738
15739         if (old->acquired_refs != cur->acquired_refs)
15740                 return false;
15741
15742         for (i = 0; i < old->acquired_refs; i++) {
15743                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15744                         return false;
15745         }
15746
15747         return true;
15748 }
15749
15750 /* compare two verifier states
15751  *
15752  * all states stored in state_list are known to be valid, since
15753  * verifier reached 'bpf_exit' instruction through them
15754  *
15755  * this function is called when verifier exploring different branches of
15756  * execution popped from the state stack. If it sees an old state that has
15757  * more strict register state and more strict stack state then this execution
15758  * branch doesn't need to be explored further, since verifier already
15759  * concluded that more strict state leads to valid finish.
15760  *
15761  * Therefore two states are equivalent if register state is more conservative
15762  * and explored stack state is more conservative than the current one.
15763  * Example:
15764  *       explored                   current
15765  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15766  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15767  *
15768  * In other words if current stack state (one being explored) has more
15769  * valid slots than old one that already passed validation, it means
15770  * the verifier can stop exploring and conclude that current state is valid too
15771  *
15772  * Similarly with registers. If explored state has register type as invalid
15773  * whereas register type in current state is meaningful, it means that
15774  * the current state will reach 'bpf_exit' instruction safely
15775  */
15776 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15777                               struct bpf_func_state *cur)
15778 {
15779         int i;
15780
15781         for (i = 0; i < MAX_BPF_REG; i++)
15782                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15783                              &env->idmap_scratch))
15784                         return false;
15785
15786         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15787                 return false;
15788
15789         if (!refsafe(old, cur, &env->idmap_scratch))
15790                 return false;
15791
15792         return true;
15793 }
15794
15795 static bool states_equal(struct bpf_verifier_env *env,
15796                          struct bpf_verifier_state *old,
15797                          struct bpf_verifier_state *cur)
15798 {
15799         int i;
15800
15801         if (old->curframe != cur->curframe)
15802                 return false;
15803
15804         env->idmap_scratch.tmp_id_gen = env->id_gen;
15805         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15806
15807         /* Verification state from speculative execution simulation
15808          * must never prune a non-speculative execution one.
15809          */
15810         if (old->speculative && !cur->speculative)
15811                 return false;
15812
15813         if (old->active_lock.ptr != cur->active_lock.ptr)
15814                 return false;
15815
15816         /* Old and cur active_lock's have to be either both present
15817          * or both absent.
15818          */
15819         if (!!old->active_lock.id != !!cur->active_lock.id)
15820                 return false;
15821
15822         if (old->active_lock.id &&
15823             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15824                 return false;
15825
15826         if (old->active_rcu_lock != cur->active_rcu_lock)
15827                 return false;
15828
15829         /* for states to be equal callsites have to be the same
15830          * and all frame states need to be equivalent
15831          */
15832         for (i = 0; i <= old->curframe; i++) {
15833                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15834                         return false;
15835                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15836                         return false;
15837         }
15838         return true;
15839 }
15840
15841 /* Return 0 if no propagation happened. Return negative error code if error
15842  * happened. Otherwise, return the propagated bit.
15843  */
15844 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15845                                   struct bpf_reg_state *reg,
15846                                   struct bpf_reg_state *parent_reg)
15847 {
15848         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15849         u8 flag = reg->live & REG_LIVE_READ;
15850         int err;
15851
15852         /* When comes here, read flags of PARENT_REG or REG could be any of
15853          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15854          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15855          */
15856         if (parent_flag == REG_LIVE_READ64 ||
15857             /* Or if there is no read flag from REG. */
15858             !flag ||
15859             /* Or if the read flag from REG is the same as PARENT_REG. */
15860             parent_flag == flag)
15861                 return 0;
15862
15863         err = mark_reg_read(env, reg, parent_reg, flag);
15864         if (err)
15865                 return err;
15866
15867         return flag;
15868 }
15869
15870 /* A write screens off any subsequent reads; but write marks come from the
15871  * straight-line code between a state and its parent.  When we arrive at an
15872  * equivalent state (jump target or such) we didn't arrive by the straight-line
15873  * code, so read marks in the state must propagate to the parent regardless
15874  * of the state's write marks. That's what 'parent == state->parent' comparison
15875  * in mark_reg_read() is for.
15876  */
15877 static int propagate_liveness(struct bpf_verifier_env *env,
15878                               const struct bpf_verifier_state *vstate,
15879                               struct bpf_verifier_state *vparent)
15880 {
15881         struct bpf_reg_state *state_reg, *parent_reg;
15882         struct bpf_func_state *state, *parent;
15883         int i, frame, err = 0;
15884
15885         if (vparent->curframe != vstate->curframe) {
15886                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15887                      vparent->curframe, vstate->curframe);
15888                 return -EFAULT;
15889         }
15890         /* Propagate read liveness of registers... */
15891         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15892         for (frame = 0; frame <= vstate->curframe; frame++) {
15893                 parent = vparent->frame[frame];
15894                 state = vstate->frame[frame];
15895                 parent_reg = parent->regs;
15896                 state_reg = state->regs;
15897                 /* We don't need to worry about FP liveness, it's read-only */
15898                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15899                         err = propagate_liveness_reg(env, &state_reg[i],
15900                                                      &parent_reg[i]);
15901                         if (err < 0)
15902                                 return err;
15903                         if (err == REG_LIVE_READ64)
15904                                 mark_insn_zext(env, &parent_reg[i]);
15905                 }
15906
15907                 /* Propagate stack slots. */
15908                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15909                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15910                         parent_reg = &parent->stack[i].spilled_ptr;
15911                         state_reg = &state->stack[i].spilled_ptr;
15912                         err = propagate_liveness_reg(env, state_reg,
15913                                                      parent_reg);
15914                         if (err < 0)
15915                                 return err;
15916                 }
15917         }
15918         return 0;
15919 }
15920
15921 /* find precise scalars in the previous equivalent state and
15922  * propagate them into the current state
15923  */
15924 static int propagate_precision(struct bpf_verifier_env *env,
15925                                const struct bpf_verifier_state *old)
15926 {
15927         struct bpf_reg_state *state_reg;
15928         struct bpf_func_state *state;
15929         int i, err = 0, fr;
15930         bool first;
15931
15932         for (fr = old->curframe; fr >= 0; fr--) {
15933                 state = old->frame[fr];
15934                 state_reg = state->regs;
15935                 first = true;
15936                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15937                         if (state_reg->type != SCALAR_VALUE ||
15938                             !state_reg->precise ||
15939                             !(state_reg->live & REG_LIVE_READ))
15940                                 continue;
15941                         if (env->log.level & BPF_LOG_LEVEL2) {
15942                                 if (first)
15943                                         verbose(env, "frame %d: propagating r%d", fr, i);
15944                                 else
15945                                         verbose(env, ",r%d", i);
15946                         }
15947                         bt_set_frame_reg(&env->bt, fr, i);
15948                         first = false;
15949                 }
15950
15951                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15952                         if (!is_spilled_reg(&state->stack[i]))
15953                                 continue;
15954                         state_reg = &state->stack[i].spilled_ptr;
15955                         if (state_reg->type != SCALAR_VALUE ||
15956                             !state_reg->precise ||
15957                             !(state_reg->live & REG_LIVE_READ))
15958                                 continue;
15959                         if (env->log.level & BPF_LOG_LEVEL2) {
15960                                 if (first)
15961                                         verbose(env, "frame %d: propagating fp%d",
15962                                                 fr, (-i - 1) * BPF_REG_SIZE);
15963                                 else
15964                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15965                         }
15966                         bt_set_frame_slot(&env->bt, fr, i);
15967                         first = false;
15968                 }
15969                 if (!first)
15970                         verbose(env, "\n");
15971         }
15972
15973         err = mark_chain_precision_batch(env);
15974         if (err < 0)
15975                 return err;
15976
15977         return 0;
15978 }
15979
15980 static bool states_maybe_looping(struct bpf_verifier_state *old,
15981                                  struct bpf_verifier_state *cur)
15982 {
15983         struct bpf_func_state *fold, *fcur;
15984         int i, fr = cur->curframe;
15985
15986         if (old->curframe != fr)
15987                 return false;
15988
15989         fold = old->frame[fr];
15990         fcur = cur->frame[fr];
15991         for (i = 0; i < MAX_BPF_REG; i++)
15992                 if (memcmp(&fold->regs[i], &fcur->regs[i],
15993                            offsetof(struct bpf_reg_state, parent)))
15994                         return false;
15995         return true;
15996 }
15997
15998 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15999 {
16000         return env->insn_aux_data[insn_idx].is_iter_next;
16001 }
16002
16003 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16004  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16005  * states to match, which otherwise would look like an infinite loop. So while
16006  * iter_next() calls are taken care of, we still need to be careful and
16007  * prevent erroneous and too eager declaration of "ininite loop", when
16008  * iterators are involved.
16009  *
16010  * Here's a situation in pseudo-BPF assembly form:
16011  *
16012  *   0: again:                          ; set up iter_next() call args
16013  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16014  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16015  *   3:   if r0 == 0 goto done
16016  *   4:   ... something useful here ...
16017  *   5:   goto again                    ; another iteration
16018  *   6: done:
16019  *   7:   r1 = &it
16020  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16021  *   9:   exit
16022  *
16023  * This is a typical loop. Let's assume that we have a prune point at 1:,
16024  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16025  * again`, assuming other heuristics don't get in a way).
16026  *
16027  * When we first time come to 1:, let's say we have some state X. We proceed
16028  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16029  * Now we come back to validate that forked ACTIVE state. We proceed through
16030  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16031  * are converging. But the problem is that we don't know that yet, as this
16032  * convergence has to happen at iter_next() call site only. So if nothing is
16033  * done, at 1: verifier will use bounded loop logic and declare infinite
16034  * looping (and would be *technically* correct, if not for iterator's
16035  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16036  * don't want that. So what we do in process_iter_next_call() when we go on
16037  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16038  * a different iteration. So when we suspect an infinite loop, we additionally
16039  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16040  * pretend we are not looping and wait for next iter_next() call.
16041  *
16042  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16043  * loop, because that would actually mean infinite loop, as DRAINED state is
16044  * "sticky", and so we'll keep returning into the same instruction with the
16045  * same state (at least in one of possible code paths).
16046  *
16047  * This approach allows to keep infinite loop heuristic even in the face of
16048  * active iterator. E.g., C snippet below is and will be detected as
16049  * inifintely looping:
16050  *
16051  *   struct bpf_iter_num it;
16052  *   int *p, x;
16053  *
16054  *   bpf_iter_num_new(&it, 0, 10);
16055  *   while ((p = bpf_iter_num_next(&t))) {
16056  *       x = p;
16057  *       while (x--) {} // <<-- infinite loop here
16058  *   }
16059  *
16060  */
16061 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16062 {
16063         struct bpf_reg_state *slot, *cur_slot;
16064         struct bpf_func_state *state;
16065         int i, fr;
16066
16067         for (fr = old->curframe; fr >= 0; fr--) {
16068                 state = old->frame[fr];
16069                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16070                         if (state->stack[i].slot_type[0] != STACK_ITER)
16071                                 continue;
16072
16073                         slot = &state->stack[i].spilled_ptr;
16074                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16075                                 continue;
16076
16077                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16078                         if (cur_slot->iter.depth != slot->iter.depth)
16079                                 return true;
16080                 }
16081         }
16082         return false;
16083 }
16084
16085 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16086 {
16087         struct bpf_verifier_state_list *new_sl;
16088         struct bpf_verifier_state_list *sl, **pprev;
16089         struct bpf_verifier_state *cur = env->cur_state, *new;
16090         int i, j, err, states_cnt = 0;
16091         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16092         bool add_new_state = force_new_state;
16093
16094         /* bpf progs typically have pruning point every 4 instructions
16095          * http://vger.kernel.org/bpfconf2019.html#session-1
16096          * Do not add new state for future pruning if the verifier hasn't seen
16097          * at least 2 jumps and at least 8 instructions.
16098          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16099          * In tests that amounts to up to 50% reduction into total verifier
16100          * memory consumption and 20% verifier time speedup.
16101          */
16102         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16103             env->insn_processed - env->prev_insn_processed >= 8)
16104                 add_new_state = true;
16105
16106         pprev = explored_state(env, insn_idx);
16107         sl = *pprev;
16108
16109         clean_live_states(env, insn_idx, cur);
16110
16111         while (sl) {
16112                 states_cnt++;
16113                 if (sl->state.insn_idx != insn_idx)
16114                         goto next;
16115
16116                 if (sl->state.branches) {
16117                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16118
16119                         if (frame->in_async_callback_fn &&
16120                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16121                                 /* Different async_entry_cnt means that the verifier is
16122                                  * processing another entry into async callback.
16123                                  * Seeing the same state is not an indication of infinite
16124                                  * loop or infinite recursion.
16125                                  * But finding the same state doesn't mean that it's safe
16126                                  * to stop processing the current state. The previous state
16127                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16128                                  * Checking in_async_callback_fn alone is not enough either.
16129                                  * Since the verifier still needs to catch infinite loops
16130                                  * inside async callbacks.
16131                                  */
16132                                 goto skip_inf_loop_check;
16133                         }
16134                         /* BPF open-coded iterators loop detection is special.
16135                          * states_maybe_looping() logic is too simplistic in detecting
16136                          * states that *might* be equivalent, because it doesn't know
16137                          * about ID remapping, so don't even perform it.
16138                          * See process_iter_next_call() and iter_active_depths_differ()
16139                          * for overview of the logic. When current and one of parent
16140                          * states are detected as equivalent, it's a good thing: we prove
16141                          * convergence and can stop simulating further iterations.
16142                          * It's safe to assume that iterator loop will finish, taking into
16143                          * account iter_next() contract of eventually returning
16144                          * sticky NULL result.
16145                          */
16146                         if (is_iter_next_insn(env, insn_idx)) {
16147                                 if (states_equal(env, &sl->state, cur)) {
16148                                         struct bpf_func_state *cur_frame;
16149                                         struct bpf_reg_state *iter_state, *iter_reg;
16150                                         int spi;
16151
16152                                         cur_frame = cur->frame[cur->curframe];
16153                                         /* btf_check_iter_kfuncs() enforces that
16154                                          * iter state pointer is always the first arg
16155                                          */
16156                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16157                                         /* current state is valid due to states_equal(),
16158                                          * so we can assume valid iter and reg state,
16159                                          * no need for extra (re-)validations
16160                                          */
16161                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16162                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16163                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16164                                                 goto hit;
16165                                 }
16166                                 goto skip_inf_loop_check;
16167                         }
16168                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16169                         if (states_maybe_looping(&sl->state, cur) &&
16170                             states_equal(env, &sl->state, cur) &&
16171                             !iter_active_depths_differ(&sl->state, cur)) {
16172                                 verbose_linfo(env, insn_idx, "; ");
16173                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16174                                 return -EINVAL;
16175                         }
16176                         /* if the verifier is processing a loop, avoid adding new state
16177                          * too often, since different loop iterations have distinct
16178                          * states and may not help future pruning.
16179                          * This threshold shouldn't be too low to make sure that
16180                          * a loop with large bound will be rejected quickly.
16181                          * The most abusive loop will be:
16182                          * r1 += 1
16183                          * if r1 < 1000000 goto pc-2
16184                          * 1M insn_procssed limit / 100 == 10k peak states.
16185                          * This threshold shouldn't be too high either, since states
16186                          * at the end of the loop are likely to be useful in pruning.
16187                          */
16188 skip_inf_loop_check:
16189                         if (!force_new_state &&
16190                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16191                             env->insn_processed - env->prev_insn_processed < 100)
16192                                 add_new_state = false;
16193                         goto miss;
16194                 }
16195                 if (states_equal(env, &sl->state, cur)) {
16196 hit:
16197                         sl->hit_cnt++;
16198                         /* reached equivalent register/stack state,
16199                          * prune the search.
16200                          * Registers read by the continuation are read by us.
16201                          * If we have any write marks in env->cur_state, they
16202                          * will prevent corresponding reads in the continuation
16203                          * from reaching our parent (an explored_state).  Our
16204                          * own state will get the read marks recorded, but
16205                          * they'll be immediately forgotten as we're pruning
16206                          * this state and will pop a new one.
16207                          */
16208                         err = propagate_liveness(env, &sl->state, cur);
16209
16210                         /* if previous state reached the exit with precision and
16211                          * current state is equivalent to it (except precsion marks)
16212                          * the precision needs to be propagated back in
16213                          * the current state.
16214                          */
16215                         err = err ? : push_jmp_history(env, cur);
16216                         err = err ? : propagate_precision(env, &sl->state);
16217                         if (err)
16218                                 return err;
16219                         return 1;
16220                 }
16221 miss:
16222                 /* when new state is not going to be added do not increase miss count.
16223                  * Otherwise several loop iterations will remove the state
16224                  * recorded earlier. The goal of these heuristics is to have
16225                  * states from some iterations of the loop (some in the beginning
16226                  * and some at the end) to help pruning.
16227                  */
16228                 if (add_new_state)
16229                         sl->miss_cnt++;
16230                 /* heuristic to determine whether this state is beneficial
16231                  * to keep checking from state equivalence point of view.
16232                  * Higher numbers increase max_states_per_insn and verification time,
16233                  * but do not meaningfully decrease insn_processed.
16234                  */
16235                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16236                         /* the state is unlikely to be useful. Remove it to
16237                          * speed up verification
16238                          */
16239                         *pprev = sl->next;
16240                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16241                                 u32 br = sl->state.branches;
16242
16243                                 WARN_ONCE(br,
16244                                           "BUG live_done but branches_to_explore %d\n",
16245                                           br);
16246                                 free_verifier_state(&sl->state, false);
16247                                 kfree(sl);
16248                                 env->peak_states--;
16249                         } else {
16250                                 /* cannot free this state, since parentage chain may
16251                                  * walk it later. Add it for free_list instead to
16252                                  * be freed at the end of verification
16253                                  */
16254                                 sl->next = env->free_list;
16255                                 env->free_list = sl;
16256                         }
16257                         sl = *pprev;
16258                         continue;
16259                 }
16260 next:
16261                 pprev = &sl->next;
16262                 sl = *pprev;
16263         }
16264
16265         if (env->max_states_per_insn < states_cnt)
16266                 env->max_states_per_insn = states_cnt;
16267
16268         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16269                 return 0;
16270
16271         if (!add_new_state)
16272                 return 0;
16273
16274         /* There were no equivalent states, remember the current one.
16275          * Technically the current state is not proven to be safe yet,
16276          * but it will either reach outer most bpf_exit (which means it's safe)
16277          * or it will be rejected. When there are no loops the verifier won't be
16278          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16279          * again on the way to bpf_exit.
16280          * When looping the sl->state.branches will be > 0 and this state
16281          * will not be considered for equivalence until branches == 0.
16282          */
16283         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16284         if (!new_sl)
16285                 return -ENOMEM;
16286         env->total_states++;
16287         env->peak_states++;
16288         env->prev_jmps_processed = env->jmps_processed;
16289         env->prev_insn_processed = env->insn_processed;
16290
16291         /* forget precise markings we inherited, see __mark_chain_precision */
16292         if (env->bpf_capable)
16293                 mark_all_scalars_imprecise(env, cur);
16294
16295         /* add new state to the head of linked list */
16296         new = &new_sl->state;
16297         err = copy_verifier_state(new, cur);
16298         if (err) {
16299                 free_verifier_state(new, false);
16300                 kfree(new_sl);
16301                 return err;
16302         }
16303         new->insn_idx = insn_idx;
16304         WARN_ONCE(new->branches != 1,
16305                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16306
16307         cur->parent = new;
16308         cur->first_insn_idx = insn_idx;
16309         clear_jmp_history(cur);
16310         new_sl->next = *explored_state(env, insn_idx);
16311         *explored_state(env, insn_idx) = new_sl;
16312         /* connect new state to parentage chain. Current frame needs all
16313          * registers connected. Only r6 - r9 of the callers are alive (pushed
16314          * to the stack implicitly by JITs) so in callers' frames connect just
16315          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16316          * the state of the call instruction (with WRITTEN set), and r0 comes
16317          * from callee with its full parentage chain, anyway.
16318          */
16319         /* clear write marks in current state: the writes we did are not writes
16320          * our child did, so they don't screen off its reads from us.
16321          * (There are no read marks in current state, because reads always mark
16322          * their parent and current state never has children yet.  Only
16323          * explored_states can get read marks.)
16324          */
16325         for (j = 0; j <= cur->curframe; j++) {
16326                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16327                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16328                 for (i = 0; i < BPF_REG_FP; i++)
16329                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16330         }
16331
16332         /* all stack frames are accessible from callee, clear them all */
16333         for (j = 0; j <= cur->curframe; j++) {
16334                 struct bpf_func_state *frame = cur->frame[j];
16335                 struct bpf_func_state *newframe = new->frame[j];
16336
16337                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16338                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16339                         frame->stack[i].spilled_ptr.parent =
16340                                                 &newframe->stack[i].spilled_ptr;
16341                 }
16342         }
16343         return 0;
16344 }
16345
16346 /* Return true if it's OK to have the same insn return a different type. */
16347 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16348 {
16349         switch (base_type(type)) {
16350         case PTR_TO_CTX:
16351         case PTR_TO_SOCKET:
16352         case PTR_TO_SOCK_COMMON:
16353         case PTR_TO_TCP_SOCK:
16354         case PTR_TO_XDP_SOCK:
16355         case PTR_TO_BTF_ID:
16356                 return false;
16357         default:
16358                 return true;
16359         }
16360 }
16361
16362 /* If an instruction was previously used with particular pointer types, then we
16363  * need to be careful to avoid cases such as the below, where it may be ok
16364  * for one branch accessing the pointer, but not ok for the other branch:
16365  *
16366  * R1 = sock_ptr
16367  * goto X;
16368  * ...
16369  * R1 = some_other_valid_ptr;
16370  * goto X;
16371  * ...
16372  * R2 = *(u32 *)(R1 + 0);
16373  */
16374 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16375 {
16376         return src != prev && (!reg_type_mismatch_ok(src) ||
16377                                !reg_type_mismatch_ok(prev));
16378 }
16379
16380 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16381                              bool allow_trust_missmatch)
16382 {
16383         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16384
16385         if (*prev_type == NOT_INIT) {
16386                 /* Saw a valid insn
16387                  * dst_reg = *(u32 *)(src_reg + off)
16388                  * save type to validate intersecting paths
16389                  */
16390                 *prev_type = type;
16391         } else if (reg_type_mismatch(type, *prev_type)) {
16392                 /* Abuser program is trying to use the same insn
16393                  * dst_reg = *(u32*) (src_reg + off)
16394                  * with different pointer types:
16395                  * src_reg == ctx in one branch and
16396                  * src_reg == stack|map in some other branch.
16397                  * Reject it.
16398                  */
16399                 if (allow_trust_missmatch &&
16400                     base_type(type) == PTR_TO_BTF_ID &&
16401                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16402                         /*
16403                          * Have to support a use case when one path through
16404                          * the program yields TRUSTED pointer while another
16405                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16406                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16407                          */
16408                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16409                 } else {
16410                         verbose(env, "same insn cannot be used with different pointers\n");
16411                         return -EINVAL;
16412                 }
16413         }
16414
16415         return 0;
16416 }
16417
16418 static int do_check(struct bpf_verifier_env *env)
16419 {
16420         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16421         struct bpf_verifier_state *state = env->cur_state;
16422         struct bpf_insn *insns = env->prog->insnsi;
16423         struct bpf_reg_state *regs;
16424         int insn_cnt = env->prog->len;
16425         bool do_print_state = false;
16426         int prev_insn_idx = -1;
16427
16428         for (;;) {
16429                 struct bpf_insn *insn;
16430                 u8 class;
16431                 int err;
16432
16433                 env->prev_insn_idx = prev_insn_idx;
16434                 if (env->insn_idx >= insn_cnt) {
16435                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16436                                 env->insn_idx, insn_cnt);
16437                         return -EFAULT;
16438                 }
16439
16440                 insn = &insns[env->insn_idx];
16441                 class = BPF_CLASS(insn->code);
16442
16443                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16444                         verbose(env,
16445                                 "BPF program is too large. Processed %d insn\n",
16446                                 env->insn_processed);
16447                         return -E2BIG;
16448                 }
16449
16450                 state->last_insn_idx = env->prev_insn_idx;
16451
16452                 if (is_prune_point(env, env->insn_idx)) {
16453                         err = is_state_visited(env, env->insn_idx);
16454                         if (err < 0)
16455                                 return err;
16456                         if (err == 1) {
16457                                 /* found equivalent state, can prune the search */
16458                                 if (env->log.level & BPF_LOG_LEVEL) {
16459                                         if (do_print_state)
16460                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16461                                                         env->prev_insn_idx, env->insn_idx,
16462                                                         env->cur_state->speculative ?
16463                                                         " (speculative execution)" : "");
16464                                         else
16465                                                 verbose(env, "%d: safe\n", env->insn_idx);
16466                                 }
16467                                 goto process_bpf_exit;
16468                         }
16469                 }
16470
16471                 if (is_jmp_point(env, env->insn_idx)) {
16472                         err = push_jmp_history(env, state);
16473                         if (err)
16474                                 return err;
16475                 }
16476
16477                 if (signal_pending(current))
16478                         return -EAGAIN;
16479
16480                 if (need_resched())
16481                         cond_resched();
16482
16483                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16484                         verbose(env, "\nfrom %d to %d%s:",
16485                                 env->prev_insn_idx, env->insn_idx,
16486                                 env->cur_state->speculative ?
16487                                 " (speculative execution)" : "");
16488                         print_verifier_state(env, state->frame[state->curframe], true);
16489                         do_print_state = false;
16490                 }
16491
16492                 if (env->log.level & BPF_LOG_LEVEL) {
16493                         const struct bpf_insn_cbs cbs = {
16494                                 .cb_call        = disasm_kfunc_name,
16495                                 .cb_print       = verbose,
16496                                 .private_data   = env,
16497                         };
16498
16499                         if (verifier_state_scratched(env))
16500                                 print_insn_state(env, state->frame[state->curframe]);
16501
16502                         verbose_linfo(env, env->insn_idx, "; ");
16503                         env->prev_log_pos = env->log.end_pos;
16504                         verbose(env, "%d: ", env->insn_idx);
16505                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16506                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16507                         env->prev_log_pos = env->log.end_pos;
16508                 }
16509
16510                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16511                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16512                                                            env->prev_insn_idx);
16513                         if (err)
16514                                 return err;
16515                 }
16516
16517                 regs = cur_regs(env);
16518                 sanitize_mark_insn_seen(env);
16519                 prev_insn_idx = env->insn_idx;
16520
16521                 if (class == BPF_ALU || class == BPF_ALU64) {
16522                         err = check_alu_op(env, insn);
16523                         if (err)
16524                                 return err;
16525
16526                 } else if (class == BPF_LDX) {
16527                         enum bpf_reg_type src_reg_type;
16528
16529                         /* check for reserved fields is already done */
16530
16531                         /* check src operand */
16532                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16533                         if (err)
16534                                 return err;
16535
16536                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16537                         if (err)
16538                                 return err;
16539
16540                         src_reg_type = regs[insn->src_reg].type;
16541
16542                         /* check that memory (src_reg + off) is readable,
16543                          * the state of dst_reg will be updated by this func
16544                          */
16545                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16546                                                insn->off, BPF_SIZE(insn->code),
16547                                                BPF_READ, insn->dst_reg, false,
16548                                                BPF_MODE(insn->code) == BPF_MEMSX);
16549                         if (err)
16550                                 return err;
16551
16552                         err = save_aux_ptr_type(env, src_reg_type, true);
16553                         if (err)
16554                                 return err;
16555                 } else if (class == BPF_STX) {
16556                         enum bpf_reg_type dst_reg_type;
16557
16558                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16559                                 err = check_atomic(env, env->insn_idx, insn);
16560                                 if (err)
16561                                         return err;
16562                                 env->insn_idx++;
16563                                 continue;
16564                         }
16565
16566                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16567                                 verbose(env, "BPF_STX uses reserved fields\n");
16568                                 return -EINVAL;
16569                         }
16570
16571                         /* check src1 operand */
16572                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16573                         if (err)
16574                                 return err;
16575                         /* check src2 operand */
16576                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16577                         if (err)
16578                                 return err;
16579
16580                         dst_reg_type = regs[insn->dst_reg].type;
16581
16582                         /* check that memory (dst_reg + off) is writeable */
16583                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16584                                                insn->off, BPF_SIZE(insn->code),
16585                                                BPF_WRITE, insn->src_reg, false, false);
16586                         if (err)
16587                                 return err;
16588
16589                         err = save_aux_ptr_type(env, dst_reg_type, false);
16590                         if (err)
16591                                 return err;
16592                 } else if (class == BPF_ST) {
16593                         enum bpf_reg_type dst_reg_type;
16594
16595                         if (BPF_MODE(insn->code) != BPF_MEM ||
16596                             insn->src_reg != BPF_REG_0) {
16597                                 verbose(env, "BPF_ST uses reserved fields\n");
16598                                 return -EINVAL;
16599                         }
16600                         /* check src operand */
16601                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16602                         if (err)
16603                                 return err;
16604
16605                         dst_reg_type = regs[insn->dst_reg].type;
16606
16607                         /* check that memory (dst_reg + off) is writeable */
16608                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16609                                                insn->off, BPF_SIZE(insn->code),
16610                                                BPF_WRITE, -1, false, false);
16611                         if (err)
16612                                 return err;
16613
16614                         err = save_aux_ptr_type(env, dst_reg_type, false);
16615                         if (err)
16616                                 return err;
16617                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16618                         u8 opcode = BPF_OP(insn->code);
16619
16620                         env->jmps_processed++;
16621                         if (opcode == BPF_CALL) {
16622                                 if (BPF_SRC(insn->code) != BPF_K ||
16623                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16624                                      && insn->off != 0) ||
16625                                     (insn->src_reg != BPF_REG_0 &&
16626                                      insn->src_reg != BPF_PSEUDO_CALL &&
16627                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16628                                     insn->dst_reg != BPF_REG_0 ||
16629                                     class == BPF_JMP32) {
16630                                         verbose(env, "BPF_CALL uses reserved fields\n");
16631                                         return -EINVAL;
16632                                 }
16633
16634                                 if (env->cur_state->active_lock.ptr) {
16635                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16636                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16637                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16638                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16639                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16640                                                 return -EINVAL;
16641                                         }
16642                                 }
16643                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16644                                         err = check_func_call(env, insn, &env->insn_idx);
16645                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16646                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16647                                 else
16648                                         err = check_helper_call(env, insn, &env->insn_idx);
16649                                 if (err)
16650                                         return err;
16651
16652                                 mark_reg_scratched(env, BPF_REG_0);
16653                         } else if (opcode == BPF_JA) {
16654                                 if (BPF_SRC(insn->code) != BPF_K ||
16655                                     insn->src_reg != BPF_REG_0 ||
16656                                     insn->dst_reg != BPF_REG_0 ||
16657                                     (class == BPF_JMP && insn->imm != 0) ||
16658                                     (class == BPF_JMP32 && insn->off != 0)) {
16659                                         verbose(env, "BPF_JA uses reserved fields\n");
16660                                         return -EINVAL;
16661                                 }
16662
16663                                 if (class == BPF_JMP)
16664                                         env->insn_idx += insn->off + 1;
16665                                 else
16666                                         env->insn_idx += insn->imm + 1;
16667                                 continue;
16668
16669                         } else if (opcode == BPF_EXIT) {
16670                                 if (BPF_SRC(insn->code) != BPF_K ||
16671                                     insn->imm != 0 ||
16672                                     insn->src_reg != BPF_REG_0 ||
16673                                     insn->dst_reg != BPF_REG_0 ||
16674                                     class == BPF_JMP32) {
16675                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16676                                         return -EINVAL;
16677                                 }
16678
16679                                 if (env->cur_state->active_lock.ptr &&
16680                                     !in_rbtree_lock_required_cb(env)) {
16681                                         verbose(env, "bpf_spin_unlock is missing\n");
16682                                         return -EINVAL;
16683                                 }
16684
16685                                 if (env->cur_state->active_rcu_lock) {
16686                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16687                                         return -EINVAL;
16688                                 }
16689
16690                                 /* We must do check_reference_leak here before
16691                                  * prepare_func_exit to handle the case when
16692                                  * state->curframe > 0, it may be a callback
16693                                  * function, for which reference_state must
16694                                  * match caller reference state when it exits.
16695                                  */
16696                                 err = check_reference_leak(env);
16697                                 if (err)
16698                                         return err;
16699
16700                                 if (state->curframe) {
16701                                         /* exit from nested function */
16702                                         err = prepare_func_exit(env, &env->insn_idx);
16703                                         if (err)
16704                                                 return err;
16705                                         do_print_state = true;
16706                                         continue;
16707                                 }
16708
16709                                 err = check_return_code(env);
16710                                 if (err)
16711                                         return err;
16712 process_bpf_exit:
16713                                 mark_verifier_state_scratched(env);
16714                                 update_branch_counts(env, env->cur_state);
16715                                 err = pop_stack(env, &prev_insn_idx,
16716                                                 &env->insn_idx, pop_log);
16717                                 if (err < 0) {
16718                                         if (err != -ENOENT)
16719                                                 return err;
16720                                         break;
16721                                 } else {
16722                                         do_print_state = true;
16723                                         continue;
16724                                 }
16725                         } else {
16726                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16727                                 if (err)
16728                                         return err;
16729                         }
16730                 } else if (class == BPF_LD) {
16731                         u8 mode = BPF_MODE(insn->code);
16732
16733                         if (mode == BPF_ABS || mode == BPF_IND) {
16734                                 err = check_ld_abs(env, insn);
16735                                 if (err)
16736                                         return err;
16737
16738                         } else if (mode == BPF_IMM) {
16739                                 err = check_ld_imm(env, insn);
16740                                 if (err)
16741                                         return err;
16742
16743                                 env->insn_idx++;
16744                                 sanitize_mark_insn_seen(env);
16745                         } else {
16746                                 verbose(env, "invalid BPF_LD mode\n");
16747                                 return -EINVAL;
16748                         }
16749                 } else {
16750                         verbose(env, "unknown insn class %d\n", class);
16751                         return -EINVAL;
16752                 }
16753
16754                 env->insn_idx++;
16755         }
16756
16757         return 0;
16758 }
16759
16760 static int find_btf_percpu_datasec(struct btf *btf)
16761 {
16762         const struct btf_type *t;
16763         const char *tname;
16764         int i, n;
16765
16766         /*
16767          * Both vmlinux and module each have their own ".data..percpu"
16768          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16769          * types to look at only module's own BTF types.
16770          */
16771         n = btf_nr_types(btf);
16772         if (btf_is_module(btf))
16773                 i = btf_nr_types(btf_vmlinux);
16774         else
16775                 i = 1;
16776
16777         for(; i < n; i++) {
16778                 t = btf_type_by_id(btf, i);
16779                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16780                         continue;
16781
16782                 tname = btf_name_by_offset(btf, t->name_off);
16783                 if (!strcmp(tname, ".data..percpu"))
16784                         return i;
16785         }
16786
16787         return -ENOENT;
16788 }
16789
16790 /* replace pseudo btf_id with kernel symbol address */
16791 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16792                                struct bpf_insn *insn,
16793                                struct bpf_insn_aux_data *aux)
16794 {
16795         const struct btf_var_secinfo *vsi;
16796         const struct btf_type *datasec;
16797         struct btf_mod_pair *btf_mod;
16798         const struct btf_type *t;
16799         const char *sym_name;
16800         bool percpu = false;
16801         u32 type, id = insn->imm;
16802         struct btf *btf;
16803         s32 datasec_id;
16804         u64 addr;
16805         int i, btf_fd, err;
16806
16807         btf_fd = insn[1].imm;
16808         if (btf_fd) {
16809                 btf = btf_get_by_fd(btf_fd);
16810                 if (IS_ERR(btf)) {
16811                         verbose(env, "invalid module BTF object FD specified.\n");
16812                         return -EINVAL;
16813                 }
16814         } else {
16815                 if (!btf_vmlinux) {
16816                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16817                         return -EINVAL;
16818                 }
16819                 btf = btf_vmlinux;
16820                 btf_get(btf);
16821         }
16822
16823         t = btf_type_by_id(btf, id);
16824         if (!t) {
16825                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16826                 err = -ENOENT;
16827                 goto err_put;
16828         }
16829
16830         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16831                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16832                 err = -EINVAL;
16833                 goto err_put;
16834         }
16835
16836         sym_name = btf_name_by_offset(btf, t->name_off);
16837         addr = kallsyms_lookup_name(sym_name);
16838         if (!addr) {
16839                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16840                         sym_name);
16841                 err = -ENOENT;
16842                 goto err_put;
16843         }
16844         insn[0].imm = (u32)addr;
16845         insn[1].imm = addr >> 32;
16846
16847         if (btf_type_is_func(t)) {
16848                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16849                 aux->btf_var.mem_size = 0;
16850                 goto check_btf;
16851         }
16852
16853         datasec_id = find_btf_percpu_datasec(btf);
16854         if (datasec_id > 0) {
16855                 datasec = btf_type_by_id(btf, datasec_id);
16856                 for_each_vsi(i, datasec, vsi) {
16857                         if (vsi->type == id) {
16858                                 percpu = true;
16859                                 break;
16860                         }
16861                 }
16862         }
16863
16864         type = t->type;
16865         t = btf_type_skip_modifiers(btf, type, NULL);
16866         if (percpu) {
16867                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16868                 aux->btf_var.btf = btf;
16869                 aux->btf_var.btf_id = type;
16870         } else if (!btf_type_is_struct(t)) {
16871                 const struct btf_type *ret;
16872                 const char *tname;
16873                 u32 tsize;
16874
16875                 /* resolve the type size of ksym. */
16876                 ret = btf_resolve_size(btf, t, &tsize);
16877                 if (IS_ERR(ret)) {
16878                         tname = btf_name_by_offset(btf, t->name_off);
16879                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16880                                 tname, PTR_ERR(ret));
16881                         err = -EINVAL;
16882                         goto err_put;
16883                 }
16884                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16885                 aux->btf_var.mem_size = tsize;
16886         } else {
16887                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16888                 aux->btf_var.btf = btf;
16889                 aux->btf_var.btf_id = type;
16890         }
16891 check_btf:
16892         /* check whether we recorded this BTF (and maybe module) already */
16893         for (i = 0; i < env->used_btf_cnt; i++) {
16894                 if (env->used_btfs[i].btf == btf) {
16895                         btf_put(btf);
16896                         return 0;
16897                 }
16898         }
16899
16900         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16901                 err = -E2BIG;
16902                 goto err_put;
16903         }
16904
16905         btf_mod = &env->used_btfs[env->used_btf_cnt];
16906         btf_mod->btf = btf;
16907         btf_mod->module = NULL;
16908
16909         /* if we reference variables from kernel module, bump its refcount */
16910         if (btf_is_module(btf)) {
16911                 btf_mod->module = btf_try_get_module(btf);
16912                 if (!btf_mod->module) {
16913                         err = -ENXIO;
16914                         goto err_put;
16915                 }
16916         }
16917
16918         env->used_btf_cnt++;
16919
16920         return 0;
16921 err_put:
16922         btf_put(btf);
16923         return err;
16924 }
16925
16926 static bool is_tracing_prog_type(enum bpf_prog_type type)
16927 {
16928         switch (type) {
16929         case BPF_PROG_TYPE_KPROBE:
16930         case BPF_PROG_TYPE_TRACEPOINT:
16931         case BPF_PROG_TYPE_PERF_EVENT:
16932         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16933         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16934                 return true;
16935         default:
16936                 return false;
16937         }
16938 }
16939
16940 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16941                                         struct bpf_map *map,
16942                                         struct bpf_prog *prog)
16943
16944 {
16945         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16946
16947         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16948             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16949                 if (is_tracing_prog_type(prog_type)) {
16950                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16951                         return -EINVAL;
16952                 }
16953         }
16954
16955         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16956                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16957                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16958                         return -EINVAL;
16959                 }
16960
16961                 if (is_tracing_prog_type(prog_type)) {
16962                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16963                         return -EINVAL;
16964                 }
16965
16966                 if (prog->aux->sleepable) {
16967                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16968                         return -EINVAL;
16969                 }
16970         }
16971
16972         if (btf_record_has_field(map->record, BPF_TIMER)) {
16973                 if (is_tracing_prog_type(prog_type)) {
16974                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
16975                         return -EINVAL;
16976                 }
16977         }
16978
16979         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16980             !bpf_offload_prog_map_match(prog, map)) {
16981                 verbose(env, "offload device mismatch between prog and map\n");
16982                 return -EINVAL;
16983         }
16984
16985         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16986                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16987                 return -EINVAL;
16988         }
16989
16990         if (prog->aux->sleepable)
16991                 switch (map->map_type) {
16992                 case BPF_MAP_TYPE_HASH:
16993                 case BPF_MAP_TYPE_LRU_HASH:
16994                 case BPF_MAP_TYPE_ARRAY:
16995                 case BPF_MAP_TYPE_PERCPU_HASH:
16996                 case BPF_MAP_TYPE_PERCPU_ARRAY:
16997                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16998                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16999                 case BPF_MAP_TYPE_HASH_OF_MAPS:
17000                 case BPF_MAP_TYPE_RINGBUF:
17001                 case BPF_MAP_TYPE_USER_RINGBUF:
17002                 case BPF_MAP_TYPE_INODE_STORAGE:
17003                 case BPF_MAP_TYPE_SK_STORAGE:
17004                 case BPF_MAP_TYPE_TASK_STORAGE:
17005                 case BPF_MAP_TYPE_CGRP_STORAGE:
17006                         break;
17007                 default:
17008                         verbose(env,
17009                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17010                         return -EINVAL;
17011                 }
17012
17013         return 0;
17014 }
17015
17016 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17017 {
17018         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17019                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17020 }
17021
17022 /* find and rewrite pseudo imm in ld_imm64 instructions:
17023  *
17024  * 1. if it accesses map FD, replace it with actual map pointer.
17025  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17026  *
17027  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17028  */
17029 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17030 {
17031         struct bpf_insn *insn = env->prog->insnsi;
17032         int insn_cnt = env->prog->len;
17033         int i, j, err;
17034
17035         err = bpf_prog_calc_tag(env->prog);
17036         if (err)
17037                 return err;
17038
17039         for (i = 0; i < insn_cnt; i++, insn++) {
17040                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17041                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17042                     insn->imm != 0)) {
17043                         verbose(env, "BPF_LDX uses reserved fields\n");
17044                         return -EINVAL;
17045                 }
17046
17047                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17048                         struct bpf_insn_aux_data *aux;
17049                         struct bpf_map *map;
17050                         struct fd f;
17051                         u64 addr;
17052                         u32 fd;
17053
17054                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17055                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17056                             insn[1].off != 0) {
17057                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17058                                 return -EINVAL;
17059                         }
17060
17061                         if (insn[0].src_reg == 0)
17062                                 /* valid generic load 64-bit imm */
17063                                 goto next_insn;
17064
17065                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17066                                 aux = &env->insn_aux_data[i];
17067                                 err = check_pseudo_btf_id(env, insn, aux);
17068                                 if (err)
17069                                         return err;
17070                                 goto next_insn;
17071                         }
17072
17073                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17074                                 aux = &env->insn_aux_data[i];
17075                                 aux->ptr_type = PTR_TO_FUNC;
17076                                 goto next_insn;
17077                         }
17078
17079                         /* In final convert_pseudo_ld_imm64() step, this is
17080                          * converted into regular 64-bit imm load insn.
17081                          */
17082                         switch (insn[0].src_reg) {
17083                         case BPF_PSEUDO_MAP_VALUE:
17084                         case BPF_PSEUDO_MAP_IDX_VALUE:
17085                                 break;
17086                         case BPF_PSEUDO_MAP_FD:
17087                         case BPF_PSEUDO_MAP_IDX:
17088                                 if (insn[1].imm == 0)
17089                                         break;
17090                                 fallthrough;
17091                         default:
17092                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17093                                 return -EINVAL;
17094                         }
17095
17096                         switch (insn[0].src_reg) {
17097                         case BPF_PSEUDO_MAP_IDX_VALUE:
17098                         case BPF_PSEUDO_MAP_IDX:
17099                                 if (bpfptr_is_null(env->fd_array)) {
17100                                         verbose(env, "fd_idx without fd_array is invalid\n");
17101                                         return -EPROTO;
17102                                 }
17103                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17104                                                             insn[0].imm * sizeof(fd),
17105                                                             sizeof(fd)))
17106                                         return -EFAULT;
17107                                 break;
17108                         default:
17109                                 fd = insn[0].imm;
17110                                 break;
17111                         }
17112
17113                         f = fdget(fd);
17114                         map = __bpf_map_get(f);
17115                         if (IS_ERR(map)) {
17116                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17117                                         insn[0].imm);
17118                                 return PTR_ERR(map);
17119                         }
17120
17121                         err = check_map_prog_compatibility(env, map, env->prog);
17122                         if (err) {
17123                                 fdput(f);
17124                                 return err;
17125                         }
17126
17127                         aux = &env->insn_aux_data[i];
17128                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17129                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17130                                 addr = (unsigned long)map;
17131                         } else {
17132                                 u32 off = insn[1].imm;
17133
17134                                 if (off >= BPF_MAX_VAR_OFF) {
17135                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17136                                         fdput(f);
17137                                         return -EINVAL;
17138                                 }
17139
17140                                 if (!map->ops->map_direct_value_addr) {
17141                                         verbose(env, "no direct value access support for this map type\n");
17142                                         fdput(f);
17143                                         return -EINVAL;
17144                                 }
17145
17146                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17147                                 if (err) {
17148                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17149                                                 map->value_size, off);
17150                                         fdput(f);
17151                                         return err;
17152                                 }
17153
17154                                 aux->map_off = off;
17155                                 addr += off;
17156                         }
17157
17158                         insn[0].imm = (u32)addr;
17159                         insn[1].imm = addr >> 32;
17160
17161                         /* check whether we recorded this map already */
17162                         for (j = 0; j < env->used_map_cnt; j++) {
17163                                 if (env->used_maps[j] == map) {
17164                                         aux->map_index = j;
17165                                         fdput(f);
17166                                         goto next_insn;
17167                                 }
17168                         }
17169
17170                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17171                                 fdput(f);
17172                                 return -E2BIG;
17173                         }
17174
17175                         /* hold the map. If the program is rejected by verifier,
17176                          * the map will be released by release_maps() or it
17177                          * will be used by the valid program until it's unloaded
17178                          * and all maps are released in free_used_maps()
17179                          */
17180                         bpf_map_inc(map);
17181
17182                         aux->map_index = env->used_map_cnt;
17183                         env->used_maps[env->used_map_cnt++] = map;
17184
17185                         if (bpf_map_is_cgroup_storage(map) &&
17186                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
17187                                 verbose(env, "only one cgroup storage of each type is allowed\n");
17188                                 fdput(f);
17189                                 return -EBUSY;
17190                         }
17191
17192                         fdput(f);
17193 next_insn:
17194                         insn++;
17195                         i++;
17196                         continue;
17197                 }
17198
17199                 /* Basic sanity check before we invest more work here. */
17200                 if (!bpf_opcode_in_insntable(insn->code)) {
17201                         verbose(env, "unknown opcode %02x\n", insn->code);
17202                         return -EINVAL;
17203                 }
17204         }
17205
17206         /* now all pseudo BPF_LD_IMM64 instructions load valid
17207          * 'struct bpf_map *' into a register instead of user map_fd.
17208          * These pointers will be used later by verifier to validate map access.
17209          */
17210         return 0;
17211 }
17212
17213 /* drop refcnt of maps used by the rejected program */
17214 static void release_maps(struct bpf_verifier_env *env)
17215 {
17216         __bpf_free_used_maps(env->prog->aux, env->used_maps,
17217                              env->used_map_cnt);
17218 }
17219
17220 /* drop refcnt of maps used by the rejected program */
17221 static void release_btfs(struct bpf_verifier_env *env)
17222 {
17223         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17224                              env->used_btf_cnt);
17225 }
17226
17227 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17228 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17229 {
17230         struct bpf_insn *insn = env->prog->insnsi;
17231         int insn_cnt = env->prog->len;
17232         int i;
17233
17234         for (i = 0; i < insn_cnt; i++, insn++) {
17235                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17236                         continue;
17237                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17238                         continue;
17239                 insn->src_reg = 0;
17240         }
17241 }
17242
17243 /* single env->prog->insni[off] instruction was replaced with the range
17244  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17245  * [0, off) and [off, end) to new locations, so the patched range stays zero
17246  */
17247 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17248                                  struct bpf_insn_aux_data *new_data,
17249                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17250 {
17251         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17252         struct bpf_insn *insn = new_prog->insnsi;
17253         u32 old_seen = old_data[off].seen;
17254         u32 prog_len;
17255         int i;
17256
17257         /* aux info at OFF always needs adjustment, no matter fast path
17258          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17259          * original insn at old prog.
17260          */
17261         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17262
17263         if (cnt == 1)
17264                 return;
17265         prog_len = new_prog->len;
17266
17267         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17268         memcpy(new_data + off + cnt - 1, old_data + off,
17269                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17270         for (i = off; i < off + cnt - 1; i++) {
17271                 /* Expand insni[off]'s seen count to the patched range. */
17272                 new_data[i].seen = old_seen;
17273                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17274         }
17275         env->insn_aux_data = new_data;
17276         vfree(old_data);
17277 }
17278
17279 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17280 {
17281         int i;
17282
17283         if (len == 1)
17284                 return;
17285         /* NOTE: fake 'exit' subprog should be updated as well. */
17286         for (i = 0; i <= env->subprog_cnt; i++) {
17287                 if (env->subprog_info[i].start <= off)
17288                         continue;
17289                 env->subprog_info[i].start += len - 1;
17290         }
17291 }
17292
17293 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17294 {
17295         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17296         int i, sz = prog->aux->size_poke_tab;
17297         struct bpf_jit_poke_descriptor *desc;
17298
17299         for (i = 0; i < sz; i++) {
17300                 desc = &tab[i];
17301                 if (desc->insn_idx <= off)
17302                         continue;
17303                 desc->insn_idx += len - 1;
17304         }
17305 }
17306
17307 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17308                                             const struct bpf_insn *patch, u32 len)
17309 {
17310         struct bpf_prog *new_prog;
17311         struct bpf_insn_aux_data *new_data = NULL;
17312
17313         if (len > 1) {
17314                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17315                                               sizeof(struct bpf_insn_aux_data)));
17316                 if (!new_data)
17317                         return NULL;
17318         }
17319
17320         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17321         if (IS_ERR(new_prog)) {
17322                 if (PTR_ERR(new_prog) == -ERANGE)
17323                         verbose(env,
17324                                 "insn %d cannot be patched due to 16-bit range\n",
17325                                 env->insn_aux_data[off].orig_idx);
17326                 vfree(new_data);
17327                 return NULL;
17328         }
17329         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17330         adjust_subprog_starts(env, off, len);
17331         adjust_poke_descs(new_prog, off, len);
17332         return new_prog;
17333 }
17334
17335 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17336                                               u32 off, u32 cnt)
17337 {
17338         int i, j;
17339
17340         /* find first prog starting at or after off (first to remove) */
17341         for (i = 0; i < env->subprog_cnt; i++)
17342                 if (env->subprog_info[i].start >= off)
17343                         break;
17344         /* find first prog starting at or after off + cnt (first to stay) */
17345         for (j = i; j < env->subprog_cnt; j++)
17346                 if (env->subprog_info[j].start >= off + cnt)
17347                         break;
17348         /* if j doesn't start exactly at off + cnt, we are just removing
17349          * the front of previous prog
17350          */
17351         if (env->subprog_info[j].start != off + cnt)
17352                 j--;
17353
17354         if (j > i) {
17355                 struct bpf_prog_aux *aux = env->prog->aux;
17356                 int move;
17357
17358                 /* move fake 'exit' subprog as well */
17359                 move = env->subprog_cnt + 1 - j;
17360
17361                 memmove(env->subprog_info + i,
17362                         env->subprog_info + j,
17363                         sizeof(*env->subprog_info) * move);
17364                 env->subprog_cnt -= j - i;
17365
17366                 /* remove func_info */
17367                 if (aux->func_info) {
17368                         move = aux->func_info_cnt - j;
17369
17370                         memmove(aux->func_info + i,
17371                                 aux->func_info + j,
17372                                 sizeof(*aux->func_info) * move);
17373                         aux->func_info_cnt -= j - i;
17374                         /* func_info->insn_off is set after all code rewrites,
17375                          * in adjust_btf_func() - no need to adjust
17376                          */
17377                 }
17378         } else {
17379                 /* convert i from "first prog to remove" to "first to adjust" */
17380                 if (env->subprog_info[i].start == off)
17381                         i++;
17382         }
17383
17384         /* update fake 'exit' subprog as well */
17385         for (; i <= env->subprog_cnt; i++)
17386                 env->subprog_info[i].start -= cnt;
17387
17388         return 0;
17389 }
17390
17391 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17392                                       u32 cnt)
17393 {
17394         struct bpf_prog *prog = env->prog;
17395         u32 i, l_off, l_cnt, nr_linfo;
17396         struct bpf_line_info *linfo;
17397
17398         nr_linfo = prog->aux->nr_linfo;
17399         if (!nr_linfo)
17400                 return 0;
17401
17402         linfo = prog->aux->linfo;
17403
17404         /* find first line info to remove, count lines to be removed */
17405         for (i = 0; i < nr_linfo; i++)
17406                 if (linfo[i].insn_off >= off)
17407                         break;
17408
17409         l_off = i;
17410         l_cnt = 0;
17411         for (; i < nr_linfo; i++)
17412                 if (linfo[i].insn_off < off + cnt)
17413                         l_cnt++;
17414                 else
17415                         break;
17416
17417         /* First live insn doesn't match first live linfo, it needs to "inherit"
17418          * last removed linfo.  prog is already modified, so prog->len == off
17419          * means no live instructions after (tail of the program was removed).
17420          */
17421         if (prog->len != off && l_cnt &&
17422             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17423                 l_cnt--;
17424                 linfo[--i].insn_off = off + cnt;
17425         }
17426
17427         /* remove the line info which refer to the removed instructions */
17428         if (l_cnt) {
17429                 memmove(linfo + l_off, linfo + i,
17430                         sizeof(*linfo) * (nr_linfo - i));
17431
17432                 prog->aux->nr_linfo -= l_cnt;
17433                 nr_linfo = prog->aux->nr_linfo;
17434         }
17435
17436         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17437         for (i = l_off; i < nr_linfo; i++)
17438                 linfo[i].insn_off -= cnt;
17439
17440         /* fix up all subprogs (incl. 'exit') which start >= off */
17441         for (i = 0; i <= env->subprog_cnt; i++)
17442                 if (env->subprog_info[i].linfo_idx > l_off) {
17443                         /* program may have started in the removed region but
17444                          * may not be fully removed
17445                          */
17446                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17447                                 env->subprog_info[i].linfo_idx -= l_cnt;
17448                         else
17449                                 env->subprog_info[i].linfo_idx = l_off;
17450                 }
17451
17452         return 0;
17453 }
17454
17455 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17456 {
17457         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17458         unsigned int orig_prog_len = env->prog->len;
17459         int err;
17460
17461         if (bpf_prog_is_offloaded(env->prog->aux))
17462                 bpf_prog_offload_remove_insns(env, off, cnt);
17463
17464         err = bpf_remove_insns(env->prog, off, cnt);
17465         if (err)
17466                 return err;
17467
17468         err = adjust_subprog_starts_after_remove(env, off, cnt);
17469         if (err)
17470                 return err;
17471
17472         err = bpf_adj_linfo_after_remove(env, off, cnt);
17473         if (err)
17474                 return err;
17475
17476         memmove(aux_data + off, aux_data + off + cnt,
17477                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17478
17479         return 0;
17480 }
17481
17482 /* The verifier does more data flow analysis than llvm and will not
17483  * explore branches that are dead at run time. Malicious programs can
17484  * have dead code too. Therefore replace all dead at-run-time code
17485  * with 'ja -1'.
17486  *
17487  * Just nops are not optimal, e.g. if they would sit at the end of the
17488  * program and through another bug we would manage to jump there, then
17489  * we'd execute beyond program memory otherwise. Returning exception
17490  * code also wouldn't work since we can have subprogs where the dead
17491  * code could be located.
17492  */
17493 static void sanitize_dead_code(struct bpf_verifier_env *env)
17494 {
17495         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17496         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17497         struct bpf_insn *insn = env->prog->insnsi;
17498         const int insn_cnt = env->prog->len;
17499         int i;
17500
17501         for (i = 0; i < insn_cnt; i++) {
17502                 if (aux_data[i].seen)
17503                         continue;
17504                 memcpy(insn + i, &trap, sizeof(trap));
17505                 aux_data[i].zext_dst = false;
17506         }
17507 }
17508
17509 static bool insn_is_cond_jump(u8 code)
17510 {
17511         u8 op;
17512
17513         op = BPF_OP(code);
17514         if (BPF_CLASS(code) == BPF_JMP32)
17515                 return op != BPF_JA;
17516
17517         if (BPF_CLASS(code) != BPF_JMP)
17518                 return false;
17519
17520         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17521 }
17522
17523 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17524 {
17525         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17526         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17527         struct bpf_insn *insn = env->prog->insnsi;
17528         const int insn_cnt = env->prog->len;
17529         int i;
17530
17531         for (i = 0; i < insn_cnt; i++, insn++) {
17532                 if (!insn_is_cond_jump(insn->code))
17533                         continue;
17534
17535                 if (!aux_data[i + 1].seen)
17536                         ja.off = insn->off;
17537                 else if (!aux_data[i + 1 + insn->off].seen)
17538                         ja.off = 0;
17539                 else
17540                         continue;
17541
17542                 if (bpf_prog_is_offloaded(env->prog->aux))
17543                         bpf_prog_offload_replace_insn(env, i, &ja);
17544
17545                 memcpy(insn, &ja, sizeof(ja));
17546         }
17547 }
17548
17549 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17550 {
17551         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17552         int insn_cnt = env->prog->len;
17553         int i, err;
17554
17555         for (i = 0; i < insn_cnt; i++) {
17556                 int j;
17557
17558                 j = 0;
17559                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17560                         j++;
17561                 if (!j)
17562                         continue;
17563
17564                 err = verifier_remove_insns(env, i, j);
17565                 if (err)
17566                         return err;
17567                 insn_cnt = env->prog->len;
17568         }
17569
17570         return 0;
17571 }
17572
17573 static int opt_remove_nops(struct bpf_verifier_env *env)
17574 {
17575         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17576         struct bpf_insn *insn = env->prog->insnsi;
17577         int insn_cnt = env->prog->len;
17578         int i, err;
17579
17580         for (i = 0; i < insn_cnt; i++) {
17581                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17582                         continue;
17583
17584                 err = verifier_remove_insns(env, i, 1);
17585                 if (err)
17586                         return err;
17587                 insn_cnt--;
17588                 i--;
17589         }
17590
17591         return 0;
17592 }
17593
17594 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17595                                          const union bpf_attr *attr)
17596 {
17597         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17598         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17599         int i, patch_len, delta = 0, len = env->prog->len;
17600         struct bpf_insn *insns = env->prog->insnsi;
17601         struct bpf_prog *new_prog;
17602         bool rnd_hi32;
17603
17604         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17605         zext_patch[1] = BPF_ZEXT_REG(0);
17606         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17607         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17608         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17609         for (i = 0; i < len; i++) {
17610                 int adj_idx = i + delta;
17611                 struct bpf_insn insn;
17612                 int load_reg;
17613
17614                 insn = insns[adj_idx];
17615                 load_reg = insn_def_regno(&insn);
17616                 if (!aux[adj_idx].zext_dst) {
17617                         u8 code, class;
17618                         u32 imm_rnd;
17619
17620                         if (!rnd_hi32)
17621                                 continue;
17622
17623                         code = insn.code;
17624                         class = BPF_CLASS(code);
17625                         if (load_reg == -1)
17626                                 continue;
17627
17628                         /* NOTE: arg "reg" (the fourth one) is only used for
17629                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17630                          *       here.
17631                          */
17632                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17633                                 if (class == BPF_LD &&
17634                                     BPF_MODE(code) == BPF_IMM)
17635                                         i++;
17636                                 continue;
17637                         }
17638
17639                         /* ctx load could be transformed into wider load. */
17640                         if (class == BPF_LDX &&
17641                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17642                                 continue;
17643
17644                         imm_rnd = get_random_u32();
17645                         rnd_hi32_patch[0] = insn;
17646                         rnd_hi32_patch[1].imm = imm_rnd;
17647                         rnd_hi32_patch[3].dst_reg = load_reg;
17648                         patch = rnd_hi32_patch;
17649                         patch_len = 4;
17650                         goto apply_patch_buffer;
17651                 }
17652
17653                 /* Add in an zero-extend instruction if a) the JIT has requested
17654                  * it or b) it's a CMPXCHG.
17655                  *
17656                  * The latter is because: BPF_CMPXCHG always loads a value into
17657                  * R0, therefore always zero-extends. However some archs'
17658                  * equivalent instruction only does this load when the
17659                  * comparison is successful. This detail of CMPXCHG is
17660                  * orthogonal to the general zero-extension behaviour of the
17661                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17662                  */
17663                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17664                         continue;
17665
17666                 /* Zero-extension is done by the caller. */
17667                 if (bpf_pseudo_kfunc_call(&insn))
17668                         continue;
17669
17670                 if (WARN_ON(load_reg == -1)) {
17671                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17672                         return -EFAULT;
17673                 }
17674
17675                 zext_patch[0] = insn;
17676                 zext_patch[1].dst_reg = load_reg;
17677                 zext_patch[1].src_reg = load_reg;
17678                 patch = zext_patch;
17679                 patch_len = 2;
17680 apply_patch_buffer:
17681                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17682                 if (!new_prog)
17683                         return -ENOMEM;
17684                 env->prog = new_prog;
17685                 insns = new_prog->insnsi;
17686                 aux = env->insn_aux_data;
17687                 delta += patch_len - 1;
17688         }
17689
17690         return 0;
17691 }
17692
17693 /* convert load instructions that access fields of a context type into a
17694  * sequence of instructions that access fields of the underlying structure:
17695  *     struct __sk_buff    -> struct sk_buff
17696  *     struct bpf_sock_ops -> struct sock
17697  */
17698 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17699 {
17700         const struct bpf_verifier_ops *ops = env->ops;
17701         int i, cnt, size, ctx_field_size, delta = 0;
17702         const int insn_cnt = env->prog->len;
17703         struct bpf_insn insn_buf[16], *insn;
17704         u32 target_size, size_default, off;
17705         struct bpf_prog *new_prog;
17706         enum bpf_access_type type;
17707         bool is_narrower_load;
17708
17709         if (ops->gen_prologue || env->seen_direct_write) {
17710                 if (!ops->gen_prologue) {
17711                         verbose(env, "bpf verifier is misconfigured\n");
17712                         return -EINVAL;
17713                 }
17714                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17715                                         env->prog);
17716                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17717                         verbose(env, "bpf verifier is misconfigured\n");
17718                         return -EINVAL;
17719                 } else if (cnt) {
17720                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17721                         if (!new_prog)
17722                                 return -ENOMEM;
17723
17724                         env->prog = new_prog;
17725                         delta += cnt - 1;
17726                 }
17727         }
17728
17729         if (bpf_prog_is_offloaded(env->prog->aux))
17730                 return 0;
17731
17732         insn = env->prog->insnsi + delta;
17733
17734         for (i = 0; i < insn_cnt; i++, insn++) {
17735                 bpf_convert_ctx_access_t convert_ctx_access;
17736                 u8 mode;
17737
17738                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17739                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17740                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17741                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17742                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17743                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17744                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17745                         type = BPF_READ;
17746                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17747                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17748                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17749                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17750                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17751                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17752                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17753                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17754                         type = BPF_WRITE;
17755                 } else {
17756                         continue;
17757                 }
17758
17759                 if (type == BPF_WRITE &&
17760                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17761                         struct bpf_insn patch[] = {
17762                                 *insn,
17763                                 BPF_ST_NOSPEC(),
17764                         };
17765
17766                         cnt = ARRAY_SIZE(patch);
17767                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17768                         if (!new_prog)
17769                                 return -ENOMEM;
17770
17771                         delta    += cnt - 1;
17772                         env->prog = new_prog;
17773                         insn      = new_prog->insnsi + i + delta;
17774                         continue;
17775                 }
17776
17777                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17778                 case PTR_TO_CTX:
17779                         if (!ops->convert_ctx_access)
17780                                 continue;
17781                         convert_ctx_access = ops->convert_ctx_access;
17782                         break;
17783                 case PTR_TO_SOCKET:
17784                 case PTR_TO_SOCK_COMMON:
17785                         convert_ctx_access = bpf_sock_convert_ctx_access;
17786                         break;
17787                 case PTR_TO_TCP_SOCK:
17788                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17789                         break;
17790                 case PTR_TO_XDP_SOCK:
17791                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17792                         break;
17793                 case PTR_TO_BTF_ID:
17794                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17795                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17796                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17797                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17798                  * any faults for loads into such types. BPF_WRITE is disallowed
17799                  * for this case.
17800                  */
17801                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17802                         if (type == BPF_READ) {
17803                                 if (BPF_MODE(insn->code) == BPF_MEM)
17804                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
17805                                                      BPF_SIZE((insn)->code);
17806                                 else
17807                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17808                                                      BPF_SIZE((insn)->code);
17809                                 env->prog->aux->num_exentries++;
17810                         }
17811                         continue;
17812                 default:
17813                         continue;
17814                 }
17815
17816                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17817                 size = BPF_LDST_BYTES(insn);
17818                 mode = BPF_MODE(insn->code);
17819
17820                 /* If the read access is a narrower load of the field,
17821                  * convert to a 4/8-byte load, to minimum program type specific
17822                  * convert_ctx_access changes. If conversion is successful,
17823                  * we will apply proper mask to the result.
17824                  */
17825                 is_narrower_load = size < ctx_field_size;
17826                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17827                 off = insn->off;
17828                 if (is_narrower_load) {
17829                         u8 size_code;
17830
17831                         if (type == BPF_WRITE) {
17832                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17833                                 return -EINVAL;
17834                         }
17835
17836                         size_code = BPF_H;
17837                         if (ctx_field_size == 4)
17838                                 size_code = BPF_W;
17839                         else if (ctx_field_size == 8)
17840                                 size_code = BPF_DW;
17841
17842                         insn->off = off & ~(size_default - 1);
17843                         insn->code = BPF_LDX | BPF_MEM | size_code;
17844                 }
17845
17846                 target_size = 0;
17847                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17848                                          &target_size);
17849                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17850                     (ctx_field_size && !target_size)) {
17851                         verbose(env, "bpf verifier is misconfigured\n");
17852                         return -EINVAL;
17853                 }
17854
17855                 if (is_narrower_load && size < target_size) {
17856                         u8 shift = bpf_ctx_narrow_access_offset(
17857                                 off, size, size_default) * 8;
17858                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17859                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17860                                 return -EINVAL;
17861                         }
17862                         if (ctx_field_size <= 4) {
17863                                 if (shift)
17864                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17865                                                                         insn->dst_reg,
17866                                                                         shift);
17867                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17868                                                                 (1 << size * 8) - 1);
17869                         } else {
17870                                 if (shift)
17871                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17872                                                                         insn->dst_reg,
17873                                                                         shift);
17874                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17875                                                                 (1ULL << size * 8) - 1);
17876                         }
17877                 }
17878                 if (mode == BPF_MEMSX)
17879                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17880                                                        insn->dst_reg, insn->dst_reg,
17881                                                        size * 8, 0);
17882
17883                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17884                 if (!new_prog)
17885                         return -ENOMEM;
17886
17887                 delta += cnt - 1;
17888
17889                 /* keep walking new program and skip insns we just inserted */
17890                 env->prog = new_prog;
17891                 insn      = new_prog->insnsi + i + delta;
17892         }
17893
17894         return 0;
17895 }
17896
17897 static int jit_subprogs(struct bpf_verifier_env *env)
17898 {
17899         struct bpf_prog *prog = env->prog, **func, *tmp;
17900         int i, j, subprog_start, subprog_end = 0, len, subprog;
17901         struct bpf_map *map_ptr;
17902         struct bpf_insn *insn;
17903         void *old_bpf_func;
17904         int err, num_exentries;
17905
17906         if (env->subprog_cnt <= 1)
17907                 return 0;
17908
17909         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17910                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17911                         continue;
17912
17913                 /* Upon error here we cannot fall back to interpreter but
17914                  * need a hard reject of the program. Thus -EFAULT is
17915                  * propagated in any case.
17916                  */
17917                 subprog = find_subprog(env, i + insn->imm + 1);
17918                 if (subprog < 0) {
17919                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17920                                   i + insn->imm + 1);
17921                         return -EFAULT;
17922                 }
17923                 /* temporarily remember subprog id inside insn instead of
17924                  * aux_data, since next loop will split up all insns into funcs
17925                  */
17926                 insn->off = subprog;
17927                 /* remember original imm in case JIT fails and fallback
17928                  * to interpreter will be needed
17929                  */
17930                 env->insn_aux_data[i].call_imm = insn->imm;
17931                 /* point imm to __bpf_call_base+1 from JITs point of view */
17932                 insn->imm = 1;
17933                 if (bpf_pseudo_func(insn))
17934                         /* jit (e.g. x86_64) may emit fewer instructions
17935                          * if it learns a u32 imm is the same as a u64 imm.
17936                          * Force a non zero here.
17937                          */
17938                         insn[1].imm = 1;
17939         }
17940
17941         err = bpf_prog_alloc_jited_linfo(prog);
17942         if (err)
17943                 goto out_undo_insn;
17944
17945         err = -ENOMEM;
17946         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17947         if (!func)
17948                 goto out_undo_insn;
17949
17950         for (i = 0; i < env->subprog_cnt; i++) {
17951                 subprog_start = subprog_end;
17952                 subprog_end = env->subprog_info[i + 1].start;
17953
17954                 len = subprog_end - subprog_start;
17955                 /* bpf_prog_run() doesn't call subprogs directly,
17956                  * hence main prog stats include the runtime of subprogs.
17957                  * subprogs don't have IDs and not reachable via prog_get_next_id
17958                  * func[i]->stats will never be accessed and stays NULL
17959                  */
17960                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17961                 if (!func[i])
17962                         goto out_free;
17963                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17964                        len * sizeof(struct bpf_insn));
17965                 func[i]->type = prog->type;
17966                 func[i]->len = len;
17967                 if (bpf_prog_calc_tag(func[i]))
17968                         goto out_free;
17969                 func[i]->is_func = 1;
17970                 func[i]->aux->func_idx = i;
17971                 /* Below members will be freed only at prog->aux */
17972                 func[i]->aux->btf = prog->aux->btf;
17973                 func[i]->aux->func_info = prog->aux->func_info;
17974                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17975                 func[i]->aux->poke_tab = prog->aux->poke_tab;
17976                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17977
17978                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17979                         struct bpf_jit_poke_descriptor *poke;
17980
17981                         poke = &prog->aux->poke_tab[j];
17982                         if (poke->insn_idx < subprog_end &&
17983                             poke->insn_idx >= subprog_start)
17984                                 poke->aux = func[i]->aux;
17985                 }
17986
17987                 func[i]->aux->name[0] = 'F';
17988                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17989                 func[i]->jit_requested = 1;
17990                 func[i]->blinding_requested = prog->blinding_requested;
17991                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17992                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17993                 func[i]->aux->linfo = prog->aux->linfo;
17994                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17995                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17996                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17997                 num_exentries = 0;
17998                 insn = func[i]->insnsi;
17999                 for (j = 0; j < func[i]->len; j++, insn++) {
18000                         if (BPF_CLASS(insn->code) == BPF_LDX &&
18001                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18002                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18003                                 num_exentries++;
18004                 }
18005                 func[i]->aux->num_exentries = num_exentries;
18006                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18007                 func[i] = bpf_int_jit_compile(func[i]);
18008                 if (!func[i]->jited) {
18009                         err = -ENOTSUPP;
18010                         goto out_free;
18011                 }
18012                 cond_resched();
18013         }
18014
18015         /* at this point all bpf functions were successfully JITed
18016          * now populate all bpf_calls with correct addresses and
18017          * run last pass of JIT
18018          */
18019         for (i = 0; i < env->subprog_cnt; i++) {
18020                 insn = func[i]->insnsi;
18021                 for (j = 0; j < func[i]->len; j++, insn++) {
18022                         if (bpf_pseudo_func(insn)) {
18023                                 subprog = insn->off;
18024                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18025                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18026                                 continue;
18027                         }
18028                         if (!bpf_pseudo_call(insn))
18029                                 continue;
18030                         subprog = insn->off;
18031                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18032                 }
18033
18034                 /* we use the aux data to keep a list of the start addresses
18035                  * of the JITed images for each function in the program
18036                  *
18037                  * for some architectures, such as powerpc64, the imm field
18038                  * might not be large enough to hold the offset of the start
18039                  * address of the callee's JITed image from __bpf_call_base
18040                  *
18041                  * in such cases, we can lookup the start address of a callee
18042                  * by using its subprog id, available from the off field of
18043                  * the call instruction, as an index for this list
18044                  */
18045                 func[i]->aux->func = func;
18046                 func[i]->aux->func_cnt = env->subprog_cnt;
18047         }
18048         for (i = 0; i < env->subprog_cnt; i++) {
18049                 old_bpf_func = func[i]->bpf_func;
18050                 tmp = bpf_int_jit_compile(func[i]);
18051                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18052                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18053                         err = -ENOTSUPP;
18054                         goto out_free;
18055                 }
18056                 cond_resched();
18057         }
18058
18059         /* finally lock prog and jit images for all functions and
18060          * populate kallsysm. Begin at the first subprogram, since
18061          * bpf_prog_load will add the kallsyms for the main program.
18062          */
18063         for (i = 1; i < env->subprog_cnt; i++) {
18064                 bpf_prog_lock_ro(func[i]);
18065                 bpf_prog_kallsyms_add(func[i]);
18066         }
18067
18068         /* Last step: make now unused interpreter insns from main
18069          * prog consistent for later dump requests, so they can
18070          * later look the same as if they were interpreted only.
18071          */
18072         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18073                 if (bpf_pseudo_func(insn)) {
18074                         insn[0].imm = env->insn_aux_data[i].call_imm;
18075                         insn[1].imm = insn->off;
18076                         insn->off = 0;
18077                         continue;
18078                 }
18079                 if (!bpf_pseudo_call(insn))
18080                         continue;
18081                 insn->off = env->insn_aux_data[i].call_imm;
18082                 subprog = find_subprog(env, i + insn->off + 1);
18083                 insn->imm = subprog;
18084         }
18085
18086         prog->jited = 1;
18087         prog->bpf_func = func[0]->bpf_func;
18088         prog->jited_len = func[0]->jited_len;
18089         prog->aux->extable = func[0]->aux->extable;
18090         prog->aux->num_exentries = func[0]->aux->num_exentries;
18091         prog->aux->func = func;
18092         prog->aux->func_cnt = env->subprog_cnt;
18093         bpf_prog_jit_attempt_done(prog);
18094         return 0;
18095 out_free:
18096         /* We failed JIT'ing, so at this point we need to unregister poke
18097          * descriptors from subprogs, so that kernel is not attempting to
18098          * patch it anymore as we're freeing the subprog JIT memory.
18099          */
18100         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18101                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18102                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18103         }
18104         /* At this point we're guaranteed that poke descriptors are not
18105          * live anymore. We can just unlink its descriptor table as it's
18106          * released with the main prog.
18107          */
18108         for (i = 0; i < env->subprog_cnt; i++) {
18109                 if (!func[i])
18110                         continue;
18111                 func[i]->aux->poke_tab = NULL;
18112                 bpf_jit_free(func[i]);
18113         }
18114         kfree(func);
18115 out_undo_insn:
18116         /* cleanup main prog to be interpreted */
18117         prog->jit_requested = 0;
18118         prog->blinding_requested = 0;
18119         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18120                 if (!bpf_pseudo_call(insn))
18121                         continue;
18122                 insn->off = 0;
18123                 insn->imm = env->insn_aux_data[i].call_imm;
18124         }
18125         bpf_prog_jit_attempt_done(prog);
18126         return err;
18127 }
18128
18129 static int fixup_call_args(struct bpf_verifier_env *env)
18130 {
18131 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18132         struct bpf_prog *prog = env->prog;
18133         struct bpf_insn *insn = prog->insnsi;
18134         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18135         int i, depth;
18136 #endif
18137         int err = 0;
18138
18139         if (env->prog->jit_requested &&
18140             !bpf_prog_is_offloaded(env->prog->aux)) {
18141                 err = jit_subprogs(env);
18142                 if (err == 0)
18143                         return 0;
18144                 if (err == -EFAULT)
18145                         return err;
18146         }
18147 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18148         if (has_kfunc_call) {
18149                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18150                 return -EINVAL;
18151         }
18152         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18153                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18154                  * have to be rejected, since interpreter doesn't support them yet.
18155                  */
18156                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18157                 return -EINVAL;
18158         }
18159         for (i = 0; i < prog->len; i++, insn++) {
18160                 if (bpf_pseudo_func(insn)) {
18161                         /* When JIT fails the progs with callback calls
18162                          * have to be rejected, since interpreter doesn't support them yet.
18163                          */
18164                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18165                         return -EINVAL;
18166                 }
18167
18168                 if (!bpf_pseudo_call(insn))
18169                         continue;
18170                 depth = get_callee_stack_depth(env, insn, i);
18171                 if (depth < 0)
18172                         return depth;
18173                 bpf_patch_call_args(insn, depth);
18174         }
18175         err = 0;
18176 #endif
18177         return err;
18178 }
18179
18180 /* replace a generic kfunc with a specialized version if necessary */
18181 static void specialize_kfunc(struct bpf_verifier_env *env,
18182                              u32 func_id, u16 offset, unsigned long *addr)
18183 {
18184         struct bpf_prog *prog = env->prog;
18185         bool seen_direct_write;
18186         void *xdp_kfunc;
18187         bool is_rdonly;
18188
18189         if (bpf_dev_bound_kfunc_id(func_id)) {
18190                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18191                 if (xdp_kfunc) {
18192                         *addr = (unsigned long)xdp_kfunc;
18193                         return;
18194                 }
18195                 /* fallback to default kfunc when not supported by netdev */
18196         }
18197
18198         if (offset)
18199                 return;
18200
18201         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18202                 seen_direct_write = env->seen_direct_write;
18203                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18204
18205                 if (is_rdonly)
18206                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18207
18208                 /* restore env->seen_direct_write to its original value, since
18209                  * may_access_direct_pkt_data mutates it
18210                  */
18211                 env->seen_direct_write = seen_direct_write;
18212         }
18213 }
18214
18215 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18216                                             u16 struct_meta_reg,
18217                                             u16 node_offset_reg,
18218                                             struct bpf_insn *insn,
18219                                             struct bpf_insn *insn_buf,
18220                                             int *cnt)
18221 {
18222         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18223         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18224
18225         insn_buf[0] = addr[0];
18226         insn_buf[1] = addr[1];
18227         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18228         insn_buf[3] = *insn;
18229         *cnt = 4;
18230 }
18231
18232 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18233                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18234 {
18235         const struct bpf_kfunc_desc *desc;
18236
18237         if (!insn->imm) {
18238                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18239                 return -EINVAL;
18240         }
18241
18242         *cnt = 0;
18243
18244         /* insn->imm has the btf func_id. Replace it with an offset relative to
18245          * __bpf_call_base, unless the JIT needs to call functions that are
18246          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18247          */
18248         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18249         if (!desc) {
18250                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18251                         insn->imm);
18252                 return -EFAULT;
18253         }
18254
18255         if (!bpf_jit_supports_far_kfunc_call())
18256                 insn->imm = BPF_CALL_IMM(desc->addr);
18257         if (insn->off)
18258                 return 0;
18259         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18260                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18261                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18262                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18263
18264                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18265                 insn_buf[1] = addr[0];
18266                 insn_buf[2] = addr[1];
18267                 insn_buf[3] = *insn;
18268                 *cnt = 4;
18269         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18270                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18271                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18272                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18273
18274                 insn_buf[0] = addr[0];
18275                 insn_buf[1] = addr[1];
18276                 insn_buf[2] = *insn;
18277                 *cnt = 3;
18278         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18279                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18280                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18281                 int struct_meta_reg = BPF_REG_3;
18282                 int node_offset_reg = BPF_REG_4;
18283
18284                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18285                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18286                         struct_meta_reg = BPF_REG_4;
18287                         node_offset_reg = BPF_REG_5;
18288                 }
18289
18290                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18291                                                 node_offset_reg, insn, insn_buf, cnt);
18292         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18293                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18294                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18295                 *cnt = 1;
18296         }
18297         return 0;
18298 }
18299
18300 /* Do various post-verification rewrites in a single program pass.
18301  * These rewrites simplify JIT and interpreter implementations.
18302  */
18303 static int do_misc_fixups(struct bpf_verifier_env *env)
18304 {
18305         struct bpf_prog *prog = env->prog;
18306         enum bpf_attach_type eatype = prog->expected_attach_type;
18307         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18308         struct bpf_insn *insn = prog->insnsi;
18309         const struct bpf_func_proto *fn;
18310         const int insn_cnt = prog->len;
18311         const struct bpf_map_ops *ops;
18312         struct bpf_insn_aux_data *aux;
18313         struct bpf_insn insn_buf[16];
18314         struct bpf_prog *new_prog;
18315         struct bpf_map *map_ptr;
18316         int i, ret, cnt, delta = 0;
18317
18318         for (i = 0; i < insn_cnt; i++, insn++) {
18319                 /* Make divide-by-zero exceptions impossible. */
18320                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18321                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18322                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18323                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18324                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18325                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18326                         struct bpf_insn *patchlet;
18327                         struct bpf_insn chk_and_div[] = {
18328                                 /* [R,W]x div 0 -> 0 */
18329                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18330                                              BPF_JNE | BPF_K, insn->src_reg,
18331                                              0, 2, 0),
18332                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18333                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18334                                 *insn,
18335                         };
18336                         struct bpf_insn chk_and_mod[] = {
18337                                 /* [R,W]x mod 0 -> [R,W]x */
18338                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18339                                              BPF_JEQ | BPF_K, insn->src_reg,
18340                                              0, 1 + (is64 ? 0 : 1), 0),
18341                                 *insn,
18342                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18343                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18344                         };
18345
18346                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18347                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18348                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18349
18350                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18351                         if (!new_prog)
18352                                 return -ENOMEM;
18353
18354                         delta    += cnt - 1;
18355                         env->prog = prog = new_prog;
18356                         insn      = new_prog->insnsi + i + delta;
18357                         continue;
18358                 }
18359
18360                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18361                 if (BPF_CLASS(insn->code) == BPF_LD &&
18362                     (BPF_MODE(insn->code) == BPF_ABS ||
18363                      BPF_MODE(insn->code) == BPF_IND)) {
18364                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18365                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18366                                 verbose(env, "bpf verifier is misconfigured\n");
18367                                 return -EINVAL;
18368                         }
18369
18370                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18371                         if (!new_prog)
18372                                 return -ENOMEM;
18373
18374                         delta    += cnt - 1;
18375                         env->prog = prog = new_prog;
18376                         insn      = new_prog->insnsi + i + delta;
18377                         continue;
18378                 }
18379
18380                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18381                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18382                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18383                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18384                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18385                         struct bpf_insn *patch = &insn_buf[0];
18386                         bool issrc, isneg, isimm;
18387                         u32 off_reg;
18388
18389                         aux = &env->insn_aux_data[i + delta];
18390                         if (!aux->alu_state ||
18391                             aux->alu_state == BPF_ALU_NON_POINTER)
18392                                 continue;
18393
18394                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18395                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18396                                 BPF_ALU_SANITIZE_SRC;
18397                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18398
18399                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18400                         if (isimm) {
18401                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18402                         } else {
18403                                 if (isneg)
18404                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18405                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18406                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18407                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18408                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18409                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18410                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18411                         }
18412                         if (!issrc)
18413                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18414                         insn->src_reg = BPF_REG_AX;
18415                         if (isneg)
18416                                 insn->code = insn->code == code_add ?
18417                                              code_sub : code_add;
18418                         *patch++ = *insn;
18419                         if (issrc && isneg && !isimm)
18420                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18421                         cnt = patch - insn_buf;
18422
18423                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18424                         if (!new_prog)
18425                                 return -ENOMEM;
18426
18427                         delta    += cnt - 1;
18428                         env->prog = prog = new_prog;
18429                         insn      = new_prog->insnsi + i + delta;
18430                         continue;
18431                 }
18432
18433                 if (insn->code != (BPF_JMP | BPF_CALL))
18434                         continue;
18435                 if (insn->src_reg == BPF_PSEUDO_CALL)
18436                         continue;
18437                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18438                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18439                         if (ret)
18440                                 return ret;
18441                         if (cnt == 0)
18442                                 continue;
18443
18444                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18445                         if (!new_prog)
18446                                 return -ENOMEM;
18447
18448                         delta    += cnt - 1;
18449                         env->prog = prog = new_prog;
18450                         insn      = new_prog->insnsi + i + delta;
18451                         continue;
18452                 }
18453
18454                 if (insn->imm == BPF_FUNC_get_route_realm)
18455                         prog->dst_needed = 1;
18456                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18457                         bpf_user_rnd_init_once();
18458                 if (insn->imm == BPF_FUNC_override_return)
18459                         prog->kprobe_override = 1;
18460                 if (insn->imm == BPF_FUNC_tail_call) {
18461                         /* If we tail call into other programs, we
18462                          * cannot make any assumptions since they can
18463                          * be replaced dynamically during runtime in
18464                          * the program array.
18465                          */
18466                         prog->cb_access = 1;
18467                         if (!allow_tail_call_in_subprogs(env))
18468                                 prog->aux->stack_depth = MAX_BPF_STACK;
18469                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18470
18471                         /* mark bpf_tail_call as different opcode to avoid
18472                          * conditional branch in the interpreter for every normal
18473                          * call and to prevent accidental JITing by JIT compiler
18474                          * that doesn't support bpf_tail_call yet
18475                          */
18476                         insn->imm = 0;
18477                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18478
18479                         aux = &env->insn_aux_data[i + delta];
18480                         if (env->bpf_capable && !prog->blinding_requested &&
18481                             prog->jit_requested &&
18482                             !bpf_map_key_poisoned(aux) &&
18483                             !bpf_map_ptr_poisoned(aux) &&
18484                             !bpf_map_ptr_unpriv(aux)) {
18485                                 struct bpf_jit_poke_descriptor desc = {
18486                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18487                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18488                                         .tail_call.key = bpf_map_key_immediate(aux),
18489                                         .insn_idx = i + delta,
18490                                 };
18491
18492                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18493                                 if (ret < 0) {
18494                                         verbose(env, "adding tail call poke descriptor failed\n");
18495                                         return ret;
18496                                 }
18497
18498                                 insn->imm = ret + 1;
18499                                 continue;
18500                         }
18501
18502                         if (!bpf_map_ptr_unpriv(aux))
18503                                 continue;
18504
18505                         /* instead of changing every JIT dealing with tail_call
18506                          * emit two extra insns:
18507                          * if (index >= max_entries) goto out;
18508                          * index &= array->index_mask;
18509                          * to avoid out-of-bounds cpu speculation
18510                          */
18511                         if (bpf_map_ptr_poisoned(aux)) {
18512                                 verbose(env, "tail_call abusing map_ptr\n");
18513                                 return -EINVAL;
18514                         }
18515
18516                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18517                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18518                                                   map_ptr->max_entries, 2);
18519                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18520                                                     container_of(map_ptr,
18521                                                                  struct bpf_array,
18522                                                                  map)->index_mask);
18523                         insn_buf[2] = *insn;
18524                         cnt = 3;
18525                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18526                         if (!new_prog)
18527                                 return -ENOMEM;
18528
18529                         delta    += cnt - 1;
18530                         env->prog = prog = new_prog;
18531                         insn      = new_prog->insnsi + i + delta;
18532                         continue;
18533                 }
18534
18535                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18536                         /* The verifier will process callback_fn as many times as necessary
18537                          * with different maps and the register states prepared by
18538                          * set_timer_callback_state will be accurate.
18539                          *
18540                          * The following use case is valid:
18541                          *   map1 is shared by prog1, prog2, prog3.
18542                          *   prog1 calls bpf_timer_init for some map1 elements
18543                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18544                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18545                          *   prog3 calls bpf_timer_start for some map1 elements.
18546                          *     Those that were not both bpf_timer_init-ed and
18547                          *     bpf_timer_set_callback-ed will return -EINVAL.
18548                          */
18549                         struct bpf_insn ld_addrs[2] = {
18550                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18551                         };
18552
18553                         insn_buf[0] = ld_addrs[0];
18554                         insn_buf[1] = ld_addrs[1];
18555                         insn_buf[2] = *insn;
18556                         cnt = 3;
18557
18558                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18559                         if (!new_prog)
18560                                 return -ENOMEM;
18561
18562                         delta    += cnt - 1;
18563                         env->prog = prog = new_prog;
18564                         insn      = new_prog->insnsi + i + delta;
18565                         goto patch_call_imm;
18566                 }
18567
18568                 if (is_storage_get_function(insn->imm)) {
18569                         if (!env->prog->aux->sleepable ||
18570                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18571                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18572                         else
18573                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18574                         insn_buf[1] = *insn;
18575                         cnt = 2;
18576
18577                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18578                         if (!new_prog)
18579                                 return -ENOMEM;
18580
18581                         delta += cnt - 1;
18582                         env->prog = prog = new_prog;
18583                         insn = new_prog->insnsi + i + delta;
18584                         goto patch_call_imm;
18585                 }
18586
18587                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18588                  * and other inlining handlers are currently limited to 64 bit
18589                  * only.
18590                  */
18591                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18592                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18593                      insn->imm == BPF_FUNC_map_update_elem ||
18594                      insn->imm == BPF_FUNC_map_delete_elem ||
18595                      insn->imm == BPF_FUNC_map_push_elem   ||
18596                      insn->imm == BPF_FUNC_map_pop_elem    ||
18597                      insn->imm == BPF_FUNC_map_peek_elem   ||
18598                      insn->imm == BPF_FUNC_redirect_map    ||
18599                      insn->imm == BPF_FUNC_for_each_map_elem ||
18600                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18601                         aux = &env->insn_aux_data[i + delta];
18602                         if (bpf_map_ptr_poisoned(aux))
18603                                 goto patch_call_imm;
18604
18605                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18606                         ops = map_ptr->ops;
18607                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18608                             ops->map_gen_lookup) {
18609                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18610                                 if (cnt == -EOPNOTSUPP)
18611                                         goto patch_map_ops_generic;
18612                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18613                                         verbose(env, "bpf verifier is misconfigured\n");
18614                                         return -EINVAL;
18615                                 }
18616
18617                                 new_prog = bpf_patch_insn_data(env, i + delta,
18618                                                                insn_buf, cnt);
18619                                 if (!new_prog)
18620                                         return -ENOMEM;
18621
18622                                 delta    += cnt - 1;
18623                                 env->prog = prog = new_prog;
18624                                 insn      = new_prog->insnsi + i + delta;
18625                                 continue;
18626                         }
18627
18628                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18629                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18630                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18631                                      (long (*)(struct bpf_map *map, void *key))NULL));
18632                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18633                                      (long (*)(struct bpf_map *map, void *key, void *value,
18634                                               u64 flags))NULL));
18635                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18636                                      (long (*)(struct bpf_map *map, void *value,
18637                                               u64 flags))NULL));
18638                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18639                                      (long (*)(struct bpf_map *map, void *value))NULL));
18640                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18641                                      (long (*)(struct bpf_map *map, void *value))NULL));
18642                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18643                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18644                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18645                                      (long (*)(struct bpf_map *map,
18646                                               bpf_callback_t callback_fn,
18647                                               void *callback_ctx,
18648                                               u64 flags))NULL));
18649                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18650                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18651
18652 patch_map_ops_generic:
18653                         switch (insn->imm) {
18654                         case BPF_FUNC_map_lookup_elem:
18655                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18656                                 continue;
18657                         case BPF_FUNC_map_update_elem:
18658                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18659                                 continue;
18660                         case BPF_FUNC_map_delete_elem:
18661                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18662                                 continue;
18663                         case BPF_FUNC_map_push_elem:
18664                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18665                                 continue;
18666                         case BPF_FUNC_map_pop_elem:
18667                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18668                                 continue;
18669                         case BPF_FUNC_map_peek_elem:
18670                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18671                                 continue;
18672                         case BPF_FUNC_redirect_map:
18673                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18674                                 continue;
18675                         case BPF_FUNC_for_each_map_elem:
18676                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18677                                 continue;
18678                         case BPF_FUNC_map_lookup_percpu_elem:
18679                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18680                                 continue;
18681                         }
18682
18683                         goto patch_call_imm;
18684                 }
18685
18686                 /* Implement bpf_jiffies64 inline. */
18687                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18688                     insn->imm == BPF_FUNC_jiffies64) {
18689                         struct bpf_insn ld_jiffies_addr[2] = {
18690                                 BPF_LD_IMM64(BPF_REG_0,
18691                                              (unsigned long)&jiffies),
18692                         };
18693
18694                         insn_buf[0] = ld_jiffies_addr[0];
18695                         insn_buf[1] = ld_jiffies_addr[1];
18696                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18697                                                   BPF_REG_0, 0);
18698                         cnt = 3;
18699
18700                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18701                                                        cnt);
18702                         if (!new_prog)
18703                                 return -ENOMEM;
18704
18705                         delta    += cnt - 1;
18706                         env->prog = prog = new_prog;
18707                         insn      = new_prog->insnsi + i + delta;
18708                         continue;
18709                 }
18710
18711                 /* Implement bpf_get_func_arg inline. */
18712                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18713                     insn->imm == BPF_FUNC_get_func_arg) {
18714                         /* Load nr_args from ctx - 8 */
18715                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18716                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18717                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18718                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18719                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18720                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18721                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18722                         insn_buf[7] = BPF_JMP_A(1);
18723                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18724                         cnt = 9;
18725
18726                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18727                         if (!new_prog)
18728                                 return -ENOMEM;
18729
18730                         delta    += cnt - 1;
18731                         env->prog = prog = new_prog;
18732                         insn      = new_prog->insnsi + i + delta;
18733                         continue;
18734                 }
18735
18736                 /* Implement bpf_get_func_ret inline. */
18737                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18738                     insn->imm == BPF_FUNC_get_func_ret) {
18739                         if (eatype == BPF_TRACE_FEXIT ||
18740                             eatype == BPF_MODIFY_RETURN) {
18741                                 /* Load nr_args from ctx - 8 */
18742                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18743                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18744                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18745                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18746                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18747                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18748                                 cnt = 6;
18749                         } else {
18750                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18751                                 cnt = 1;
18752                         }
18753
18754                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18755                         if (!new_prog)
18756                                 return -ENOMEM;
18757
18758                         delta    += cnt - 1;
18759                         env->prog = prog = new_prog;
18760                         insn      = new_prog->insnsi + i + delta;
18761                         continue;
18762                 }
18763
18764                 /* Implement get_func_arg_cnt inline. */
18765                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18766                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18767                         /* Load nr_args from ctx - 8 */
18768                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18769
18770                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18771                         if (!new_prog)
18772                                 return -ENOMEM;
18773
18774                         env->prog = prog = new_prog;
18775                         insn      = new_prog->insnsi + i + delta;
18776                         continue;
18777                 }
18778
18779                 /* Implement bpf_get_func_ip inline. */
18780                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18781                     insn->imm == BPF_FUNC_get_func_ip) {
18782                         /* Load IP address from ctx - 16 */
18783                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18784
18785                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18786                         if (!new_prog)
18787                                 return -ENOMEM;
18788
18789                         env->prog = prog = new_prog;
18790                         insn      = new_prog->insnsi + i + delta;
18791                         continue;
18792                 }
18793
18794 patch_call_imm:
18795                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18796                 /* all functions that have prototype and verifier allowed
18797                  * programs to call them, must be real in-kernel functions
18798                  */
18799                 if (!fn->func) {
18800                         verbose(env,
18801                                 "kernel subsystem misconfigured func %s#%d\n",
18802                                 func_id_name(insn->imm), insn->imm);
18803                         return -EFAULT;
18804                 }
18805                 insn->imm = fn->func - __bpf_call_base;
18806         }
18807
18808         /* Since poke tab is now finalized, publish aux to tracker. */
18809         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18810                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18811                 if (!map_ptr->ops->map_poke_track ||
18812                     !map_ptr->ops->map_poke_untrack ||
18813                     !map_ptr->ops->map_poke_run) {
18814                         verbose(env, "bpf verifier is misconfigured\n");
18815                         return -EINVAL;
18816                 }
18817
18818                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18819                 if (ret < 0) {
18820                         verbose(env, "tracking tail call prog failed\n");
18821                         return ret;
18822                 }
18823         }
18824
18825         sort_kfunc_descs_by_imm_off(env->prog);
18826
18827         return 0;
18828 }
18829
18830 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18831                                         int position,
18832                                         s32 stack_base,
18833                                         u32 callback_subprogno,
18834                                         u32 *cnt)
18835 {
18836         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18837         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18838         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18839         int reg_loop_max = BPF_REG_6;
18840         int reg_loop_cnt = BPF_REG_7;
18841         int reg_loop_ctx = BPF_REG_8;
18842
18843         struct bpf_prog *new_prog;
18844         u32 callback_start;
18845         u32 call_insn_offset;
18846         s32 callback_offset;
18847
18848         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18849          * be careful to modify this code in sync.
18850          */
18851         struct bpf_insn insn_buf[] = {
18852                 /* Return error and jump to the end of the patch if
18853                  * expected number of iterations is too big.
18854                  */
18855                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18856                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18857                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18858                 /* spill R6, R7, R8 to use these as loop vars */
18859                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18860                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18861                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18862                 /* initialize loop vars */
18863                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18864                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18865                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18866                 /* loop header,
18867                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18868                  */
18869                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18870                 /* callback call,
18871                  * correct callback offset would be set after patching
18872                  */
18873                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18874                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18875                 BPF_CALL_REL(0),
18876                 /* increment loop counter */
18877                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18878                 /* jump to loop header if callback returned 0 */
18879                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18880                 /* return value of bpf_loop,
18881                  * set R0 to the number of iterations
18882                  */
18883                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18884                 /* restore original values of R6, R7, R8 */
18885                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18886                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18887                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18888         };
18889
18890         *cnt = ARRAY_SIZE(insn_buf);
18891         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18892         if (!new_prog)
18893                 return new_prog;
18894
18895         /* callback start is known only after patching */
18896         callback_start = env->subprog_info[callback_subprogno].start;
18897         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18898         call_insn_offset = position + 12;
18899         callback_offset = callback_start - call_insn_offset - 1;
18900         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18901
18902         return new_prog;
18903 }
18904
18905 static bool is_bpf_loop_call(struct bpf_insn *insn)
18906 {
18907         return insn->code == (BPF_JMP | BPF_CALL) &&
18908                 insn->src_reg == 0 &&
18909                 insn->imm == BPF_FUNC_loop;
18910 }
18911
18912 /* For all sub-programs in the program (including main) check
18913  * insn_aux_data to see if there are bpf_loop calls that require
18914  * inlining. If such calls are found the calls are replaced with a
18915  * sequence of instructions produced by `inline_bpf_loop` function and
18916  * subprog stack_depth is increased by the size of 3 registers.
18917  * This stack space is used to spill values of the R6, R7, R8.  These
18918  * registers are used to store the loop bound, counter and context
18919  * variables.
18920  */
18921 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18922 {
18923         struct bpf_subprog_info *subprogs = env->subprog_info;
18924         int i, cur_subprog = 0, cnt, delta = 0;
18925         struct bpf_insn *insn = env->prog->insnsi;
18926         int insn_cnt = env->prog->len;
18927         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18928         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18929         u16 stack_depth_extra = 0;
18930
18931         for (i = 0; i < insn_cnt; i++, insn++) {
18932                 struct bpf_loop_inline_state *inline_state =
18933                         &env->insn_aux_data[i + delta].loop_inline_state;
18934
18935                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18936                         struct bpf_prog *new_prog;
18937
18938                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18939                         new_prog = inline_bpf_loop(env,
18940                                                    i + delta,
18941                                                    -(stack_depth + stack_depth_extra),
18942                                                    inline_state->callback_subprogno,
18943                                                    &cnt);
18944                         if (!new_prog)
18945                                 return -ENOMEM;
18946
18947                         delta     += cnt - 1;
18948                         env->prog  = new_prog;
18949                         insn       = new_prog->insnsi + i + delta;
18950                 }
18951
18952                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18953                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
18954                         cur_subprog++;
18955                         stack_depth = subprogs[cur_subprog].stack_depth;
18956                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18957                         stack_depth_extra = 0;
18958                 }
18959         }
18960
18961         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18962
18963         return 0;
18964 }
18965
18966 static void free_states(struct bpf_verifier_env *env)
18967 {
18968         struct bpf_verifier_state_list *sl, *sln;
18969         int i;
18970
18971         sl = env->free_list;
18972         while (sl) {
18973                 sln = sl->next;
18974                 free_verifier_state(&sl->state, false);
18975                 kfree(sl);
18976                 sl = sln;
18977         }
18978         env->free_list = NULL;
18979
18980         if (!env->explored_states)
18981                 return;
18982
18983         for (i = 0; i < state_htab_size(env); i++) {
18984                 sl = env->explored_states[i];
18985
18986                 while (sl) {
18987                         sln = sl->next;
18988                         free_verifier_state(&sl->state, false);
18989                         kfree(sl);
18990                         sl = sln;
18991                 }
18992                 env->explored_states[i] = NULL;
18993         }
18994 }
18995
18996 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18997 {
18998         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18999         struct bpf_verifier_state *state;
19000         struct bpf_reg_state *regs;
19001         int ret, i;
19002
19003         env->prev_linfo = NULL;
19004         env->pass_cnt++;
19005
19006         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19007         if (!state)
19008                 return -ENOMEM;
19009         state->curframe = 0;
19010         state->speculative = false;
19011         state->branches = 1;
19012         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19013         if (!state->frame[0]) {
19014                 kfree(state);
19015                 return -ENOMEM;
19016         }
19017         env->cur_state = state;
19018         init_func_state(env, state->frame[0],
19019                         BPF_MAIN_FUNC /* callsite */,
19020                         0 /* frameno */,
19021                         subprog);
19022         state->first_insn_idx = env->subprog_info[subprog].start;
19023         state->last_insn_idx = -1;
19024
19025         regs = state->frame[state->curframe]->regs;
19026         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19027                 ret = btf_prepare_func_args(env, subprog, regs);
19028                 if (ret)
19029                         goto out;
19030                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19031                         if (regs[i].type == PTR_TO_CTX)
19032                                 mark_reg_known_zero(env, regs, i);
19033                         else if (regs[i].type == SCALAR_VALUE)
19034                                 mark_reg_unknown(env, regs, i);
19035                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19036                                 const u32 mem_size = regs[i].mem_size;
19037
19038                                 mark_reg_known_zero(env, regs, i);
19039                                 regs[i].mem_size = mem_size;
19040                                 regs[i].id = ++env->id_gen;
19041                         }
19042                 }
19043         } else {
19044                 /* 1st arg to a function */
19045                 regs[BPF_REG_1].type = PTR_TO_CTX;
19046                 mark_reg_known_zero(env, regs, BPF_REG_1);
19047                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19048                 if (ret == -EFAULT)
19049                         /* unlikely verifier bug. abort.
19050                          * ret == 0 and ret < 0 are sadly acceptable for
19051                          * main() function due to backward compatibility.
19052                          * Like socket filter program may be written as:
19053                          * int bpf_prog(struct pt_regs *ctx)
19054                          * and never dereference that ctx in the program.
19055                          * 'struct pt_regs' is a type mismatch for socket
19056                          * filter that should be using 'struct __sk_buff'.
19057                          */
19058                         goto out;
19059         }
19060
19061         ret = do_check(env);
19062 out:
19063         /* check for NULL is necessary, since cur_state can be freed inside
19064          * do_check() under memory pressure.
19065          */
19066         if (env->cur_state) {
19067                 free_verifier_state(env->cur_state, true);
19068                 env->cur_state = NULL;
19069         }
19070         while (!pop_stack(env, NULL, NULL, false));
19071         if (!ret && pop_log)
19072                 bpf_vlog_reset(&env->log, 0);
19073         free_states(env);
19074         return ret;
19075 }
19076
19077 /* Verify all global functions in a BPF program one by one based on their BTF.
19078  * All global functions must pass verification. Otherwise the whole program is rejected.
19079  * Consider:
19080  * int bar(int);
19081  * int foo(int f)
19082  * {
19083  *    return bar(f);
19084  * }
19085  * int bar(int b)
19086  * {
19087  *    ...
19088  * }
19089  * foo() will be verified first for R1=any_scalar_value. During verification it
19090  * will be assumed that bar() already verified successfully and call to bar()
19091  * from foo() will be checked for type match only. Later bar() will be verified
19092  * independently to check that it's safe for R1=any_scalar_value.
19093  */
19094 static int do_check_subprogs(struct bpf_verifier_env *env)
19095 {
19096         struct bpf_prog_aux *aux = env->prog->aux;
19097         int i, ret;
19098
19099         if (!aux->func_info)
19100                 return 0;
19101
19102         for (i = 1; i < env->subprog_cnt; i++) {
19103                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19104                         continue;
19105                 env->insn_idx = env->subprog_info[i].start;
19106                 WARN_ON_ONCE(env->insn_idx == 0);
19107                 ret = do_check_common(env, i);
19108                 if (ret) {
19109                         return ret;
19110                 } else if (env->log.level & BPF_LOG_LEVEL) {
19111                         verbose(env,
19112                                 "Func#%d is safe for any args that match its prototype\n",
19113                                 i);
19114                 }
19115         }
19116         return 0;
19117 }
19118
19119 static int do_check_main(struct bpf_verifier_env *env)
19120 {
19121         int ret;
19122
19123         env->insn_idx = 0;
19124         ret = do_check_common(env, 0);
19125         if (!ret)
19126                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19127         return ret;
19128 }
19129
19130
19131 static void print_verification_stats(struct bpf_verifier_env *env)
19132 {
19133         int i;
19134
19135         if (env->log.level & BPF_LOG_STATS) {
19136                 verbose(env, "verification time %lld usec\n",
19137                         div_u64(env->verification_time, 1000));
19138                 verbose(env, "stack depth ");
19139                 for (i = 0; i < env->subprog_cnt; i++) {
19140                         u32 depth = env->subprog_info[i].stack_depth;
19141
19142                         verbose(env, "%d", depth);
19143                         if (i + 1 < env->subprog_cnt)
19144                                 verbose(env, "+");
19145                 }
19146                 verbose(env, "\n");
19147         }
19148         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19149                 "total_states %d peak_states %d mark_read %d\n",
19150                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19151                 env->max_states_per_insn, env->total_states,
19152                 env->peak_states, env->longest_mark_read_walk);
19153 }
19154
19155 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19156 {
19157         const struct btf_type *t, *func_proto;
19158         const struct bpf_struct_ops *st_ops;
19159         const struct btf_member *member;
19160         struct bpf_prog *prog = env->prog;
19161         u32 btf_id, member_idx;
19162         const char *mname;
19163
19164         if (!prog->gpl_compatible) {
19165                 verbose(env, "struct ops programs must have a GPL compatible license\n");
19166                 return -EINVAL;
19167         }
19168
19169         btf_id = prog->aux->attach_btf_id;
19170         st_ops = bpf_struct_ops_find(btf_id);
19171         if (!st_ops) {
19172                 verbose(env, "attach_btf_id %u is not a supported struct\n",
19173                         btf_id);
19174                 return -ENOTSUPP;
19175         }
19176
19177         t = st_ops->type;
19178         member_idx = prog->expected_attach_type;
19179         if (member_idx >= btf_type_vlen(t)) {
19180                 verbose(env, "attach to invalid member idx %u of struct %s\n",
19181                         member_idx, st_ops->name);
19182                 return -EINVAL;
19183         }
19184
19185         member = &btf_type_member(t)[member_idx];
19186         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19187         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19188                                                NULL);
19189         if (!func_proto) {
19190                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19191                         mname, member_idx, st_ops->name);
19192                 return -EINVAL;
19193         }
19194
19195         if (st_ops->check_member) {
19196                 int err = st_ops->check_member(t, member, prog);
19197
19198                 if (err) {
19199                         verbose(env, "attach to unsupported member %s of struct %s\n",
19200                                 mname, st_ops->name);
19201                         return err;
19202                 }
19203         }
19204
19205         prog->aux->attach_func_proto = func_proto;
19206         prog->aux->attach_func_name = mname;
19207         env->ops = st_ops->verifier_ops;
19208
19209         return 0;
19210 }
19211 #define SECURITY_PREFIX "security_"
19212
19213 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19214 {
19215         if (within_error_injection_list(addr) ||
19216             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19217                 return 0;
19218
19219         return -EINVAL;
19220 }
19221
19222 /* list of non-sleepable functions that are otherwise on
19223  * ALLOW_ERROR_INJECTION list
19224  */
19225 BTF_SET_START(btf_non_sleepable_error_inject)
19226 /* Three functions below can be called from sleepable and non-sleepable context.
19227  * Assume non-sleepable from bpf safety point of view.
19228  */
19229 BTF_ID(func, __filemap_add_folio)
19230 BTF_ID(func, should_fail_alloc_page)
19231 BTF_ID(func, should_failslab)
19232 BTF_SET_END(btf_non_sleepable_error_inject)
19233
19234 static int check_non_sleepable_error_inject(u32 btf_id)
19235 {
19236         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19237 }
19238
19239 int bpf_check_attach_target(struct bpf_verifier_log *log,
19240                             const struct bpf_prog *prog,
19241                             const struct bpf_prog *tgt_prog,
19242                             u32 btf_id,
19243                             struct bpf_attach_target_info *tgt_info)
19244 {
19245         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19246         const char prefix[] = "btf_trace_";
19247         int ret = 0, subprog = -1, i;
19248         const struct btf_type *t;
19249         bool conservative = true;
19250         const char *tname;
19251         struct btf *btf;
19252         long addr = 0;
19253         struct module *mod = NULL;
19254
19255         if (!btf_id) {
19256                 bpf_log(log, "Tracing programs must provide btf_id\n");
19257                 return -EINVAL;
19258         }
19259         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19260         if (!btf) {
19261                 bpf_log(log,
19262                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19263                 return -EINVAL;
19264         }
19265         t = btf_type_by_id(btf, btf_id);
19266         if (!t) {
19267                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19268                 return -EINVAL;
19269         }
19270         tname = btf_name_by_offset(btf, t->name_off);
19271         if (!tname) {
19272                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19273                 return -EINVAL;
19274         }
19275         if (tgt_prog) {
19276                 struct bpf_prog_aux *aux = tgt_prog->aux;
19277
19278                 if (bpf_prog_is_dev_bound(prog->aux) &&
19279                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19280                         bpf_log(log, "Target program bound device mismatch");
19281                         return -EINVAL;
19282                 }
19283
19284                 for (i = 0; i < aux->func_info_cnt; i++)
19285                         if (aux->func_info[i].type_id == btf_id) {
19286                                 subprog = i;
19287                                 break;
19288                         }
19289                 if (subprog == -1) {
19290                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19291                         return -EINVAL;
19292                 }
19293                 conservative = aux->func_info_aux[subprog].unreliable;
19294                 if (prog_extension) {
19295                         if (conservative) {
19296                                 bpf_log(log,
19297                                         "Cannot replace static functions\n");
19298                                 return -EINVAL;
19299                         }
19300                         if (!prog->jit_requested) {
19301                                 bpf_log(log,
19302                                         "Extension programs should be JITed\n");
19303                                 return -EINVAL;
19304                         }
19305                 }
19306                 if (!tgt_prog->jited) {
19307                         bpf_log(log, "Can attach to only JITed progs\n");
19308                         return -EINVAL;
19309                 }
19310                 if (tgt_prog->type == prog->type) {
19311                         /* Cannot fentry/fexit another fentry/fexit program.
19312                          * Cannot attach program extension to another extension.
19313                          * It's ok to attach fentry/fexit to extension program.
19314                          */
19315                         bpf_log(log, "Cannot recursively attach\n");
19316                         return -EINVAL;
19317                 }
19318                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19319                     prog_extension &&
19320                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19321                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19322                         /* Program extensions can extend all program types
19323                          * except fentry/fexit. The reason is the following.
19324                          * The fentry/fexit programs are used for performance
19325                          * analysis, stats and can be attached to any program
19326                          * type except themselves. When extension program is
19327                          * replacing XDP function it is necessary to allow
19328                          * performance analysis of all functions. Both original
19329                          * XDP program and its program extension. Hence
19330                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19331                          * allowed. If extending of fentry/fexit was allowed it
19332                          * would be possible to create long call chain
19333                          * fentry->extension->fentry->extension beyond
19334                          * reasonable stack size. Hence extending fentry is not
19335                          * allowed.
19336                          */
19337                         bpf_log(log, "Cannot extend fentry/fexit\n");
19338                         return -EINVAL;
19339                 }
19340         } else {
19341                 if (prog_extension) {
19342                         bpf_log(log, "Cannot replace kernel functions\n");
19343                         return -EINVAL;
19344                 }
19345         }
19346
19347         switch (prog->expected_attach_type) {
19348         case BPF_TRACE_RAW_TP:
19349                 if (tgt_prog) {
19350                         bpf_log(log,
19351                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19352                         return -EINVAL;
19353                 }
19354                 if (!btf_type_is_typedef(t)) {
19355                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19356                                 btf_id);
19357                         return -EINVAL;
19358                 }
19359                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19360                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19361                                 btf_id, tname);
19362                         return -EINVAL;
19363                 }
19364                 tname += sizeof(prefix) - 1;
19365                 t = btf_type_by_id(btf, t->type);
19366                 if (!btf_type_is_ptr(t))
19367                         /* should never happen in valid vmlinux build */
19368                         return -EINVAL;
19369                 t = btf_type_by_id(btf, t->type);
19370                 if (!btf_type_is_func_proto(t))
19371                         /* should never happen in valid vmlinux build */
19372                         return -EINVAL;
19373
19374                 break;
19375         case BPF_TRACE_ITER:
19376                 if (!btf_type_is_func(t)) {
19377                         bpf_log(log, "attach_btf_id %u is not a function\n",
19378                                 btf_id);
19379                         return -EINVAL;
19380                 }
19381                 t = btf_type_by_id(btf, t->type);
19382                 if (!btf_type_is_func_proto(t))
19383                         return -EINVAL;
19384                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19385                 if (ret)
19386                         return ret;
19387                 break;
19388         default:
19389                 if (!prog_extension)
19390                         return -EINVAL;
19391                 fallthrough;
19392         case BPF_MODIFY_RETURN:
19393         case BPF_LSM_MAC:
19394         case BPF_LSM_CGROUP:
19395         case BPF_TRACE_FENTRY:
19396         case BPF_TRACE_FEXIT:
19397                 if (!btf_type_is_func(t)) {
19398                         bpf_log(log, "attach_btf_id %u is not a function\n",
19399                                 btf_id);
19400                         return -EINVAL;
19401                 }
19402                 if (prog_extension &&
19403                     btf_check_type_match(log, prog, btf, t))
19404                         return -EINVAL;
19405                 t = btf_type_by_id(btf, t->type);
19406                 if (!btf_type_is_func_proto(t))
19407                         return -EINVAL;
19408
19409                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19410                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19411                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19412                         return -EINVAL;
19413
19414                 if (tgt_prog && conservative)
19415                         t = NULL;
19416
19417                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19418                 if (ret < 0)
19419                         return ret;
19420
19421                 if (tgt_prog) {
19422                         if (subprog == 0)
19423                                 addr = (long) tgt_prog->bpf_func;
19424                         else
19425                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19426                 } else {
19427                         if (btf_is_module(btf)) {
19428                                 mod = btf_try_get_module(btf);
19429                                 if (mod)
19430                                         addr = find_kallsyms_symbol_value(mod, tname);
19431                                 else
19432                                         addr = 0;
19433                         } else {
19434                                 addr = kallsyms_lookup_name(tname);
19435                         }
19436                         if (!addr) {
19437                                 module_put(mod);
19438                                 bpf_log(log,
19439                                         "The address of function %s cannot be found\n",
19440                                         tname);
19441                                 return -ENOENT;
19442                         }
19443                 }
19444
19445                 if (prog->aux->sleepable) {
19446                         ret = -EINVAL;
19447                         switch (prog->type) {
19448                         case BPF_PROG_TYPE_TRACING:
19449
19450                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19451                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19452                                  */
19453                                 if (!check_non_sleepable_error_inject(btf_id) &&
19454                                     within_error_injection_list(addr))
19455                                         ret = 0;
19456                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19457                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19458                                  */
19459                                 else {
19460                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19461                                                                                 prog);
19462
19463                                         if (flags && (*flags & KF_SLEEPABLE))
19464                                                 ret = 0;
19465                                 }
19466                                 break;
19467                         case BPF_PROG_TYPE_LSM:
19468                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19469                                  * Only some of them are sleepable.
19470                                  */
19471                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19472                                         ret = 0;
19473                                 break;
19474                         default:
19475                                 break;
19476                         }
19477                         if (ret) {
19478                                 module_put(mod);
19479                                 bpf_log(log, "%s is not sleepable\n", tname);
19480                                 return ret;
19481                         }
19482                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19483                         if (tgt_prog) {
19484                                 module_put(mod);
19485                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19486                                 return -EINVAL;
19487                         }
19488                         ret = -EINVAL;
19489                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19490                             !check_attach_modify_return(addr, tname))
19491                                 ret = 0;
19492                         if (ret) {
19493                                 module_put(mod);
19494                                 bpf_log(log, "%s() is not modifiable\n", tname);
19495                                 return ret;
19496                         }
19497                 }
19498
19499                 break;
19500         }
19501         tgt_info->tgt_addr = addr;
19502         tgt_info->tgt_name = tname;
19503         tgt_info->tgt_type = t;
19504         tgt_info->tgt_mod = mod;
19505         return 0;
19506 }
19507
19508 BTF_SET_START(btf_id_deny)
19509 BTF_ID_UNUSED
19510 #ifdef CONFIG_SMP
19511 BTF_ID(func, migrate_disable)
19512 BTF_ID(func, migrate_enable)
19513 #endif
19514 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19515 BTF_ID(func, rcu_read_unlock_strict)
19516 #endif
19517 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19518 BTF_ID(func, preempt_count_add)
19519 BTF_ID(func, preempt_count_sub)
19520 #endif
19521 #ifdef CONFIG_PREEMPT_RCU
19522 BTF_ID(func, __rcu_read_lock)
19523 BTF_ID(func, __rcu_read_unlock)
19524 #endif
19525 BTF_SET_END(btf_id_deny)
19526
19527 static bool can_be_sleepable(struct bpf_prog *prog)
19528 {
19529         if (prog->type == BPF_PROG_TYPE_TRACING) {
19530                 switch (prog->expected_attach_type) {
19531                 case BPF_TRACE_FENTRY:
19532                 case BPF_TRACE_FEXIT:
19533                 case BPF_MODIFY_RETURN:
19534                 case BPF_TRACE_ITER:
19535                         return true;
19536                 default:
19537                         return false;
19538                 }
19539         }
19540         return prog->type == BPF_PROG_TYPE_LSM ||
19541                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19542                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19543 }
19544
19545 static int check_attach_btf_id(struct bpf_verifier_env *env)
19546 {
19547         struct bpf_prog *prog = env->prog;
19548         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19549         struct bpf_attach_target_info tgt_info = {};
19550         u32 btf_id = prog->aux->attach_btf_id;
19551         struct bpf_trampoline *tr;
19552         int ret;
19553         u64 key;
19554
19555         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19556                 if (prog->aux->sleepable)
19557                         /* attach_btf_id checked to be zero already */
19558                         return 0;
19559                 verbose(env, "Syscall programs can only be sleepable\n");
19560                 return -EINVAL;
19561         }
19562
19563         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19564                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19565                 return -EINVAL;
19566         }
19567
19568         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19569                 return check_struct_ops_btf_id(env);
19570
19571         if (prog->type != BPF_PROG_TYPE_TRACING &&
19572             prog->type != BPF_PROG_TYPE_LSM &&
19573             prog->type != BPF_PROG_TYPE_EXT)
19574                 return 0;
19575
19576         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19577         if (ret)
19578                 return ret;
19579
19580         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19581                 /* to make freplace equivalent to their targets, they need to
19582                  * inherit env->ops and expected_attach_type for the rest of the
19583                  * verification
19584                  */
19585                 env->ops = bpf_verifier_ops[tgt_prog->type];
19586                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19587         }
19588
19589         /* store info about the attachment target that will be used later */
19590         prog->aux->attach_func_proto = tgt_info.tgt_type;
19591         prog->aux->attach_func_name = tgt_info.tgt_name;
19592         prog->aux->mod = tgt_info.tgt_mod;
19593
19594         if (tgt_prog) {
19595                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19596                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19597         }
19598
19599         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19600                 prog->aux->attach_btf_trace = true;
19601                 return 0;
19602         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19603                 if (!bpf_iter_prog_supported(prog))
19604                         return -EINVAL;
19605                 return 0;
19606         }
19607
19608         if (prog->type == BPF_PROG_TYPE_LSM) {
19609                 ret = bpf_lsm_verify_prog(&env->log, prog);
19610                 if (ret < 0)
19611                         return ret;
19612         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19613                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19614                 return -EINVAL;
19615         }
19616
19617         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19618         tr = bpf_trampoline_get(key, &tgt_info);
19619         if (!tr)
19620                 return -ENOMEM;
19621
19622         prog->aux->dst_trampoline = tr;
19623         return 0;
19624 }
19625
19626 struct btf *bpf_get_btf_vmlinux(void)
19627 {
19628         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19629                 mutex_lock(&bpf_verifier_lock);
19630                 if (!btf_vmlinux)
19631                         btf_vmlinux = btf_parse_vmlinux();
19632                 mutex_unlock(&bpf_verifier_lock);
19633         }
19634         return btf_vmlinux;
19635 }
19636
19637 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19638 {
19639         u64 start_time = ktime_get_ns();
19640         struct bpf_verifier_env *env;
19641         int i, len, ret = -EINVAL, err;
19642         u32 log_true_size;
19643         bool is_priv;
19644
19645         /* no program is valid */
19646         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19647                 return -EINVAL;
19648
19649         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19650          * allocate/free it every time bpf_check() is called
19651          */
19652         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19653         if (!env)
19654                 return -ENOMEM;
19655
19656         env->bt.env = env;
19657
19658         len = (*prog)->len;
19659         env->insn_aux_data =
19660                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19661         ret = -ENOMEM;
19662         if (!env->insn_aux_data)
19663                 goto err_free_env;
19664         for (i = 0; i < len; i++)
19665                 env->insn_aux_data[i].orig_idx = i;
19666         env->prog = *prog;
19667         env->ops = bpf_verifier_ops[env->prog->type];
19668         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19669         is_priv = bpf_capable();
19670
19671         bpf_get_btf_vmlinux();
19672
19673         /* grab the mutex to protect few globals used by verifier */
19674         if (!is_priv)
19675                 mutex_lock(&bpf_verifier_lock);
19676
19677         /* user could have requested verbose verifier output
19678          * and supplied buffer to store the verification trace
19679          */
19680         ret = bpf_vlog_init(&env->log, attr->log_level,
19681                             (char __user *) (unsigned long) attr->log_buf,
19682                             attr->log_size);
19683         if (ret)
19684                 goto err_unlock;
19685
19686         mark_verifier_state_clean(env);
19687
19688         if (IS_ERR(btf_vmlinux)) {
19689                 /* Either gcc or pahole or kernel are broken. */
19690                 verbose(env, "in-kernel BTF is malformed\n");
19691                 ret = PTR_ERR(btf_vmlinux);
19692                 goto skip_full_check;
19693         }
19694
19695         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19696         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19697                 env->strict_alignment = true;
19698         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19699                 env->strict_alignment = false;
19700
19701         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19702         env->allow_uninit_stack = bpf_allow_uninit_stack();
19703         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19704         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19705         env->bpf_capable = bpf_capable();
19706
19707         if (is_priv)
19708                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19709
19710         env->explored_states = kvcalloc(state_htab_size(env),
19711                                        sizeof(struct bpf_verifier_state_list *),
19712                                        GFP_USER);
19713         ret = -ENOMEM;
19714         if (!env->explored_states)
19715                 goto skip_full_check;
19716
19717         ret = add_subprog_and_kfunc(env);
19718         if (ret < 0)
19719                 goto skip_full_check;
19720
19721         ret = check_subprogs(env);
19722         if (ret < 0)
19723                 goto skip_full_check;
19724
19725         ret = check_btf_info(env, attr, uattr);
19726         if (ret < 0)
19727                 goto skip_full_check;
19728
19729         ret = check_attach_btf_id(env);
19730         if (ret)
19731                 goto skip_full_check;
19732
19733         ret = resolve_pseudo_ldimm64(env);
19734         if (ret < 0)
19735                 goto skip_full_check;
19736
19737         if (bpf_prog_is_offloaded(env->prog->aux)) {
19738                 ret = bpf_prog_offload_verifier_prep(env->prog);
19739                 if (ret)
19740                         goto skip_full_check;
19741         }
19742
19743         ret = check_cfg(env);
19744         if (ret < 0)
19745                 goto skip_full_check;
19746
19747         ret = do_check_subprogs(env);
19748         ret = ret ?: do_check_main(env);
19749
19750         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19751                 ret = bpf_prog_offload_finalize(env);
19752
19753 skip_full_check:
19754         kvfree(env->explored_states);
19755
19756         if (ret == 0)
19757                 ret = check_max_stack_depth(env);
19758
19759         /* instruction rewrites happen after this point */
19760         if (ret == 0)
19761                 ret = optimize_bpf_loop(env);
19762
19763         if (is_priv) {
19764                 if (ret == 0)
19765                         opt_hard_wire_dead_code_branches(env);
19766                 if (ret == 0)
19767                         ret = opt_remove_dead_code(env);
19768                 if (ret == 0)
19769                         ret = opt_remove_nops(env);
19770         } else {
19771                 if (ret == 0)
19772                         sanitize_dead_code(env);
19773         }
19774
19775         if (ret == 0)
19776                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19777                 ret = convert_ctx_accesses(env);
19778
19779         if (ret == 0)
19780                 ret = do_misc_fixups(env);
19781
19782         /* do 32-bit optimization after insn patching has done so those patched
19783          * insns could be handled correctly.
19784          */
19785         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19786                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19787                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19788                                                                      : false;
19789         }
19790
19791         if (ret == 0)
19792                 ret = fixup_call_args(env);
19793
19794         env->verification_time = ktime_get_ns() - start_time;
19795         print_verification_stats(env);
19796         env->prog->aux->verified_insns = env->insn_processed;
19797
19798         /* preserve original error even if log finalization is successful */
19799         err = bpf_vlog_finalize(&env->log, &log_true_size);
19800         if (err)
19801                 ret = err;
19802
19803         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19804             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19805                                   &log_true_size, sizeof(log_true_size))) {
19806                 ret = -EFAULT;
19807                 goto err_release_maps;
19808         }
19809
19810         if (ret)
19811                 goto err_release_maps;
19812
19813         if (env->used_map_cnt) {
19814                 /* if program passed verifier, update used_maps in bpf_prog_info */
19815                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19816                                                           sizeof(env->used_maps[0]),
19817                                                           GFP_KERNEL);
19818
19819                 if (!env->prog->aux->used_maps) {
19820                         ret = -ENOMEM;
19821                         goto err_release_maps;
19822                 }
19823
19824                 memcpy(env->prog->aux->used_maps, env->used_maps,
19825                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19826                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19827         }
19828         if (env->used_btf_cnt) {
19829                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19830                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19831                                                           sizeof(env->used_btfs[0]),
19832                                                           GFP_KERNEL);
19833                 if (!env->prog->aux->used_btfs) {
19834                         ret = -ENOMEM;
19835                         goto err_release_maps;
19836                 }
19837
19838                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19839                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19840                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19841         }
19842         if (env->used_map_cnt || env->used_btf_cnt) {
19843                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19844                  * bpf_ld_imm64 instructions
19845                  */
19846                 convert_pseudo_ld_imm64(env);
19847         }
19848
19849         adjust_btf_func(env);
19850
19851 err_release_maps:
19852         if (!env->prog->aux->used_maps)
19853                 /* if we didn't copy map pointers into bpf_prog_info, release
19854                  * them now. Otherwise free_used_maps() will release them.
19855                  */
19856                 release_maps(env);
19857         if (!env->prog->aux->used_btfs)
19858                 release_btfs(env);
19859
19860         /* extension progs temporarily inherit the attach_type of their targets
19861            for verification purposes, so set it back to zero before returning
19862          */
19863         if (env->prog->type == BPF_PROG_TYPE_EXT)
19864                 env->prog->expected_attach_type = 0;
19865
19866         *prog = env->prog;
19867 err_unlock:
19868         if (!is_priv)
19869                 mutex_unlock(&bpf_verifier_lock);
19870         vfree(env->insn_aux_data);
19871 err_free_env:
19872         kfree(env);
19873         return ret;
19874 }