bpf: Handle sign-extenstin ctx member accesses
[linux-2.6-microblaze.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29
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                 off = i + insn[i].off + 1;
2859                 if (off < subprog_start || off >= subprog_end) {
2860                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2861                         return -EINVAL;
2862                 }
2863 next:
2864                 if (i == subprog_end - 1) {
2865                         /* to avoid fall-through from one subprog into another
2866                          * the last insn of the subprog should be either exit
2867                          * or unconditional jump back
2868                          */
2869                         if (code != (BPF_JMP | BPF_EXIT) &&
2870                             code != (BPF_JMP | BPF_JA)) {
2871                                 verbose(env, "last insn is not an exit or jmp\n");
2872                                 return -EINVAL;
2873                         }
2874                         subprog_start = subprog_end;
2875                         cur_subprog++;
2876                         if (cur_subprog < env->subprog_cnt)
2877                                 subprog_end = subprog[cur_subprog + 1].start;
2878                 }
2879         }
2880         return 0;
2881 }
2882
2883 /* Parentage chain of this register (or stack slot) should take care of all
2884  * issues like callee-saved registers, stack slot allocation time, etc.
2885  */
2886 static int mark_reg_read(struct bpf_verifier_env *env,
2887                          const struct bpf_reg_state *state,
2888                          struct bpf_reg_state *parent, u8 flag)
2889 {
2890         bool writes = parent == state->parent; /* Observe write marks */
2891         int cnt = 0;
2892
2893         while (parent) {
2894                 /* if read wasn't screened by an earlier write ... */
2895                 if (writes && state->live & REG_LIVE_WRITTEN)
2896                         break;
2897                 if (parent->live & REG_LIVE_DONE) {
2898                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2899                                 reg_type_str(env, parent->type),
2900                                 parent->var_off.value, parent->off);
2901                         return -EFAULT;
2902                 }
2903                 /* The first condition is more likely to be true than the
2904                  * second, checked it first.
2905                  */
2906                 if ((parent->live & REG_LIVE_READ) == flag ||
2907                     parent->live & REG_LIVE_READ64)
2908                         /* The parentage chain never changes and
2909                          * this parent was already marked as LIVE_READ.
2910                          * There is no need to keep walking the chain again and
2911                          * keep re-marking all parents as LIVE_READ.
2912                          * This case happens when the same register is read
2913                          * multiple times without writes into it in-between.
2914                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2915                          * then no need to set the weak REG_LIVE_READ32.
2916                          */
2917                         break;
2918                 /* ... then we depend on parent's value */
2919                 parent->live |= flag;
2920                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2921                 if (flag == REG_LIVE_READ64)
2922                         parent->live &= ~REG_LIVE_READ32;
2923                 state = parent;
2924                 parent = state->parent;
2925                 writes = true;
2926                 cnt++;
2927         }
2928
2929         if (env->longest_mark_read_walk < cnt)
2930                 env->longest_mark_read_walk = cnt;
2931         return 0;
2932 }
2933
2934 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2935 {
2936         struct bpf_func_state *state = func(env, reg);
2937         int spi, ret;
2938
2939         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2940          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2941          * check_kfunc_call.
2942          */
2943         if (reg->type == CONST_PTR_TO_DYNPTR)
2944                 return 0;
2945         spi = dynptr_get_spi(env, reg);
2946         if (spi < 0)
2947                 return spi;
2948         /* Caller ensures dynptr is valid and initialized, which means spi is in
2949          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2950          * read.
2951          */
2952         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2953                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2954         if (ret)
2955                 return ret;
2956         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2957                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2958 }
2959
2960 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2961                           int spi, int nr_slots)
2962 {
2963         struct bpf_func_state *state = func(env, reg);
2964         int err, i;
2965
2966         for (i = 0; i < nr_slots; i++) {
2967                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2968
2969                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2970                 if (err)
2971                         return err;
2972
2973                 mark_stack_slot_scratched(env, spi - i);
2974         }
2975
2976         return 0;
2977 }
2978
2979 /* This function is supposed to be used by the following 32-bit optimization
2980  * code only. It returns TRUE if the source or destination register operates
2981  * on 64-bit, otherwise return FALSE.
2982  */
2983 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2984                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2985 {
2986         u8 code, class, op;
2987
2988         code = insn->code;
2989         class = BPF_CLASS(code);
2990         op = BPF_OP(code);
2991         if (class == BPF_JMP) {
2992                 /* BPF_EXIT for "main" will reach here. Return TRUE
2993                  * conservatively.
2994                  */
2995                 if (op == BPF_EXIT)
2996                         return true;
2997                 if (op == BPF_CALL) {
2998                         /* BPF to BPF call will reach here because of marking
2999                          * caller saved clobber with DST_OP_NO_MARK for which we
3000                          * don't care the register def because they are anyway
3001                          * marked as NOT_INIT already.
3002                          */
3003                         if (insn->src_reg == BPF_PSEUDO_CALL)
3004                                 return false;
3005                         /* Helper call will reach here because of arg type
3006                          * check, conservatively return TRUE.
3007                          */
3008                         if (t == SRC_OP)
3009                                 return true;
3010
3011                         return false;
3012                 }
3013         }
3014
3015         if (class == BPF_ALU64 || class == BPF_JMP ||
3016             /* BPF_END always use BPF_ALU class. */
3017             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3018                 return true;
3019
3020         if (class == BPF_ALU || class == BPF_JMP32)
3021                 return false;
3022
3023         if (class == BPF_LDX) {
3024                 if (t != SRC_OP)
3025                         return BPF_SIZE(code) == BPF_DW;
3026                 /* LDX source must be ptr. */
3027                 return true;
3028         }
3029
3030         if (class == BPF_STX) {
3031                 /* BPF_STX (including atomic variants) has multiple source
3032                  * operands, one of which is a ptr. Check whether the caller is
3033                  * asking about it.
3034                  */
3035                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3036                         return true;
3037                 return BPF_SIZE(code) == BPF_DW;
3038         }
3039
3040         if (class == BPF_LD) {
3041                 u8 mode = BPF_MODE(code);
3042
3043                 /* LD_IMM64 */
3044                 if (mode == BPF_IMM)
3045                         return true;
3046
3047                 /* Both LD_IND and LD_ABS return 32-bit data. */
3048                 if (t != SRC_OP)
3049                         return  false;
3050
3051                 /* Implicit ctx ptr. */
3052                 if (regno == BPF_REG_6)
3053                         return true;
3054
3055                 /* Explicit source could be any width. */
3056                 return true;
3057         }
3058
3059         if (class == BPF_ST)
3060                 /* The only source register for BPF_ST is a ptr. */
3061                 return true;
3062
3063         /* Conservatively return true at default. */
3064         return true;
3065 }
3066
3067 /* Return the regno defined by the insn, or -1. */
3068 static int insn_def_regno(const struct bpf_insn *insn)
3069 {
3070         switch (BPF_CLASS(insn->code)) {
3071         case BPF_JMP:
3072         case BPF_JMP32:
3073         case BPF_ST:
3074                 return -1;
3075         case BPF_STX:
3076                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3077                     (insn->imm & BPF_FETCH)) {
3078                         if (insn->imm == BPF_CMPXCHG)
3079                                 return BPF_REG_0;
3080                         else
3081                                 return insn->src_reg;
3082                 } else {
3083                         return -1;
3084                 }
3085         default:
3086                 return insn->dst_reg;
3087         }
3088 }
3089
3090 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3091 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3092 {
3093         int dst_reg = insn_def_regno(insn);
3094
3095         if (dst_reg == -1)
3096                 return false;
3097
3098         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3099 }
3100
3101 static void mark_insn_zext(struct bpf_verifier_env *env,
3102                            struct bpf_reg_state *reg)
3103 {
3104         s32 def_idx = reg->subreg_def;
3105
3106         if (def_idx == DEF_NOT_SUBREG)
3107                 return;
3108
3109         env->insn_aux_data[def_idx - 1].zext_dst = true;
3110         /* The dst will be zero extended, so won't be sub-register anymore. */
3111         reg->subreg_def = DEF_NOT_SUBREG;
3112 }
3113
3114 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3115                          enum reg_arg_type t)
3116 {
3117         struct bpf_verifier_state *vstate = env->cur_state;
3118         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3119         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3120         struct bpf_reg_state *reg, *regs = state->regs;
3121         bool rw64;
3122
3123         if (regno >= MAX_BPF_REG) {
3124                 verbose(env, "R%d is invalid\n", regno);
3125                 return -EINVAL;
3126         }
3127
3128         mark_reg_scratched(env, regno);
3129
3130         reg = &regs[regno];
3131         rw64 = is_reg64(env, insn, regno, reg, t);
3132         if (t == SRC_OP) {
3133                 /* check whether register used as source operand can be read */
3134                 if (reg->type == NOT_INIT) {
3135                         verbose(env, "R%d !read_ok\n", regno);
3136                         return -EACCES;
3137                 }
3138                 /* We don't need to worry about FP liveness because it's read-only */
3139                 if (regno == BPF_REG_FP)
3140                         return 0;
3141
3142                 if (rw64)
3143                         mark_insn_zext(env, reg);
3144
3145                 return mark_reg_read(env, reg, reg->parent,
3146                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3147         } else {
3148                 /* check whether register used as dest operand can be written to */
3149                 if (regno == BPF_REG_FP) {
3150                         verbose(env, "frame pointer is read only\n");
3151                         return -EACCES;
3152                 }
3153                 reg->live |= REG_LIVE_WRITTEN;
3154                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3155                 if (t == DST_OP)
3156                         mark_reg_unknown(env, regs, regno);
3157         }
3158         return 0;
3159 }
3160
3161 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3162 {
3163         env->insn_aux_data[idx].jmp_point = true;
3164 }
3165
3166 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3167 {
3168         return env->insn_aux_data[insn_idx].jmp_point;
3169 }
3170
3171 /* for any branch, call, exit record the history of jmps in the given state */
3172 static int push_jmp_history(struct bpf_verifier_env *env,
3173                             struct bpf_verifier_state *cur)
3174 {
3175         u32 cnt = cur->jmp_history_cnt;
3176         struct bpf_idx_pair *p;
3177         size_t alloc_size;
3178
3179         if (!is_jmp_point(env, env->insn_idx))
3180                 return 0;
3181
3182         cnt++;
3183         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3184         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3185         if (!p)
3186                 return -ENOMEM;
3187         p[cnt - 1].idx = env->insn_idx;
3188         p[cnt - 1].prev_idx = env->prev_insn_idx;
3189         cur->jmp_history = p;
3190         cur->jmp_history_cnt = cnt;
3191         return 0;
3192 }
3193
3194 /* Backtrack one insn at a time. If idx is not at the top of recorded
3195  * history then previous instruction came from straight line execution.
3196  */
3197 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3198                              u32 *history)
3199 {
3200         u32 cnt = *history;
3201
3202         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3203                 i = st->jmp_history[cnt - 1].prev_idx;
3204                 (*history)--;
3205         } else {
3206                 i--;
3207         }
3208         return i;
3209 }
3210
3211 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3212 {
3213         const struct btf_type *func;
3214         struct btf *desc_btf;
3215
3216         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3217                 return NULL;
3218
3219         desc_btf = find_kfunc_desc_btf(data, insn->off);
3220         if (IS_ERR(desc_btf))
3221                 return "<error>";
3222
3223         func = btf_type_by_id(desc_btf, insn->imm);
3224         return btf_name_by_offset(desc_btf, func->name_off);
3225 }
3226
3227 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3228 {
3229         bt->frame = frame;
3230 }
3231
3232 static inline void bt_reset(struct backtrack_state *bt)
3233 {
3234         struct bpf_verifier_env *env = bt->env;
3235
3236         memset(bt, 0, sizeof(*bt));
3237         bt->env = env;
3238 }
3239
3240 static inline u32 bt_empty(struct backtrack_state *bt)
3241 {
3242         u64 mask = 0;
3243         int i;
3244
3245         for (i = 0; i <= bt->frame; i++)
3246                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3247
3248         return mask == 0;
3249 }
3250
3251 static inline int bt_subprog_enter(struct backtrack_state *bt)
3252 {
3253         if (bt->frame == MAX_CALL_FRAMES - 1) {
3254                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3255                 WARN_ONCE(1, "verifier backtracking bug");
3256                 return -EFAULT;
3257         }
3258         bt->frame++;
3259         return 0;
3260 }
3261
3262 static inline int bt_subprog_exit(struct backtrack_state *bt)
3263 {
3264         if (bt->frame == 0) {
3265                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3266                 WARN_ONCE(1, "verifier backtracking bug");
3267                 return -EFAULT;
3268         }
3269         bt->frame--;
3270         return 0;
3271 }
3272
3273 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3274 {
3275         bt->reg_masks[frame] |= 1 << reg;
3276 }
3277
3278 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3279 {
3280         bt->reg_masks[frame] &= ~(1 << reg);
3281 }
3282
3283 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3284 {
3285         bt_set_frame_reg(bt, bt->frame, reg);
3286 }
3287
3288 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3289 {
3290         bt_clear_frame_reg(bt, bt->frame, reg);
3291 }
3292
3293 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3294 {
3295         bt->stack_masks[frame] |= 1ull << slot;
3296 }
3297
3298 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3299 {
3300         bt->stack_masks[frame] &= ~(1ull << slot);
3301 }
3302
3303 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3304 {
3305         bt_set_frame_slot(bt, bt->frame, slot);
3306 }
3307
3308 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3309 {
3310         bt_clear_frame_slot(bt, bt->frame, slot);
3311 }
3312
3313 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3314 {
3315         return bt->reg_masks[frame];
3316 }
3317
3318 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3319 {
3320         return bt->reg_masks[bt->frame];
3321 }
3322
3323 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3324 {
3325         return bt->stack_masks[frame];
3326 }
3327
3328 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3329 {
3330         return bt->stack_masks[bt->frame];
3331 }
3332
3333 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3334 {
3335         return bt->reg_masks[bt->frame] & (1 << reg);
3336 }
3337
3338 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3339 {
3340         return bt->stack_masks[bt->frame] & (1ull << slot);
3341 }
3342
3343 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3344 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3345 {
3346         DECLARE_BITMAP(mask, 64);
3347         bool first = true;
3348         int i, n;
3349
3350         buf[0] = '\0';
3351
3352         bitmap_from_u64(mask, reg_mask);
3353         for_each_set_bit(i, mask, 32) {
3354                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3355                 first = false;
3356                 buf += n;
3357                 buf_sz -= n;
3358                 if (buf_sz < 0)
3359                         break;
3360         }
3361 }
3362 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3363 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3364 {
3365         DECLARE_BITMAP(mask, 64);
3366         bool first = true;
3367         int i, n;
3368
3369         buf[0] = '\0';
3370
3371         bitmap_from_u64(mask, stack_mask);
3372         for_each_set_bit(i, mask, 64) {
3373                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3374                 first = false;
3375                 buf += n;
3376                 buf_sz -= n;
3377                 if (buf_sz < 0)
3378                         break;
3379         }
3380 }
3381
3382 /* For given verifier state backtrack_insn() is called from the last insn to
3383  * the first insn. Its purpose is to compute a bitmask of registers and
3384  * stack slots that needs precision in the parent verifier state.
3385  *
3386  * @idx is an index of the instruction we are currently processing;
3387  * @subseq_idx is an index of the subsequent instruction that:
3388  *   - *would be* executed next, if jump history is viewed in forward order;
3389  *   - *was* processed previously during backtracking.
3390  */
3391 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3392                           struct backtrack_state *bt)
3393 {
3394         const struct bpf_insn_cbs cbs = {
3395                 .cb_call        = disasm_kfunc_name,
3396                 .cb_print       = verbose,
3397                 .private_data   = env,
3398         };
3399         struct bpf_insn *insn = env->prog->insnsi + idx;
3400         u8 class = BPF_CLASS(insn->code);
3401         u8 opcode = BPF_OP(insn->code);
3402         u8 mode = BPF_MODE(insn->code);
3403         u32 dreg = insn->dst_reg;
3404         u32 sreg = insn->src_reg;
3405         u32 spi, i;
3406
3407         if (insn->code == 0)
3408                 return 0;
3409         if (env->log.level & BPF_LOG_LEVEL2) {
3410                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3411                 verbose(env, "mark_precise: frame%d: regs=%s ",
3412                         bt->frame, env->tmp_str_buf);
3413                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3414                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3415                 verbose(env, "%d: ", idx);
3416                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3417         }
3418
3419         if (class == BPF_ALU || class == BPF_ALU64) {
3420                 if (!bt_is_reg_set(bt, dreg))
3421                         return 0;
3422                 if (opcode == BPF_MOV) {
3423                         if (BPF_SRC(insn->code) == BPF_X) {
3424                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3425                                  * dreg needs precision after this insn
3426                                  * sreg needs precision before this insn
3427                                  */
3428                                 bt_clear_reg(bt, dreg);
3429                                 bt_set_reg(bt, sreg);
3430                         } else {
3431                                 /* dreg = K
3432                                  * dreg needs precision after this insn.
3433                                  * Corresponding register is already marked
3434                                  * as precise=true in this verifier state.
3435                                  * No further markings in parent are necessary
3436                                  */
3437                                 bt_clear_reg(bt, dreg);
3438                         }
3439                 } else {
3440                         if (BPF_SRC(insn->code) == BPF_X) {
3441                                 /* dreg += sreg
3442                                  * both dreg and sreg need precision
3443                                  * before this insn
3444                                  */
3445                                 bt_set_reg(bt, sreg);
3446                         } /* else dreg += K
3447                            * dreg still needs precision before this insn
3448                            */
3449                 }
3450         } else if (class == BPF_LDX) {
3451                 if (!bt_is_reg_set(bt, dreg))
3452                         return 0;
3453                 bt_clear_reg(bt, dreg);
3454
3455                 /* scalars can only be spilled into stack w/o losing precision.
3456                  * Load from any other memory can be zero extended.
3457                  * The desire to keep that precision is already indicated
3458                  * by 'precise' mark in corresponding register of this state.
3459                  * No further tracking necessary.
3460                  */
3461                 if (insn->src_reg != BPF_REG_FP)
3462                         return 0;
3463
3464                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3465                  * that [fp - off] slot contains scalar that needs to be
3466                  * tracked with precision
3467                  */
3468                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3469                 if (spi >= 64) {
3470                         verbose(env, "BUG spi %d\n", spi);
3471                         WARN_ONCE(1, "verifier backtracking bug");
3472                         return -EFAULT;
3473                 }
3474                 bt_set_slot(bt, spi);
3475         } else if (class == BPF_STX || class == BPF_ST) {
3476                 if (bt_is_reg_set(bt, dreg))
3477                         /* stx & st shouldn't be using _scalar_ dst_reg
3478                          * to access memory. It means backtracking
3479                          * encountered a case of pointer subtraction.
3480                          */
3481                         return -ENOTSUPP;
3482                 /* scalars can only be spilled into stack */
3483                 if (insn->dst_reg != BPF_REG_FP)
3484                         return 0;
3485                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3486                 if (spi >= 64) {
3487                         verbose(env, "BUG spi %d\n", spi);
3488                         WARN_ONCE(1, "verifier backtracking bug");
3489                         return -EFAULT;
3490                 }
3491                 if (!bt_is_slot_set(bt, spi))
3492                         return 0;
3493                 bt_clear_slot(bt, spi);
3494                 if (class == BPF_STX)
3495                         bt_set_reg(bt, sreg);
3496         } else if (class == BPF_JMP || class == BPF_JMP32) {
3497                 if (bpf_pseudo_call(insn)) {
3498                         int subprog_insn_idx, subprog;
3499
3500                         subprog_insn_idx = idx + insn->imm + 1;
3501                         subprog = find_subprog(env, subprog_insn_idx);
3502                         if (subprog < 0)
3503                                 return -EFAULT;
3504
3505                         if (subprog_is_global(env, subprog)) {
3506                                 /* check that jump history doesn't have any
3507                                  * extra instructions from subprog; the next
3508                                  * instruction after call to global subprog
3509                                  * should be literally next instruction in
3510                                  * caller program
3511                                  */
3512                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3513                                 /* r1-r5 are invalidated after subprog call,
3514                                  * so for global func call it shouldn't be set
3515                                  * anymore
3516                                  */
3517                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3518                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3519                                         WARN_ONCE(1, "verifier backtracking bug");
3520                                         return -EFAULT;
3521                                 }
3522                                 /* global subprog always sets R0 */
3523                                 bt_clear_reg(bt, BPF_REG_0);
3524                                 return 0;
3525                         } else {
3526                                 /* static subprog call instruction, which
3527                                  * means that we are exiting current subprog,
3528                                  * so only r1-r5 could be still requested as
3529                                  * precise, r0 and r6-r10 or any stack slot in
3530                                  * the current frame should be zero by now
3531                                  */
3532                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3533                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3534                                         WARN_ONCE(1, "verifier backtracking bug");
3535                                         return -EFAULT;
3536                                 }
3537                                 /* we don't track register spills perfectly,
3538                                  * so fallback to force-precise instead of failing */
3539                                 if (bt_stack_mask(bt) != 0)
3540                                         return -ENOTSUPP;
3541                                 /* propagate r1-r5 to the caller */
3542                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3543                                         if (bt_is_reg_set(bt, i)) {
3544                                                 bt_clear_reg(bt, i);
3545                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3546                                         }
3547                                 }
3548                                 if (bt_subprog_exit(bt))
3549                                         return -EFAULT;
3550                                 return 0;
3551                         }
3552                 } else if ((bpf_helper_call(insn) &&
3553                             is_callback_calling_function(insn->imm) &&
3554                             !is_async_callback_calling_function(insn->imm)) ||
3555                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3556                         /* callback-calling helper or kfunc call, which means
3557                          * we are exiting from subprog, but unlike the subprog
3558                          * call handling above, we shouldn't propagate
3559                          * precision of r1-r5 (if any requested), as they are
3560                          * not actually arguments passed directly to callback
3561                          * subprogs
3562                          */
3563                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3564                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3565                                 WARN_ONCE(1, "verifier backtracking bug");
3566                                 return -EFAULT;
3567                         }
3568                         if (bt_stack_mask(bt) != 0)
3569                                 return -ENOTSUPP;
3570                         /* clear r1-r5 in callback subprog's mask */
3571                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3572                                 bt_clear_reg(bt, i);
3573                         if (bt_subprog_exit(bt))
3574                                 return -EFAULT;
3575                         return 0;
3576                 } else if (opcode == BPF_CALL) {
3577                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3578                          * catch this error later. Make backtracking conservative
3579                          * with ENOTSUPP.
3580                          */
3581                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3582                                 return -ENOTSUPP;
3583                         /* regular helper call sets R0 */
3584                         bt_clear_reg(bt, BPF_REG_0);
3585                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3586                                 /* if backtracing was looking for registers R1-R5
3587                                  * they should have been found already.
3588                                  */
3589                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3590                                 WARN_ONCE(1, "verifier backtracking bug");
3591                                 return -EFAULT;
3592                         }
3593                 } else if (opcode == BPF_EXIT) {
3594                         bool r0_precise;
3595
3596                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3597                                 /* if backtracing was looking for registers R1-R5
3598                                  * they should have been found already.
3599                                  */
3600                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3601                                 WARN_ONCE(1, "verifier backtracking bug");
3602                                 return -EFAULT;
3603                         }
3604
3605                         /* BPF_EXIT in subprog or callback always returns
3606                          * right after the call instruction, so by checking
3607                          * whether the instruction at subseq_idx-1 is subprog
3608                          * call or not we can distinguish actual exit from
3609                          * *subprog* from exit from *callback*. In the former
3610                          * case, we need to propagate r0 precision, if
3611                          * necessary. In the former we never do that.
3612                          */
3613                         r0_precise = subseq_idx - 1 >= 0 &&
3614                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3615                                      bt_is_reg_set(bt, BPF_REG_0);
3616
3617                         bt_clear_reg(bt, BPF_REG_0);
3618                         if (bt_subprog_enter(bt))
3619                                 return -EFAULT;
3620
3621                         if (r0_precise)
3622                                 bt_set_reg(bt, BPF_REG_0);
3623                         /* r6-r9 and stack slots will stay set in caller frame
3624                          * bitmasks until we return back from callee(s)
3625                          */
3626                         return 0;
3627                 } else if (BPF_SRC(insn->code) == BPF_X) {
3628                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3629                                 return 0;
3630                         /* dreg <cond> sreg
3631                          * Both dreg and sreg need precision before
3632                          * this insn. If only sreg was marked precise
3633                          * before it would be equally necessary to
3634                          * propagate it to dreg.
3635                          */
3636                         bt_set_reg(bt, dreg);
3637                         bt_set_reg(bt, sreg);
3638                          /* else dreg <cond> K
3639                           * Only dreg still needs precision before
3640                           * this insn, so for the K-based conditional
3641                           * there is nothing new to be marked.
3642                           */
3643                 }
3644         } else if (class == BPF_LD) {
3645                 if (!bt_is_reg_set(bt, dreg))
3646                         return 0;
3647                 bt_clear_reg(bt, dreg);
3648                 /* It's ld_imm64 or ld_abs or ld_ind.
3649                  * For ld_imm64 no further tracking of precision
3650                  * into parent is necessary
3651                  */
3652                 if (mode == BPF_IND || mode == BPF_ABS)
3653                         /* to be analyzed */
3654                         return -ENOTSUPP;
3655         }
3656         return 0;
3657 }
3658
3659 /* the scalar precision tracking algorithm:
3660  * . at the start all registers have precise=false.
3661  * . scalar ranges are tracked as normal through alu and jmp insns.
3662  * . once precise value of the scalar register is used in:
3663  *   .  ptr + scalar alu
3664  *   . if (scalar cond K|scalar)
3665  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3666  *   backtrack through the verifier states and mark all registers and
3667  *   stack slots with spilled constants that these scalar regisers
3668  *   should be precise.
3669  * . during state pruning two registers (or spilled stack slots)
3670  *   are equivalent if both are not precise.
3671  *
3672  * Note the verifier cannot simply walk register parentage chain,
3673  * since many different registers and stack slots could have been
3674  * used to compute single precise scalar.
3675  *
3676  * The approach of starting with precise=true for all registers and then
3677  * backtrack to mark a register as not precise when the verifier detects
3678  * that program doesn't care about specific value (e.g., when helper
3679  * takes register as ARG_ANYTHING parameter) is not safe.
3680  *
3681  * It's ok to walk single parentage chain of the verifier states.
3682  * It's possible that this backtracking will go all the way till 1st insn.
3683  * All other branches will be explored for needing precision later.
3684  *
3685  * The backtracking needs to deal with cases like:
3686  *   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)
3687  * r9 -= r8
3688  * r5 = r9
3689  * if r5 > 0x79f goto pc+7
3690  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3691  * r5 += 1
3692  * ...
3693  * call bpf_perf_event_output#25
3694  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3695  *
3696  * and this case:
3697  * r6 = 1
3698  * call foo // uses callee's r6 inside to compute r0
3699  * r0 += r6
3700  * if r0 == 0 goto
3701  *
3702  * to track above reg_mask/stack_mask needs to be independent for each frame.
3703  *
3704  * Also if parent's curframe > frame where backtracking started,
3705  * the verifier need to mark registers in both frames, otherwise callees
3706  * may incorrectly prune callers. This is similar to
3707  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3708  *
3709  * For now backtracking falls back into conservative marking.
3710  */
3711 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3712                                      struct bpf_verifier_state *st)
3713 {
3714         struct bpf_func_state *func;
3715         struct bpf_reg_state *reg;
3716         int i, j;
3717
3718         if (env->log.level & BPF_LOG_LEVEL2) {
3719                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3720                         st->curframe);
3721         }
3722
3723         /* big hammer: mark all scalars precise in this path.
3724          * pop_stack may still get !precise scalars.
3725          * We also skip current state and go straight to first parent state,
3726          * because precision markings in current non-checkpointed state are
3727          * not needed. See why in the comment in __mark_chain_precision below.
3728          */
3729         for (st = st->parent; st; st = st->parent) {
3730                 for (i = 0; i <= st->curframe; i++) {
3731                         func = st->frame[i];
3732                         for (j = 0; j < BPF_REG_FP; j++) {
3733                                 reg = &func->regs[j];
3734                                 if (reg->type != SCALAR_VALUE || reg->precise)
3735                                         continue;
3736                                 reg->precise = true;
3737                                 if (env->log.level & BPF_LOG_LEVEL2) {
3738                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3739                                                 i, j);
3740                                 }
3741                         }
3742                         for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3743                                 if (!is_spilled_reg(&func->stack[j]))
3744                                         continue;
3745                                 reg = &func->stack[j].spilled_ptr;
3746                                 if (reg->type != SCALAR_VALUE || reg->precise)
3747                                         continue;
3748                                 reg->precise = true;
3749                                 if (env->log.level & BPF_LOG_LEVEL2) {
3750                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3751                                                 i, -(j + 1) * 8);
3752                                 }
3753                         }
3754                 }
3755         }
3756 }
3757
3758 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3759 {
3760         struct bpf_func_state *func;
3761         struct bpf_reg_state *reg;
3762         int i, j;
3763
3764         for (i = 0; i <= st->curframe; i++) {
3765                 func = st->frame[i];
3766                 for (j = 0; j < BPF_REG_FP; j++) {
3767                         reg = &func->regs[j];
3768                         if (reg->type != SCALAR_VALUE)
3769                                 continue;
3770                         reg->precise = false;
3771                 }
3772                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3773                         if (!is_spilled_reg(&func->stack[j]))
3774                                 continue;
3775                         reg = &func->stack[j].spilled_ptr;
3776                         if (reg->type != SCALAR_VALUE)
3777                                 continue;
3778                         reg->precise = false;
3779                 }
3780         }
3781 }
3782
3783 static bool idset_contains(struct bpf_idset *s, u32 id)
3784 {
3785         u32 i;
3786
3787         for (i = 0; i < s->count; ++i)
3788                 if (s->ids[i] == id)
3789                         return true;
3790
3791         return false;
3792 }
3793
3794 static int idset_push(struct bpf_idset *s, u32 id)
3795 {
3796         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3797                 return -EFAULT;
3798         s->ids[s->count++] = id;
3799         return 0;
3800 }
3801
3802 static void idset_reset(struct bpf_idset *s)
3803 {
3804         s->count = 0;
3805 }
3806
3807 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3808  * Mark all registers with these IDs as precise.
3809  */
3810 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3811 {
3812         struct bpf_idset *precise_ids = &env->idset_scratch;
3813         struct backtrack_state *bt = &env->bt;
3814         struct bpf_func_state *func;
3815         struct bpf_reg_state *reg;
3816         DECLARE_BITMAP(mask, 64);
3817         int i, fr;
3818
3819         idset_reset(precise_ids);
3820
3821         for (fr = bt->frame; fr >= 0; fr--) {
3822                 func = st->frame[fr];
3823
3824                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3825                 for_each_set_bit(i, mask, 32) {
3826                         reg = &func->regs[i];
3827                         if (!reg->id || reg->type != SCALAR_VALUE)
3828                                 continue;
3829                         if (idset_push(precise_ids, reg->id))
3830                                 return -EFAULT;
3831                 }
3832
3833                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3834                 for_each_set_bit(i, mask, 64) {
3835                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3836                                 break;
3837                         if (!is_spilled_scalar_reg(&func->stack[i]))
3838                                 continue;
3839                         reg = &func->stack[i].spilled_ptr;
3840                         if (!reg->id)
3841                                 continue;
3842                         if (idset_push(precise_ids, reg->id))
3843                                 return -EFAULT;
3844                 }
3845         }
3846
3847         for (fr = 0; fr <= st->curframe; ++fr) {
3848                 func = st->frame[fr];
3849
3850                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3851                         reg = &func->regs[i];
3852                         if (!reg->id)
3853                                 continue;
3854                         if (!idset_contains(precise_ids, reg->id))
3855                                 continue;
3856                         bt_set_frame_reg(bt, fr, i);
3857                 }
3858                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3859                         if (!is_spilled_scalar_reg(&func->stack[i]))
3860                                 continue;
3861                         reg = &func->stack[i].spilled_ptr;
3862                         if (!reg->id)
3863                                 continue;
3864                         if (!idset_contains(precise_ids, reg->id))
3865                                 continue;
3866                         bt_set_frame_slot(bt, fr, i);
3867                 }
3868         }
3869
3870         return 0;
3871 }
3872
3873 /*
3874  * __mark_chain_precision() backtracks BPF program instruction sequence and
3875  * chain of verifier states making sure that register *regno* (if regno >= 0)
3876  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3877  * SCALARS, as well as any other registers and slots that contribute to
3878  * a tracked state of given registers/stack slots, depending on specific BPF
3879  * assembly instructions (see backtrack_insns() for exact instruction handling
3880  * logic). This backtracking relies on recorded jmp_history and is able to
3881  * traverse entire chain of parent states. This process ends only when all the
3882  * necessary registers/slots and their transitive dependencies are marked as
3883  * precise.
3884  *
3885  * One important and subtle aspect is that precise marks *do not matter* in
3886  * the currently verified state (current state). It is important to understand
3887  * why this is the case.
3888  *
3889  * First, note that current state is the state that is not yet "checkpointed",
3890  * i.e., it is not yet put into env->explored_states, and it has no children
3891  * states as well. It's ephemeral, and can end up either a) being discarded if
3892  * compatible explored state is found at some point or BPF_EXIT instruction is
3893  * reached or b) checkpointed and put into env->explored_states, branching out
3894  * into one or more children states.
3895  *
3896  * In the former case, precise markings in current state are completely
3897  * ignored by state comparison code (see regsafe() for details). Only
3898  * checkpointed ("old") state precise markings are important, and if old
3899  * state's register/slot is precise, regsafe() assumes current state's
3900  * register/slot as precise and checks value ranges exactly and precisely. If
3901  * states turn out to be compatible, current state's necessary precise
3902  * markings and any required parent states' precise markings are enforced
3903  * after the fact with propagate_precision() logic, after the fact. But it's
3904  * important to realize that in this case, even after marking current state
3905  * registers/slots as precise, we immediately discard current state. So what
3906  * actually matters is any of the precise markings propagated into current
3907  * state's parent states, which are always checkpointed (due to b) case above).
3908  * As such, for scenario a) it doesn't matter if current state has precise
3909  * markings set or not.
3910  *
3911  * Now, for the scenario b), checkpointing and forking into child(ren)
3912  * state(s). Note that before current state gets to checkpointing step, any
3913  * processed instruction always assumes precise SCALAR register/slot
3914  * knowledge: if precise value or range is useful to prune jump branch, BPF
3915  * verifier takes this opportunity enthusiastically. Similarly, when
3916  * register's value is used to calculate offset or memory address, exact
3917  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3918  * what we mentioned above about state comparison ignoring precise markings
3919  * during state comparison, BPF verifier ignores and also assumes precise
3920  * markings *at will* during instruction verification process. But as verifier
3921  * assumes precision, it also propagates any precision dependencies across
3922  * parent states, which are not yet finalized, so can be further restricted
3923  * based on new knowledge gained from restrictions enforced by their children
3924  * states. This is so that once those parent states are finalized, i.e., when
3925  * they have no more active children state, state comparison logic in
3926  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3927  * required for correctness.
3928  *
3929  * To build a bit more intuition, note also that once a state is checkpointed,
3930  * the path we took to get to that state is not important. This is crucial
3931  * property for state pruning. When state is checkpointed and finalized at
3932  * some instruction index, it can be correctly and safely used to "short
3933  * circuit" any *compatible* state that reaches exactly the same instruction
3934  * index. I.e., if we jumped to that instruction from a completely different
3935  * code path than original finalized state was derived from, it doesn't
3936  * matter, current state can be discarded because from that instruction
3937  * forward having a compatible state will ensure we will safely reach the
3938  * exit. States describe preconditions for further exploration, but completely
3939  * forget the history of how we got here.
3940  *
3941  * This also means that even if we needed precise SCALAR range to get to
3942  * finalized state, but from that point forward *that same* SCALAR register is
3943  * never used in a precise context (i.e., it's precise value is not needed for
3944  * correctness), it's correct and safe to mark such register as "imprecise"
3945  * (i.e., precise marking set to false). This is what we rely on when we do
3946  * not set precise marking in current state. If no child state requires
3947  * precision for any given SCALAR register, it's safe to dictate that it can
3948  * be imprecise. If any child state does require this register to be precise,
3949  * we'll mark it precise later retroactively during precise markings
3950  * propagation from child state to parent states.
3951  *
3952  * Skipping precise marking setting in current state is a mild version of
3953  * relying on the above observation. But we can utilize this property even
3954  * more aggressively by proactively forgetting any precise marking in the
3955  * current state (which we inherited from the parent state), right before we
3956  * checkpoint it and branch off into new child state. This is done by
3957  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3958  * finalized states which help in short circuiting more future states.
3959  */
3960 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3961 {
3962         struct backtrack_state *bt = &env->bt;
3963         struct bpf_verifier_state *st = env->cur_state;
3964         int first_idx = st->first_insn_idx;
3965         int last_idx = env->insn_idx;
3966         int subseq_idx = -1;
3967         struct bpf_func_state *func;
3968         struct bpf_reg_state *reg;
3969         bool skip_first = true;
3970         int i, fr, err;
3971
3972         if (!env->bpf_capable)
3973                 return 0;
3974
3975         /* set frame number from which we are starting to backtrack */
3976         bt_init(bt, env->cur_state->curframe);
3977
3978         /* Do sanity checks against current state of register and/or stack
3979          * slot, but don't set precise flag in current state, as precision
3980          * tracking in the current state is unnecessary.
3981          */
3982         func = st->frame[bt->frame];
3983         if (regno >= 0) {
3984                 reg = &func->regs[regno];
3985                 if (reg->type != SCALAR_VALUE) {
3986                         WARN_ONCE(1, "backtracing misuse");
3987                         return -EFAULT;
3988                 }
3989                 bt_set_reg(bt, regno);
3990         }
3991
3992         if (bt_empty(bt))
3993                 return 0;
3994
3995         for (;;) {
3996                 DECLARE_BITMAP(mask, 64);
3997                 u32 history = st->jmp_history_cnt;
3998
3999                 if (env->log.level & BPF_LOG_LEVEL2) {
4000                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4001                                 bt->frame, last_idx, first_idx, subseq_idx);
4002                 }
4003
4004                 /* If some register with scalar ID is marked as precise,
4005                  * make sure that all registers sharing this ID are also precise.
4006                  * This is needed to estimate effect of find_equal_scalars().
4007                  * Do this at the last instruction of each state,
4008                  * bpf_reg_state::id fields are valid for these instructions.
4009                  *
4010                  * Allows to track precision in situation like below:
4011                  *
4012                  *     r2 = unknown value
4013                  *     ...
4014                  *   --- state #0 ---
4015                  *     ...
4016                  *     r1 = r2                 // r1 and r2 now share the same ID
4017                  *     ...
4018                  *   --- state #1 {r1.id = A, r2.id = A} ---
4019                  *     ...
4020                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4021                  *     ...
4022                  *   --- state #2 {r1.id = A, r2.id = A} ---
4023                  *     r3 = r10
4024                  *     r3 += r1                // need to mark both r1 and r2
4025                  */
4026                 if (mark_precise_scalar_ids(env, st))
4027                         return -EFAULT;
4028
4029                 if (last_idx < 0) {
4030                         /* we are at the entry into subprog, which
4031                          * is expected for global funcs, but only if
4032                          * requested precise registers are R1-R5
4033                          * (which are global func's input arguments)
4034                          */
4035                         if (st->curframe == 0 &&
4036                             st->frame[0]->subprogno > 0 &&
4037                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4038                             bt_stack_mask(bt) == 0 &&
4039                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4040                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4041                                 for_each_set_bit(i, mask, 32) {
4042                                         reg = &st->frame[0]->regs[i];
4043                                         if (reg->type != SCALAR_VALUE) {
4044                                                 bt_clear_reg(bt, i);
4045                                                 continue;
4046                                         }
4047                                         reg->precise = true;
4048                                 }
4049                                 return 0;
4050                         }
4051
4052                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4053                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4054                         WARN_ONCE(1, "verifier backtracking bug");
4055                         return -EFAULT;
4056                 }
4057
4058                 for (i = last_idx;;) {
4059                         if (skip_first) {
4060                                 err = 0;
4061                                 skip_first = false;
4062                         } else {
4063                                 err = backtrack_insn(env, i, subseq_idx, bt);
4064                         }
4065                         if (err == -ENOTSUPP) {
4066                                 mark_all_scalars_precise(env, env->cur_state);
4067                                 bt_reset(bt);
4068                                 return 0;
4069                         } else if (err) {
4070                                 return err;
4071                         }
4072                         if (bt_empty(bt))
4073                                 /* Found assignment(s) into tracked register in this state.
4074                                  * Since this state is already marked, just return.
4075                                  * Nothing to be tracked further in the parent state.
4076                                  */
4077                                 return 0;
4078                         if (i == first_idx)
4079                                 break;
4080                         subseq_idx = i;
4081                         i = get_prev_insn_idx(st, i, &history);
4082                         if (i >= env->prog->len) {
4083                                 /* This can happen if backtracking reached insn 0
4084                                  * and there are still reg_mask or stack_mask
4085                                  * to backtrack.
4086                                  * It means the backtracking missed the spot where
4087                                  * particular register was initialized with a constant.
4088                                  */
4089                                 verbose(env, "BUG backtracking idx %d\n", i);
4090                                 WARN_ONCE(1, "verifier backtracking bug");
4091                                 return -EFAULT;
4092                         }
4093                 }
4094                 st = st->parent;
4095                 if (!st)
4096                         break;
4097
4098                 for (fr = bt->frame; fr >= 0; fr--) {
4099                         func = st->frame[fr];
4100                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4101                         for_each_set_bit(i, mask, 32) {
4102                                 reg = &func->regs[i];
4103                                 if (reg->type != SCALAR_VALUE) {
4104                                         bt_clear_frame_reg(bt, fr, i);
4105                                         continue;
4106                                 }
4107                                 if (reg->precise)
4108                                         bt_clear_frame_reg(bt, fr, i);
4109                                 else
4110                                         reg->precise = true;
4111                         }
4112
4113                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4114                         for_each_set_bit(i, mask, 64) {
4115                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4116                                         /* the sequence of instructions:
4117                                          * 2: (bf) r3 = r10
4118                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4119                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4120                                          * doesn't contain jmps. It's backtracked
4121                                          * as a single block.
4122                                          * During backtracking insn 3 is not recognized as
4123                                          * stack access, so at the end of backtracking
4124                                          * stack slot fp-8 is still marked in stack_mask.
4125                                          * However the parent state may not have accessed
4126                                          * fp-8 and it's "unallocated" stack space.
4127                                          * In such case fallback to conservative.
4128                                          */
4129                                         mark_all_scalars_precise(env, env->cur_state);
4130                                         bt_reset(bt);
4131                                         return 0;
4132                                 }
4133
4134                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4135                                         bt_clear_frame_slot(bt, fr, i);
4136                                         continue;
4137                                 }
4138                                 reg = &func->stack[i].spilled_ptr;
4139                                 if (reg->precise)
4140                                         bt_clear_frame_slot(bt, fr, i);
4141                                 else
4142                                         reg->precise = true;
4143                         }
4144                         if (env->log.level & BPF_LOG_LEVEL2) {
4145                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4146                                              bt_frame_reg_mask(bt, fr));
4147                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4148                                         fr, env->tmp_str_buf);
4149                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4150                                                bt_frame_stack_mask(bt, fr));
4151                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4152                                 print_verifier_state(env, func, true);
4153                         }
4154                 }
4155
4156                 if (bt_empty(bt))
4157                         return 0;
4158
4159                 subseq_idx = first_idx;
4160                 last_idx = st->last_insn_idx;
4161                 first_idx = st->first_insn_idx;
4162         }
4163
4164         /* if we still have requested precise regs or slots, we missed
4165          * something (e.g., stack access through non-r10 register), so
4166          * fallback to marking all precise
4167          */
4168         if (!bt_empty(bt)) {
4169                 mark_all_scalars_precise(env, env->cur_state);
4170                 bt_reset(bt);
4171         }
4172
4173         return 0;
4174 }
4175
4176 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4177 {
4178         return __mark_chain_precision(env, regno);
4179 }
4180
4181 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4182  * desired reg and stack masks across all relevant frames
4183  */
4184 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4185 {
4186         return __mark_chain_precision(env, -1);
4187 }
4188
4189 static bool is_spillable_regtype(enum bpf_reg_type type)
4190 {
4191         switch (base_type(type)) {
4192         case PTR_TO_MAP_VALUE:
4193         case PTR_TO_STACK:
4194         case PTR_TO_CTX:
4195         case PTR_TO_PACKET:
4196         case PTR_TO_PACKET_META:
4197         case PTR_TO_PACKET_END:
4198         case PTR_TO_FLOW_KEYS:
4199         case CONST_PTR_TO_MAP:
4200         case PTR_TO_SOCKET:
4201         case PTR_TO_SOCK_COMMON:
4202         case PTR_TO_TCP_SOCK:
4203         case PTR_TO_XDP_SOCK:
4204         case PTR_TO_BTF_ID:
4205         case PTR_TO_BUF:
4206         case PTR_TO_MEM:
4207         case PTR_TO_FUNC:
4208         case PTR_TO_MAP_KEY:
4209                 return true;
4210         default:
4211                 return false;
4212         }
4213 }
4214
4215 /* Does this register contain a constant zero? */
4216 static bool register_is_null(struct bpf_reg_state *reg)
4217 {
4218         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4219 }
4220
4221 static bool register_is_const(struct bpf_reg_state *reg)
4222 {
4223         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4224 }
4225
4226 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4227 {
4228         return tnum_is_unknown(reg->var_off) &&
4229                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4230                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4231                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4232                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4233 }
4234
4235 static bool register_is_bounded(struct bpf_reg_state *reg)
4236 {
4237         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4238 }
4239
4240 static bool __is_pointer_value(bool allow_ptr_leaks,
4241                                const struct bpf_reg_state *reg)
4242 {
4243         if (allow_ptr_leaks)
4244                 return false;
4245
4246         return reg->type != SCALAR_VALUE;
4247 }
4248
4249 /* Copy src state preserving dst->parent and dst->live fields */
4250 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4251 {
4252         struct bpf_reg_state *parent = dst->parent;
4253         enum bpf_reg_liveness live = dst->live;
4254
4255         *dst = *src;
4256         dst->parent = parent;
4257         dst->live = live;
4258 }
4259
4260 static void save_register_state(struct bpf_func_state *state,
4261                                 int spi, struct bpf_reg_state *reg,
4262                                 int size)
4263 {
4264         int i;
4265
4266         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4267         if (size == BPF_REG_SIZE)
4268                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4269
4270         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4271                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4272
4273         /* size < 8 bytes spill */
4274         for (; i; i--)
4275                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4276 }
4277
4278 static bool is_bpf_st_mem(struct bpf_insn *insn)
4279 {
4280         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4281 }
4282
4283 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4284  * stack boundary and alignment are checked in check_mem_access()
4285  */
4286 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4287                                        /* stack frame we're writing to */
4288                                        struct bpf_func_state *state,
4289                                        int off, int size, int value_regno,
4290                                        int insn_idx)
4291 {
4292         struct bpf_func_state *cur; /* state of the current function */
4293         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4294         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4295         struct bpf_reg_state *reg = NULL;
4296         u32 dst_reg = insn->dst_reg;
4297
4298         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4299         if (err)
4300                 return err;
4301         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4302          * so it's aligned access and [off, off + size) are within stack limits
4303          */
4304         if (!env->allow_ptr_leaks &&
4305             state->stack[spi].slot_type[0] == STACK_SPILL &&
4306             size != BPF_REG_SIZE) {
4307                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4308                 return -EACCES;
4309         }
4310
4311         cur = env->cur_state->frame[env->cur_state->curframe];
4312         if (value_regno >= 0)
4313                 reg = &cur->regs[value_regno];
4314         if (!env->bypass_spec_v4) {
4315                 bool sanitize = reg && is_spillable_regtype(reg->type);
4316
4317                 for (i = 0; i < size; i++) {
4318                         u8 type = state->stack[spi].slot_type[i];
4319
4320                         if (type != STACK_MISC && type != STACK_ZERO) {
4321                                 sanitize = true;
4322                                 break;
4323                         }
4324                 }
4325
4326                 if (sanitize)
4327                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4328         }
4329
4330         err = destroy_if_dynptr_stack_slot(env, state, spi);
4331         if (err)
4332                 return err;
4333
4334         mark_stack_slot_scratched(env, spi);
4335         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4336             !register_is_null(reg) && env->bpf_capable) {
4337                 if (dst_reg != BPF_REG_FP) {
4338                         /* The backtracking logic can only recognize explicit
4339                          * stack slot address like [fp - 8]. Other spill of
4340                          * scalar via different register has to be conservative.
4341                          * Backtrack from here and mark all registers as precise
4342                          * that contributed into 'reg' being a constant.
4343                          */
4344                         err = mark_chain_precision(env, value_regno);
4345                         if (err)
4346                                 return err;
4347                 }
4348                 save_register_state(state, spi, reg, size);
4349                 /* Break the relation on a narrowing spill. */
4350                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4351                         state->stack[spi].spilled_ptr.id = 0;
4352         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4353                    insn->imm != 0 && env->bpf_capable) {
4354                 struct bpf_reg_state fake_reg = {};
4355
4356                 __mark_reg_known(&fake_reg, (u32)insn->imm);
4357                 fake_reg.type = SCALAR_VALUE;
4358                 save_register_state(state, spi, &fake_reg, size);
4359         } else if (reg && is_spillable_regtype(reg->type)) {
4360                 /* register containing pointer is being spilled into stack */
4361                 if (size != BPF_REG_SIZE) {
4362                         verbose_linfo(env, insn_idx, "; ");
4363                         verbose(env, "invalid size of register spill\n");
4364                         return -EACCES;
4365                 }
4366                 if (state != cur && reg->type == PTR_TO_STACK) {
4367                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4368                         return -EINVAL;
4369                 }
4370                 save_register_state(state, spi, reg, size);
4371         } else {
4372                 u8 type = STACK_MISC;
4373
4374                 /* regular write of data into stack destroys any spilled ptr */
4375                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4376                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4377                 if (is_stack_slot_special(&state->stack[spi]))
4378                         for (i = 0; i < BPF_REG_SIZE; i++)
4379                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4380
4381                 /* only mark the slot as written if all 8 bytes were written
4382                  * otherwise read propagation may incorrectly stop too soon
4383                  * when stack slots are partially written.
4384                  * This heuristic means that read propagation will be
4385                  * conservative, since it will add reg_live_read marks
4386                  * to stack slots all the way to first state when programs
4387                  * writes+reads less than 8 bytes
4388                  */
4389                 if (size == BPF_REG_SIZE)
4390                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4391
4392                 /* when we zero initialize stack slots mark them as such */
4393                 if ((reg && register_is_null(reg)) ||
4394                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4395                         /* backtracking doesn't work for STACK_ZERO yet. */
4396                         err = mark_chain_precision(env, value_regno);
4397                         if (err)
4398                                 return err;
4399                         type = STACK_ZERO;
4400                 }
4401
4402                 /* Mark slots affected by this stack write. */
4403                 for (i = 0; i < size; i++)
4404                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4405                                 type;
4406         }
4407         return 0;
4408 }
4409
4410 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4411  * known to contain a variable offset.
4412  * This function checks whether the write is permitted and conservatively
4413  * tracks the effects of the write, considering that each stack slot in the
4414  * dynamic range is potentially written to.
4415  *
4416  * 'off' includes 'regno->off'.
4417  * 'value_regno' can be -1, meaning that an unknown value is being written to
4418  * the stack.
4419  *
4420  * Spilled pointers in range are not marked as written because we don't know
4421  * what's going to be actually written. This means that read propagation for
4422  * future reads cannot be terminated by this write.
4423  *
4424  * For privileged programs, uninitialized stack slots are considered
4425  * initialized by this write (even though we don't know exactly what offsets
4426  * are going to be written to). The idea is that we don't want the verifier to
4427  * reject future reads that access slots written to through variable offsets.
4428  */
4429 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4430                                      /* func where register points to */
4431                                      struct bpf_func_state *state,
4432                                      int ptr_regno, int off, int size,
4433                                      int value_regno, int insn_idx)
4434 {
4435         struct bpf_func_state *cur; /* state of the current function */
4436         int min_off, max_off;
4437         int i, err;
4438         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4439         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4440         bool writing_zero = false;
4441         /* set if the fact that we're writing a zero is used to let any
4442          * stack slots remain STACK_ZERO
4443          */
4444         bool zero_used = false;
4445
4446         cur = env->cur_state->frame[env->cur_state->curframe];
4447         ptr_reg = &cur->regs[ptr_regno];
4448         min_off = ptr_reg->smin_value + off;
4449         max_off = ptr_reg->smax_value + off + size;
4450         if (value_regno >= 0)
4451                 value_reg = &cur->regs[value_regno];
4452         if ((value_reg && register_is_null(value_reg)) ||
4453             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4454                 writing_zero = true;
4455
4456         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4457         if (err)
4458                 return err;
4459
4460         for (i = min_off; i < max_off; i++) {
4461                 int spi;
4462
4463                 spi = __get_spi(i);
4464                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4465                 if (err)
4466                         return err;
4467         }
4468
4469         /* Variable offset writes destroy any spilled pointers in range. */
4470         for (i = min_off; i < max_off; i++) {
4471                 u8 new_type, *stype;
4472                 int slot, spi;
4473
4474                 slot = -i - 1;
4475                 spi = slot / BPF_REG_SIZE;
4476                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4477                 mark_stack_slot_scratched(env, spi);
4478
4479                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4480                         /* Reject the write if range we may write to has not
4481                          * been initialized beforehand. If we didn't reject
4482                          * here, the ptr status would be erased below (even
4483                          * though not all slots are actually overwritten),
4484                          * possibly opening the door to leaks.
4485                          *
4486                          * We do however catch STACK_INVALID case below, and
4487                          * only allow reading possibly uninitialized memory
4488                          * later for CAP_PERFMON, as the write may not happen to
4489                          * that slot.
4490                          */
4491                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4492                                 insn_idx, i);
4493                         return -EINVAL;
4494                 }
4495
4496                 /* Erase all spilled pointers. */
4497                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4498
4499                 /* Update the slot type. */
4500                 new_type = STACK_MISC;
4501                 if (writing_zero && *stype == STACK_ZERO) {
4502                         new_type = STACK_ZERO;
4503                         zero_used = true;
4504                 }
4505                 /* If the slot is STACK_INVALID, we check whether it's OK to
4506                  * pretend that it will be initialized by this write. The slot
4507                  * might not actually be written to, and so if we mark it as
4508                  * initialized future reads might leak uninitialized memory.
4509                  * For privileged programs, we will accept such reads to slots
4510                  * that may or may not be written because, if we're reject
4511                  * them, the error would be too confusing.
4512                  */
4513                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4514                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4515                                         insn_idx, i);
4516                         return -EINVAL;
4517                 }
4518                 *stype = new_type;
4519         }
4520         if (zero_used) {
4521                 /* backtracking doesn't work for STACK_ZERO yet. */
4522                 err = mark_chain_precision(env, value_regno);
4523                 if (err)
4524                         return err;
4525         }
4526         return 0;
4527 }
4528
4529 /* When register 'dst_regno' is assigned some values from stack[min_off,
4530  * max_off), we set the register's type according to the types of the
4531  * respective stack slots. If all the stack values are known to be zeros, then
4532  * so is the destination reg. Otherwise, the register is considered to be
4533  * SCALAR. This function does not deal with register filling; the caller must
4534  * ensure that all spilled registers in the stack range have been marked as
4535  * read.
4536  */
4537 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4538                                 /* func where src register points to */
4539                                 struct bpf_func_state *ptr_state,
4540                                 int min_off, int max_off, int dst_regno)
4541 {
4542         struct bpf_verifier_state *vstate = env->cur_state;
4543         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4544         int i, slot, spi;
4545         u8 *stype;
4546         int zeros = 0;
4547
4548         for (i = min_off; i < max_off; i++) {
4549                 slot = -i - 1;
4550                 spi = slot / BPF_REG_SIZE;
4551                 mark_stack_slot_scratched(env, spi);
4552                 stype = ptr_state->stack[spi].slot_type;
4553                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4554                         break;
4555                 zeros++;
4556         }
4557         if (zeros == max_off - min_off) {
4558                 /* any access_size read into register is zero extended,
4559                  * so the whole register == const_zero
4560                  */
4561                 __mark_reg_const_zero(&state->regs[dst_regno]);
4562                 /* backtracking doesn't support STACK_ZERO yet,
4563                  * so mark it precise here, so that later
4564                  * backtracking can stop here.
4565                  * Backtracking may not need this if this register
4566                  * doesn't participate in pointer adjustment.
4567                  * Forward propagation of precise flag is not
4568                  * necessary either. This mark is only to stop
4569                  * backtracking. Any register that contributed
4570                  * to const 0 was marked precise before spill.
4571                  */
4572                 state->regs[dst_regno].precise = true;
4573         } else {
4574                 /* have read misc data from the stack */
4575                 mark_reg_unknown(env, state->regs, dst_regno);
4576         }
4577         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4578 }
4579
4580 /* Read the stack at 'off' and put the results into the register indicated by
4581  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4582  * spilled reg.
4583  *
4584  * 'dst_regno' can be -1, meaning that the read value is not going to a
4585  * register.
4586  *
4587  * The access is assumed to be within the current stack bounds.
4588  */
4589 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4590                                       /* func where src register points to */
4591                                       struct bpf_func_state *reg_state,
4592                                       int off, int size, int dst_regno)
4593 {
4594         struct bpf_verifier_state *vstate = env->cur_state;
4595         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4596         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4597         struct bpf_reg_state *reg;
4598         u8 *stype, type;
4599
4600         stype = reg_state->stack[spi].slot_type;
4601         reg = &reg_state->stack[spi].spilled_ptr;
4602
4603         mark_stack_slot_scratched(env, spi);
4604
4605         if (is_spilled_reg(&reg_state->stack[spi])) {
4606                 u8 spill_size = 1;
4607
4608                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4609                         spill_size++;
4610
4611                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4612                         if (reg->type != SCALAR_VALUE) {
4613                                 verbose_linfo(env, env->insn_idx, "; ");
4614                                 verbose(env, "invalid size of register fill\n");
4615                                 return -EACCES;
4616                         }
4617
4618                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4619                         if (dst_regno < 0)
4620                                 return 0;
4621
4622                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4623                                 /* The earlier check_reg_arg() has decided the
4624                                  * subreg_def for this insn.  Save it first.
4625                                  */
4626                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4627
4628                                 copy_register_state(&state->regs[dst_regno], reg);
4629                                 state->regs[dst_regno].subreg_def = subreg_def;
4630                         } else {
4631                                 for (i = 0; i < size; i++) {
4632                                         type = stype[(slot - i) % BPF_REG_SIZE];
4633                                         if (type == STACK_SPILL)
4634                                                 continue;
4635                                         if (type == STACK_MISC)
4636                                                 continue;
4637                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4638                                                 continue;
4639                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4640                                                 off, i, size);
4641                                         return -EACCES;
4642                                 }
4643                                 mark_reg_unknown(env, state->regs, dst_regno);
4644                         }
4645                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4646                         return 0;
4647                 }
4648
4649                 if (dst_regno >= 0) {
4650                         /* restore register state from stack */
4651                         copy_register_state(&state->regs[dst_regno], reg);
4652                         /* mark reg as written since spilled pointer state likely
4653                          * has its liveness marks cleared by is_state_visited()
4654                          * which resets stack/reg liveness for state transitions
4655                          */
4656                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4657                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4658                         /* If dst_regno==-1, the caller is asking us whether
4659                          * it is acceptable to use this value as a SCALAR_VALUE
4660                          * (e.g. for XADD).
4661                          * We must not allow unprivileged callers to do that
4662                          * with spilled pointers.
4663                          */
4664                         verbose(env, "leaking pointer from stack off %d\n",
4665                                 off);
4666                         return -EACCES;
4667                 }
4668                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4669         } else {
4670                 for (i = 0; i < size; i++) {
4671                         type = stype[(slot - i) % BPF_REG_SIZE];
4672                         if (type == STACK_MISC)
4673                                 continue;
4674                         if (type == STACK_ZERO)
4675                                 continue;
4676                         if (type == STACK_INVALID && env->allow_uninit_stack)
4677                                 continue;
4678                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4679                                 off, i, size);
4680                         return -EACCES;
4681                 }
4682                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4683                 if (dst_regno >= 0)
4684                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4685         }
4686         return 0;
4687 }
4688
4689 enum bpf_access_src {
4690         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4691         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4692 };
4693
4694 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4695                                          int regno, int off, int access_size,
4696                                          bool zero_size_allowed,
4697                                          enum bpf_access_src type,
4698                                          struct bpf_call_arg_meta *meta);
4699
4700 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4701 {
4702         return cur_regs(env) + regno;
4703 }
4704
4705 /* Read the stack at 'ptr_regno + off' and put the result into the register
4706  * 'dst_regno'.
4707  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4708  * but not its variable offset.
4709  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4710  *
4711  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4712  * filling registers (i.e. reads of spilled register cannot be detected when
4713  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4714  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4715  * offset; for a fixed offset check_stack_read_fixed_off should be used
4716  * instead.
4717  */
4718 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4719                                     int ptr_regno, int off, int size, int dst_regno)
4720 {
4721         /* The state of the source register. */
4722         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4723         struct bpf_func_state *ptr_state = func(env, reg);
4724         int err;
4725         int min_off, max_off;
4726
4727         /* Note that we pass a NULL meta, so raw access will not be permitted.
4728          */
4729         err = check_stack_range_initialized(env, ptr_regno, off, size,
4730                                             false, ACCESS_DIRECT, NULL);
4731         if (err)
4732                 return err;
4733
4734         min_off = reg->smin_value + off;
4735         max_off = reg->smax_value + off;
4736         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4737         return 0;
4738 }
4739
4740 /* check_stack_read dispatches to check_stack_read_fixed_off or
4741  * check_stack_read_var_off.
4742  *
4743  * The caller must ensure that the offset falls within the allocated stack
4744  * bounds.
4745  *
4746  * 'dst_regno' is a register which will receive the value from the stack. It
4747  * can be -1, meaning that the read value is not going to a register.
4748  */
4749 static int check_stack_read(struct bpf_verifier_env *env,
4750                             int ptr_regno, int off, int size,
4751                             int dst_regno)
4752 {
4753         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4754         struct bpf_func_state *state = func(env, reg);
4755         int err;
4756         /* Some accesses are only permitted with a static offset. */
4757         bool var_off = !tnum_is_const(reg->var_off);
4758
4759         /* The offset is required to be static when reads don't go to a
4760          * register, in order to not leak pointers (see
4761          * check_stack_read_fixed_off).
4762          */
4763         if (dst_regno < 0 && var_off) {
4764                 char tn_buf[48];
4765
4766                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4767                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4768                         tn_buf, off, size);
4769                 return -EACCES;
4770         }
4771         /* Variable offset is prohibited for unprivileged mode for simplicity
4772          * since it requires corresponding support in Spectre masking for stack
4773          * ALU. See also retrieve_ptr_limit(). The check in
4774          * check_stack_access_for_ptr_arithmetic() called by
4775          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4776          * with variable offsets, therefore no check is required here. Further,
4777          * just checking it here would be insufficient as speculative stack
4778          * writes could still lead to unsafe speculative behaviour.
4779          */
4780         if (!var_off) {
4781                 off += reg->var_off.value;
4782                 err = check_stack_read_fixed_off(env, state, off, size,
4783                                                  dst_regno);
4784         } else {
4785                 /* Variable offset stack reads need more conservative handling
4786                  * than fixed offset ones. Note that dst_regno >= 0 on this
4787                  * branch.
4788                  */
4789                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4790                                                dst_regno);
4791         }
4792         return err;
4793 }
4794
4795
4796 /* check_stack_write dispatches to check_stack_write_fixed_off or
4797  * check_stack_write_var_off.
4798  *
4799  * 'ptr_regno' is the register used as a pointer into the stack.
4800  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4801  * 'value_regno' is the register whose value we're writing to the stack. It can
4802  * be -1, meaning that we're not writing from a register.
4803  *
4804  * The caller must ensure that the offset falls within the maximum stack size.
4805  */
4806 static int check_stack_write(struct bpf_verifier_env *env,
4807                              int ptr_regno, int off, int size,
4808                              int value_regno, int insn_idx)
4809 {
4810         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4811         struct bpf_func_state *state = func(env, reg);
4812         int err;
4813
4814         if (tnum_is_const(reg->var_off)) {
4815                 off += reg->var_off.value;
4816                 err = check_stack_write_fixed_off(env, state, off, size,
4817                                                   value_regno, insn_idx);
4818         } else {
4819                 /* Variable offset stack reads need more conservative handling
4820                  * than fixed offset ones.
4821                  */
4822                 err = check_stack_write_var_off(env, state,
4823                                                 ptr_regno, off, size,
4824                                                 value_regno, insn_idx);
4825         }
4826         return err;
4827 }
4828
4829 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4830                                  int off, int size, enum bpf_access_type type)
4831 {
4832         struct bpf_reg_state *regs = cur_regs(env);
4833         struct bpf_map *map = regs[regno].map_ptr;
4834         u32 cap = bpf_map_flags_to_cap(map);
4835
4836         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4837                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4838                         map->value_size, off, size);
4839                 return -EACCES;
4840         }
4841
4842         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4843                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4844                         map->value_size, off, size);
4845                 return -EACCES;
4846         }
4847
4848         return 0;
4849 }
4850
4851 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4852 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4853                               int off, int size, u32 mem_size,
4854                               bool zero_size_allowed)
4855 {
4856         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4857         struct bpf_reg_state *reg;
4858
4859         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4860                 return 0;
4861
4862         reg = &cur_regs(env)[regno];
4863         switch (reg->type) {
4864         case PTR_TO_MAP_KEY:
4865                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4866                         mem_size, off, size);
4867                 break;
4868         case PTR_TO_MAP_VALUE:
4869                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4870                         mem_size, off, size);
4871                 break;
4872         case PTR_TO_PACKET:
4873         case PTR_TO_PACKET_META:
4874         case PTR_TO_PACKET_END:
4875                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4876                         off, size, regno, reg->id, off, mem_size);
4877                 break;
4878         case PTR_TO_MEM:
4879         default:
4880                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4881                         mem_size, off, size);
4882         }
4883
4884         return -EACCES;
4885 }
4886
4887 /* check read/write into a memory region with possible variable offset */
4888 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4889                                    int off, int size, u32 mem_size,
4890                                    bool zero_size_allowed)
4891 {
4892         struct bpf_verifier_state *vstate = env->cur_state;
4893         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4894         struct bpf_reg_state *reg = &state->regs[regno];
4895         int err;
4896
4897         /* We may have adjusted the register pointing to memory region, so we
4898          * need to try adding each of min_value and max_value to off
4899          * to make sure our theoretical access will be safe.
4900          *
4901          * The minimum value is only important with signed
4902          * comparisons where we can't assume the floor of a
4903          * value is 0.  If we are using signed variables for our
4904          * index'es we need to make sure that whatever we use
4905          * will have a set floor within our range.
4906          */
4907         if (reg->smin_value < 0 &&
4908             (reg->smin_value == S64_MIN ||
4909              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4910               reg->smin_value + off < 0)) {
4911                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4912                         regno);
4913                 return -EACCES;
4914         }
4915         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4916                                  mem_size, zero_size_allowed);
4917         if (err) {
4918                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4919                         regno);
4920                 return err;
4921         }
4922
4923         /* If we haven't set a max value then we need to bail since we can't be
4924          * sure we won't do bad things.
4925          * If reg->umax_value + off could overflow, treat that as unbounded too.
4926          */
4927         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4928                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4929                         regno);
4930                 return -EACCES;
4931         }
4932         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4933                                  mem_size, zero_size_allowed);
4934         if (err) {
4935                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4936                         regno);
4937                 return err;
4938         }
4939
4940         return 0;
4941 }
4942
4943 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4944                                const struct bpf_reg_state *reg, int regno,
4945                                bool fixed_off_ok)
4946 {
4947         /* Access to this pointer-typed register or passing it to a helper
4948          * is only allowed in its original, unmodified form.
4949          */
4950
4951         if (reg->off < 0) {
4952                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4953                         reg_type_str(env, reg->type), regno, reg->off);
4954                 return -EACCES;
4955         }
4956
4957         if (!fixed_off_ok && reg->off) {
4958                 verbose(env, "dereference of modified %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 (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4964                 char tn_buf[48];
4965
4966                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4967                 verbose(env, "variable %s access var_off=%s disallowed\n",
4968                         reg_type_str(env, reg->type), tn_buf);
4969                 return -EACCES;
4970         }
4971
4972         return 0;
4973 }
4974
4975 int check_ptr_off_reg(struct bpf_verifier_env *env,
4976                       const struct bpf_reg_state *reg, int regno)
4977 {
4978         return __check_ptr_off_reg(env, reg, regno, false);
4979 }
4980
4981 static int map_kptr_match_type(struct bpf_verifier_env *env,
4982                                struct btf_field *kptr_field,
4983                                struct bpf_reg_state *reg, u32 regno)
4984 {
4985         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
4986         int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
4987         const char *reg_name = "";
4988
4989         /* Only unreferenced case accepts untrusted pointers */
4990         if (kptr_field->type == BPF_KPTR_UNREF)
4991                 perm_flags |= PTR_UNTRUSTED;
4992
4993         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
4994                 goto bad_type;
4995
4996         if (!btf_is_kernel(reg->btf)) {
4997                 verbose(env, "R%d must point to kernel BTF\n", regno);
4998                 return -EINVAL;
4999         }
5000         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5001         reg_name = btf_type_name(reg->btf, reg->btf_id);
5002
5003         /* For ref_ptr case, release function check should ensure we get one
5004          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5005          * normal store of unreferenced kptr, we must ensure var_off is zero.
5006          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5007          * reg->off and reg->ref_obj_id are not needed here.
5008          */
5009         if (__check_ptr_off_reg(env, reg, regno, true))
5010                 return -EACCES;
5011
5012         /* A full type match is needed, as BTF can be vmlinux or module BTF, and
5013          * we also need to take into account the reg->off.
5014          *
5015          * We want to support cases like:
5016          *
5017          * struct foo {
5018          *         struct bar br;
5019          *         struct baz bz;
5020          * };
5021          *
5022          * struct foo *v;
5023          * v = func();        // PTR_TO_BTF_ID
5024          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5025          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5026          *                    // first member type of struct after comparison fails
5027          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5028          *                    // to match type
5029          *
5030          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5031          * is zero. We must also ensure that btf_struct_ids_match does not walk
5032          * the struct to match type against first member of struct, i.e. reject
5033          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5034          * strict mode to true for type match.
5035          */
5036         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5037                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5038                                   kptr_field->type == BPF_KPTR_REF))
5039                 goto bad_type;
5040         return 0;
5041 bad_type:
5042         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5043                 reg_type_str(env, reg->type), reg_name);
5044         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5045         if (kptr_field->type == BPF_KPTR_UNREF)
5046                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5047                         targ_name);
5048         else
5049                 verbose(env, "\n");
5050         return -EINVAL;
5051 }
5052
5053 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5054  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5055  */
5056 static bool in_rcu_cs(struct bpf_verifier_env *env)
5057 {
5058         return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable;
5059 }
5060
5061 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5062 BTF_SET_START(rcu_protected_types)
5063 BTF_ID(struct, prog_test_ref_kfunc)
5064 BTF_ID(struct, cgroup)
5065 BTF_ID(struct, bpf_cpumask)
5066 BTF_ID(struct, task_struct)
5067 BTF_SET_END(rcu_protected_types)
5068
5069 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5070 {
5071         if (!btf_is_kernel(btf))
5072                 return false;
5073         return btf_id_set_contains(&rcu_protected_types, btf_id);
5074 }
5075
5076 static bool rcu_safe_kptr(const struct btf_field *field)
5077 {
5078         const struct btf_field_kptr *kptr = &field->kptr;
5079
5080         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5081 }
5082
5083 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5084                                  int value_regno, int insn_idx,
5085                                  struct btf_field *kptr_field)
5086 {
5087         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5088         int class = BPF_CLASS(insn->code);
5089         struct bpf_reg_state *val_reg;
5090
5091         /* Things we already checked for in check_map_access and caller:
5092          *  - Reject cases where variable offset may touch kptr
5093          *  - size of access (must be BPF_DW)
5094          *  - tnum_is_const(reg->var_off)
5095          *  - kptr_field->offset == off + reg->var_off.value
5096          */
5097         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5098         if (BPF_MODE(insn->code) != BPF_MEM) {
5099                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5100                 return -EACCES;
5101         }
5102
5103         /* We only allow loading referenced kptr, since it will be marked as
5104          * untrusted, similar to unreferenced kptr.
5105          */
5106         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5107                 verbose(env, "store to referenced kptr disallowed\n");
5108                 return -EACCES;
5109         }
5110
5111         if (class == BPF_LDX) {
5112                 val_reg = reg_state(env, value_regno);
5113                 /* We can simply mark the value_regno receiving the pointer
5114                  * value from map as PTR_TO_BTF_ID, with the correct type.
5115                  */
5116                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5117                                 kptr_field->kptr.btf_id,
5118                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5119                                 PTR_MAYBE_NULL | MEM_RCU :
5120                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5121                 /* For mark_ptr_or_null_reg */
5122                 val_reg->id = ++env->id_gen;
5123         } else if (class == BPF_STX) {
5124                 val_reg = reg_state(env, value_regno);
5125                 if (!register_is_null(val_reg) &&
5126                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5127                         return -EACCES;
5128         } else if (class == BPF_ST) {
5129                 if (insn->imm) {
5130                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5131                                 kptr_field->offset);
5132                         return -EACCES;
5133                 }
5134         } else {
5135                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5136                 return -EACCES;
5137         }
5138         return 0;
5139 }
5140
5141 /* check read/write into a map element with possible variable offset */
5142 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5143                             int off, int size, bool zero_size_allowed,
5144                             enum bpf_access_src src)
5145 {
5146         struct bpf_verifier_state *vstate = env->cur_state;
5147         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5148         struct bpf_reg_state *reg = &state->regs[regno];
5149         struct bpf_map *map = reg->map_ptr;
5150         struct btf_record *rec;
5151         int err, i;
5152
5153         err = check_mem_region_access(env, regno, off, size, map->value_size,
5154                                       zero_size_allowed);
5155         if (err)
5156                 return err;
5157
5158         if (IS_ERR_OR_NULL(map->record))
5159                 return 0;
5160         rec = map->record;
5161         for (i = 0; i < rec->cnt; i++) {
5162                 struct btf_field *field = &rec->fields[i];
5163                 u32 p = field->offset;
5164
5165                 /* If any part of a field  can be touched by load/store, reject
5166                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5167                  * it is sufficient to check x1 < y2 && y1 < x2.
5168                  */
5169                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5170                     p < reg->umax_value + off + size) {
5171                         switch (field->type) {
5172                         case BPF_KPTR_UNREF:
5173                         case BPF_KPTR_REF:
5174                                 if (src != ACCESS_DIRECT) {
5175                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5176                                         return -EACCES;
5177                                 }
5178                                 if (!tnum_is_const(reg->var_off)) {
5179                                         verbose(env, "kptr access cannot have variable offset\n");
5180                                         return -EACCES;
5181                                 }
5182                                 if (p != off + reg->var_off.value) {
5183                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5184                                                 p, off + reg->var_off.value);
5185                                         return -EACCES;
5186                                 }
5187                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5188                                         verbose(env, "kptr access size must be BPF_DW\n");
5189                                         return -EACCES;
5190                                 }
5191                                 break;
5192                         default:
5193                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5194                                         btf_field_type_name(field->type));
5195                                 return -EACCES;
5196                         }
5197                 }
5198         }
5199         return 0;
5200 }
5201
5202 #define MAX_PACKET_OFF 0xffff
5203
5204 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5205                                        const struct bpf_call_arg_meta *meta,
5206                                        enum bpf_access_type t)
5207 {
5208         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5209
5210         switch (prog_type) {
5211         /* Program types only with direct read access go here! */
5212         case BPF_PROG_TYPE_LWT_IN:
5213         case BPF_PROG_TYPE_LWT_OUT:
5214         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5215         case BPF_PROG_TYPE_SK_REUSEPORT:
5216         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5217         case BPF_PROG_TYPE_CGROUP_SKB:
5218                 if (t == BPF_WRITE)
5219                         return false;
5220                 fallthrough;
5221
5222         /* Program types with direct read + write access go here! */
5223         case BPF_PROG_TYPE_SCHED_CLS:
5224         case BPF_PROG_TYPE_SCHED_ACT:
5225         case BPF_PROG_TYPE_XDP:
5226         case BPF_PROG_TYPE_LWT_XMIT:
5227         case BPF_PROG_TYPE_SK_SKB:
5228         case BPF_PROG_TYPE_SK_MSG:
5229                 if (meta)
5230                         return meta->pkt_access;
5231
5232                 env->seen_direct_write = true;
5233                 return true;
5234
5235         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5236                 if (t == BPF_WRITE)
5237                         env->seen_direct_write = true;
5238
5239                 return true;
5240
5241         default:
5242                 return false;
5243         }
5244 }
5245
5246 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5247                                int size, bool zero_size_allowed)
5248 {
5249         struct bpf_reg_state *regs = cur_regs(env);
5250         struct bpf_reg_state *reg = &regs[regno];
5251         int err;
5252
5253         /* We may have added a variable offset to the packet pointer; but any
5254          * reg->range we have comes after that.  We are only checking the fixed
5255          * offset.
5256          */
5257
5258         /* We don't allow negative numbers, because we aren't tracking enough
5259          * detail to prove they're safe.
5260          */
5261         if (reg->smin_value < 0) {
5262                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5263                         regno);
5264                 return -EACCES;
5265         }
5266
5267         err = reg->range < 0 ? -EINVAL :
5268               __check_mem_access(env, regno, off, size, reg->range,
5269                                  zero_size_allowed);
5270         if (err) {
5271                 verbose(env, "R%d offset is outside of the packet\n", regno);
5272                 return err;
5273         }
5274
5275         /* __check_mem_access has made sure "off + size - 1" is within u16.
5276          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5277          * otherwise find_good_pkt_pointers would have refused to set range info
5278          * that __check_mem_access would have rejected this pkt access.
5279          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5280          */
5281         env->prog->aux->max_pkt_offset =
5282                 max_t(u32, env->prog->aux->max_pkt_offset,
5283                       off + reg->umax_value + size - 1);
5284
5285         return err;
5286 }
5287
5288 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5289 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5290                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5291                             struct btf **btf, u32 *btf_id)
5292 {
5293         struct bpf_insn_access_aux info = {
5294                 .reg_type = *reg_type,
5295                 .log = &env->log,
5296         };
5297
5298         if (env->ops->is_valid_access &&
5299             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5300                 /* A non zero info.ctx_field_size indicates that this field is a
5301                  * candidate for later verifier transformation to load the whole
5302                  * field and then apply a mask when accessed with a narrower
5303                  * access than actual ctx access size. A zero info.ctx_field_size
5304                  * will only allow for whole field access and rejects any other
5305                  * type of narrower access.
5306                  */
5307                 *reg_type = info.reg_type;
5308
5309                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5310                         *btf = info.btf;
5311                         *btf_id = info.btf_id;
5312                 } else {
5313                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5314                 }
5315                 /* remember the offset of last byte accessed in ctx */
5316                 if (env->prog->aux->max_ctx_offset < off + size)
5317                         env->prog->aux->max_ctx_offset = off + size;
5318                 return 0;
5319         }
5320
5321         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5322         return -EACCES;
5323 }
5324
5325 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5326                                   int size)
5327 {
5328         if (size < 0 || off < 0 ||
5329             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5330                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5331                         off, size);
5332                 return -EACCES;
5333         }
5334         return 0;
5335 }
5336
5337 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5338                              u32 regno, int off, int size,
5339                              enum bpf_access_type t)
5340 {
5341         struct bpf_reg_state *regs = cur_regs(env);
5342         struct bpf_reg_state *reg = &regs[regno];
5343         struct bpf_insn_access_aux info = {};
5344         bool valid;
5345
5346         if (reg->smin_value < 0) {
5347                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5348                         regno);
5349                 return -EACCES;
5350         }
5351
5352         switch (reg->type) {
5353         case PTR_TO_SOCK_COMMON:
5354                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5355                 break;
5356         case PTR_TO_SOCKET:
5357                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5358                 break;
5359         case PTR_TO_TCP_SOCK:
5360                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5361                 break;
5362         case PTR_TO_XDP_SOCK:
5363                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5364                 break;
5365         default:
5366                 valid = false;
5367         }
5368
5369
5370         if (valid) {
5371                 env->insn_aux_data[insn_idx].ctx_field_size =
5372                         info.ctx_field_size;
5373                 return 0;
5374         }
5375
5376         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5377                 regno, reg_type_str(env, reg->type), off, size);
5378
5379         return -EACCES;
5380 }
5381
5382 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5383 {
5384         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5385 }
5386
5387 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5388 {
5389         const struct bpf_reg_state *reg = reg_state(env, regno);
5390
5391         return reg->type == PTR_TO_CTX;
5392 }
5393
5394 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5395 {
5396         const struct bpf_reg_state *reg = reg_state(env, regno);
5397
5398         return type_is_sk_pointer(reg->type);
5399 }
5400
5401 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5402 {
5403         const struct bpf_reg_state *reg = reg_state(env, regno);
5404
5405         return type_is_pkt_pointer(reg->type);
5406 }
5407
5408 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5409 {
5410         const struct bpf_reg_state *reg = reg_state(env, regno);
5411
5412         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5413         return reg->type == PTR_TO_FLOW_KEYS;
5414 }
5415
5416 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5417 #ifdef CONFIG_NET
5418         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5419         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5420         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5421 #endif
5422         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5423 };
5424
5425 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5426 {
5427         /* A referenced register is always trusted. */
5428         if (reg->ref_obj_id)
5429                 return true;
5430
5431         /* Types listed in the reg2btf_ids are always trusted */
5432         if (reg2btf_ids[base_type(reg->type)])
5433                 return true;
5434
5435         /* If a register is not referenced, it is trusted if it has the
5436          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5437          * other type modifiers may be safe, but we elect to take an opt-in
5438          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5439          * not.
5440          *
5441          * Eventually, we should make PTR_TRUSTED the single source of truth
5442          * for whether a register is trusted.
5443          */
5444         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5445                !bpf_type_has_unsafe_modifiers(reg->type);
5446 }
5447
5448 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5449 {
5450         return reg->type & MEM_RCU;
5451 }
5452
5453 static void clear_trusted_flags(enum bpf_type_flag *flag)
5454 {
5455         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5456 }
5457
5458 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5459                                    const struct bpf_reg_state *reg,
5460                                    int off, int size, bool strict)
5461 {
5462         struct tnum reg_off;
5463         int ip_align;
5464
5465         /* Byte size accesses are always allowed. */
5466         if (!strict || size == 1)
5467                 return 0;
5468
5469         /* For platforms that do not have a Kconfig enabling
5470          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5471          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5472          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5473          * to this code only in strict mode where we want to emulate
5474          * the NET_IP_ALIGN==2 checking.  Therefore use an
5475          * unconditional IP align value of '2'.
5476          */
5477         ip_align = 2;
5478
5479         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5480         if (!tnum_is_aligned(reg_off, size)) {
5481                 char tn_buf[48];
5482
5483                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5484                 verbose(env,
5485                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5486                         ip_align, tn_buf, reg->off, off, size);
5487                 return -EACCES;
5488         }
5489
5490         return 0;
5491 }
5492
5493 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5494                                        const struct bpf_reg_state *reg,
5495                                        const char *pointer_desc,
5496                                        int off, int size, bool strict)
5497 {
5498         struct tnum reg_off;
5499
5500         /* Byte size accesses are always allowed. */
5501         if (!strict || size == 1)
5502                 return 0;
5503
5504         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5505         if (!tnum_is_aligned(reg_off, size)) {
5506                 char tn_buf[48];
5507
5508                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5509                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5510                         pointer_desc, tn_buf, reg->off, off, size);
5511                 return -EACCES;
5512         }
5513
5514         return 0;
5515 }
5516
5517 static int check_ptr_alignment(struct bpf_verifier_env *env,
5518                                const struct bpf_reg_state *reg, int off,
5519                                int size, bool strict_alignment_once)
5520 {
5521         bool strict = env->strict_alignment || strict_alignment_once;
5522         const char *pointer_desc = "";
5523
5524         switch (reg->type) {
5525         case PTR_TO_PACKET:
5526         case PTR_TO_PACKET_META:
5527                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5528                  * right in front, treat it the very same way.
5529                  */
5530                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5531         case PTR_TO_FLOW_KEYS:
5532                 pointer_desc = "flow keys ";
5533                 break;
5534         case PTR_TO_MAP_KEY:
5535                 pointer_desc = "key ";
5536                 break;
5537         case PTR_TO_MAP_VALUE:
5538                 pointer_desc = "value ";
5539                 break;
5540         case PTR_TO_CTX:
5541                 pointer_desc = "context ";
5542                 break;
5543         case PTR_TO_STACK:
5544                 pointer_desc = "stack ";
5545                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5546                  * and check_stack_read_fixed_off() relies on stack accesses being
5547                  * aligned.
5548                  */
5549                 strict = true;
5550                 break;
5551         case PTR_TO_SOCKET:
5552                 pointer_desc = "sock ";
5553                 break;
5554         case PTR_TO_SOCK_COMMON:
5555                 pointer_desc = "sock_common ";
5556                 break;
5557         case PTR_TO_TCP_SOCK:
5558                 pointer_desc = "tcp_sock ";
5559                 break;
5560         case PTR_TO_XDP_SOCK:
5561                 pointer_desc = "xdp_sock ";
5562                 break;
5563         default:
5564                 break;
5565         }
5566         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5567                                            strict);
5568 }
5569
5570 static int update_stack_depth(struct bpf_verifier_env *env,
5571                               const struct bpf_func_state *func,
5572                               int off)
5573 {
5574         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5575
5576         if (stack >= -off)
5577                 return 0;
5578
5579         /* update known max for given subprogram */
5580         env->subprog_info[func->subprogno].stack_depth = -off;
5581         return 0;
5582 }
5583
5584 /* starting from main bpf function walk all instructions of the function
5585  * and recursively walk all callees that given function can call.
5586  * Ignore jump and exit insns.
5587  * Since recursion is prevented by check_cfg() this algorithm
5588  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5589  */
5590 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5591 {
5592         struct bpf_subprog_info *subprog = env->subprog_info;
5593         struct bpf_insn *insn = env->prog->insnsi;
5594         int depth = 0, frame = 0, i, subprog_end;
5595         bool tail_call_reachable = false;
5596         int ret_insn[MAX_CALL_FRAMES];
5597         int ret_prog[MAX_CALL_FRAMES];
5598         int j;
5599
5600         i = subprog[idx].start;
5601 process_func:
5602         /* protect against potential stack overflow that might happen when
5603          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5604          * depth for such case down to 256 so that the worst case scenario
5605          * would result in 8k stack size (32 which is tailcall limit * 256 =
5606          * 8k).
5607          *
5608          * To get the idea what might happen, see an example:
5609          * func1 -> sub rsp, 128
5610          *  subfunc1 -> sub rsp, 256
5611          *  tailcall1 -> add rsp, 256
5612          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5613          *   subfunc2 -> sub rsp, 64
5614          *   subfunc22 -> sub rsp, 128
5615          *   tailcall2 -> add rsp, 128
5616          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5617          *
5618          * tailcall will unwind the current stack frame but it will not get rid
5619          * of caller's stack as shown on the example above.
5620          */
5621         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5622                 verbose(env,
5623                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5624                         depth);
5625                 return -EACCES;
5626         }
5627         /* round up to 32-bytes, since this is granularity
5628          * of interpreter stack size
5629          */
5630         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5631         if (depth > MAX_BPF_STACK) {
5632                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5633                         frame + 1, depth);
5634                 return -EACCES;
5635         }
5636 continue_func:
5637         subprog_end = subprog[idx + 1].start;
5638         for (; i < subprog_end; i++) {
5639                 int next_insn, sidx;
5640
5641                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5642                         continue;
5643                 /* remember insn and function to return to */
5644                 ret_insn[frame] = i + 1;
5645                 ret_prog[frame] = idx;
5646
5647                 /* find the callee */
5648                 next_insn = i + insn[i].imm + 1;
5649                 sidx = find_subprog(env, next_insn);
5650                 if (sidx < 0) {
5651                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5652                                   next_insn);
5653                         return -EFAULT;
5654                 }
5655                 if (subprog[sidx].is_async_cb) {
5656                         if (subprog[sidx].has_tail_call) {
5657                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5658                                 return -EFAULT;
5659                         }
5660                         /* async callbacks don't increase bpf prog stack size unless called directly */
5661                         if (!bpf_pseudo_call(insn + i))
5662                                 continue;
5663                 }
5664                 i = next_insn;
5665                 idx = sidx;
5666
5667                 if (subprog[idx].has_tail_call)
5668                         tail_call_reachable = true;
5669
5670                 frame++;
5671                 if (frame >= MAX_CALL_FRAMES) {
5672                         verbose(env, "the call stack of %d frames is too deep !\n",
5673                                 frame);
5674                         return -E2BIG;
5675                 }
5676                 goto process_func;
5677         }
5678         /* if tail call got detected across bpf2bpf calls then mark each of the
5679          * currently present subprog frames as tail call reachable subprogs;
5680          * this info will be utilized by JIT so that we will be preserving the
5681          * tail call counter throughout bpf2bpf calls combined with tailcalls
5682          */
5683         if (tail_call_reachable)
5684                 for (j = 0; j < frame; j++)
5685                         subprog[ret_prog[j]].tail_call_reachable = true;
5686         if (subprog[0].tail_call_reachable)
5687                 env->prog->aux->tail_call_reachable = true;
5688
5689         /* end of for() loop means the last insn of the 'subprog'
5690          * was reached. Doesn't matter whether it was JA or EXIT
5691          */
5692         if (frame == 0)
5693                 return 0;
5694         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5695         frame--;
5696         i = ret_insn[frame];
5697         idx = ret_prog[frame];
5698         goto continue_func;
5699 }
5700
5701 static int check_max_stack_depth(struct bpf_verifier_env *env)
5702 {
5703         struct bpf_subprog_info *si = env->subprog_info;
5704         int ret;
5705
5706         for (int i = 0; i < env->subprog_cnt; i++) {
5707                 if (!i || si[i].is_async_cb) {
5708                         ret = check_max_stack_depth_subprog(env, i);
5709                         if (ret < 0)
5710                                 return ret;
5711                 }
5712                 continue;
5713         }
5714         return 0;
5715 }
5716
5717 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5718 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5719                                   const struct bpf_insn *insn, int idx)
5720 {
5721         int start = idx + insn->imm + 1, subprog;
5722
5723         subprog = find_subprog(env, start);
5724         if (subprog < 0) {
5725                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5726                           start);
5727                 return -EFAULT;
5728         }
5729         return env->subprog_info[subprog].stack_depth;
5730 }
5731 #endif
5732
5733 static int __check_buffer_access(struct bpf_verifier_env *env,
5734                                  const char *buf_info,
5735                                  const struct bpf_reg_state *reg,
5736                                  int regno, int off, int size)
5737 {
5738         if (off < 0) {
5739                 verbose(env,
5740                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5741                         regno, buf_info, off, size);
5742                 return -EACCES;
5743         }
5744         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5745                 char tn_buf[48];
5746
5747                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5748                 verbose(env,
5749                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5750                         regno, off, tn_buf);
5751                 return -EACCES;
5752         }
5753
5754         return 0;
5755 }
5756
5757 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5758                                   const struct bpf_reg_state *reg,
5759                                   int regno, int off, int size)
5760 {
5761         int err;
5762
5763         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5764         if (err)
5765                 return err;
5766
5767         if (off + size > env->prog->aux->max_tp_access)
5768                 env->prog->aux->max_tp_access = off + size;
5769
5770         return 0;
5771 }
5772
5773 static int check_buffer_access(struct bpf_verifier_env *env,
5774                                const struct bpf_reg_state *reg,
5775                                int regno, int off, int size,
5776                                bool zero_size_allowed,
5777                                u32 *max_access)
5778 {
5779         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5780         int err;
5781
5782         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5783         if (err)
5784                 return err;
5785
5786         if (off + size > *max_access)
5787                 *max_access = off + size;
5788
5789         return 0;
5790 }
5791
5792 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5793 static void zext_32_to_64(struct bpf_reg_state *reg)
5794 {
5795         reg->var_off = tnum_subreg(reg->var_off);
5796         __reg_assign_32_into_64(reg);
5797 }
5798
5799 /* truncate register to smaller size (in bytes)
5800  * must be called with size < BPF_REG_SIZE
5801  */
5802 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5803 {
5804         u64 mask;
5805
5806         /* clear high bits in bit representation */
5807         reg->var_off = tnum_cast(reg->var_off, size);
5808
5809         /* fix arithmetic bounds */
5810         mask = ((u64)1 << (size * 8)) - 1;
5811         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5812                 reg->umin_value &= mask;
5813                 reg->umax_value &= mask;
5814         } else {
5815                 reg->umin_value = 0;
5816                 reg->umax_value = mask;
5817         }
5818         reg->smin_value = reg->umin_value;
5819         reg->smax_value = reg->umax_value;
5820
5821         /* If size is smaller than 32bit register the 32bit register
5822          * values are also truncated so we push 64-bit bounds into
5823          * 32-bit bounds. Above were truncated < 32-bits already.
5824          */
5825         if (size >= 4)
5826                 return;
5827         __reg_combine_64_into_32(reg);
5828 }
5829
5830 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5831 {
5832         if (size == 1) {
5833                 reg->smin_value = reg->s32_min_value = S8_MIN;
5834                 reg->smax_value = reg->s32_max_value = S8_MAX;
5835         } else if (size == 2) {
5836                 reg->smin_value = reg->s32_min_value = S16_MIN;
5837                 reg->smax_value = reg->s32_max_value = S16_MAX;
5838         } else {
5839                 /* size == 4 */
5840                 reg->smin_value = reg->s32_min_value = S32_MIN;
5841                 reg->smax_value = reg->s32_max_value = S32_MAX;
5842         }
5843         reg->umin_value = reg->u32_min_value = 0;
5844         reg->umax_value = U64_MAX;
5845         reg->u32_max_value = U32_MAX;
5846         reg->var_off = tnum_unknown;
5847 }
5848
5849 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5850 {
5851         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5852         u64 top_smax_value, top_smin_value;
5853         u64 num_bits = size * 8;
5854
5855         if (tnum_is_const(reg->var_off)) {
5856                 u64_cval = reg->var_off.value;
5857                 if (size == 1)
5858                         reg->var_off = tnum_const((s8)u64_cval);
5859                 else if (size == 2)
5860                         reg->var_off = tnum_const((s16)u64_cval);
5861                 else
5862                         /* size == 4 */
5863                         reg->var_off = tnum_const((s32)u64_cval);
5864
5865                 u64_cval = reg->var_off.value;
5866                 reg->smax_value = reg->smin_value = u64_cval;
5867                 reg->umax_value = reg->umin_value = u64_cval;
5868                 reg->s32_max_value = reg->s32_min_value = u64_cval;
5869                 reg->u32_max_value = reg->u32_min_value = u64_cval;
5870                 return;
5871         }
5872
5873         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5874         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5875
5876         if (top_smax_value != top_smin_value)
5877                 goto out;
5878
5879         /* find the s64_min and s64_min after sign extension */
5880         if (size == 1) {
5881                 init_s64_max = (s8)reg->smax_value;
5882                 init_s64_min = (s8)reg->smin_value;
5883         } else if (size == 2) {
5884                 init_s64_max = (s16)reg->smax_value;
5885                 init_s64_min = (s16)reg->smin_value;
5886         } else {
5887                 init_s64_max = (s32)reg->smax_value;
5888                 init_s64_min = (s32)reg->smin_value;
5889         }
5890
5891         s64_max = max(init_s64_max, init_s64_min);
5892         s64_min = min(init_s64_max, init_s64_min);
5893
5894         /* both of s64_max/s64_min positive or negative */
5895         if (s64_max >= 0 == s64_min >= 0) {
5896                 reg->smin_value = reg->s32_min_value = s64_min;
5897                 reg->smax_value = reg->s32_max_value = s64_max;
5898                 reg->umin_value = reg->u32_min_value = s64_min;
5899                 reg->umax_value = reg->u32_max_value = s64_max;
5900                 reg->var_off = tnum_range(s64_min, s64_max);
5901                 return;
5902         }
5903
5904 out:
5905         set_sext64_default_val(reg, size);
5906 }
5907
5908 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5909 {
5910         if (size == 1) {
5911                 reg->s32_min_value = S8_MIN;
5912                 reg->s32_max_value = S8_MAX;
5913         } else {
5914                 /* size == 2 */
5915                 reg->s32_min_value = S16_MIN;
5916                 reg->s32_max_value = S16_MAX;
5917         }
5918         reg->u32_min_value = 0;
5919         reg->u32_max_value = U32_MAX;
5920 }
5921
5922 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5923 {
5924         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5925         u32 top_smax_value, top_smin_value;
5926         u32 num_bits = size * 8;
5927
5928         if (tnum_is_const(reg->var_off)) {
5929                 u32_val = reg->var_off.value;
5930                 if (size == 1)
5931                         reg->var_off = tnum_const((s8)u32_val);
5932                 else
5933                         reg->var_off = tnum_const((s16)u32_val);
5934
5935                 u32_val = reg->var_off.value;
5936                 reg->s32_min_value = reg->s32_max_value = u32_val;
5937                 reg->u32_min_value = reg->u32_max_value = u32_val;
5938                 return;
5939         }
5940
5941         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5942         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5943
5944         if (top_smax_value != top_smin_value)
5945                 goto out;
5946
5947         /* find the s32_min and s32_min after sign extension */
5948         if (size == 1) {
5949                 init_s32_max = (s8)reg->s32_max_value;
5950                 init_s32_min = (s8)reg->s32_min_value;
5951         } else {
5952                 /* size == 2 */
5953                 init_s32_max = (s16)reg->s32_max_value;
5954                 init_s32_min = (s16)reg->s32_min_value;
5955         }
5956         s32_max = max(init_s32_max, init_s32_min);
5957         s32_min = min(init_s32_max, init_s32_min);
5958
5959         if (s32_min >= 0 == s32_max >= 0) {
5960                 reg->s32_min_value = s32_min;
5961                 reg->s32_max_value = s32_max;
5962                 reg->u32_min_value = (u32)s32_min;
5963                 reg->u32_max_value = (u32)s32_max;
5964                 return;
5965         }
5966
5967 out:
5968         set_sext32_default_val(reg, size);
5969 }
5970
5971 static bool bpf_map_is_rdonly(const struct bpf_map *map)
5972 {
5973         /* A map is considered read-only if the following condition are true:
5974          *
5975          * 1) BPF program side cannot change any of the map content. The
5976          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
5977          *    and was set at map creation time.
5978          * 2) The map value(s) have been initialized from user space by a
5979          *    loader and then "frozen", such that no new map update/delete
5980          *    operations from syscall side are possible for the rest of
5981          *    the map's lifetime from that point onwards.
5982          * 3) Any parallel/pending map update/delete operations from syscall
5983          *    side have been completed. Only after that point, it's safe to
5984          *    assume that map value(s) are immutable.
5985          */
5986         return (map->map_flags & BPF_F_RDONLY_PROG) &&
5987                READ_ONCE(map->frozen) &&
5988                !bpf_map_write_active(map);
5989 }
5990
5991 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
5992                                bool is_ldsx)
5993 {
5994         void *ptr;
5995         u64 addr;
5996         int err;
5997
5998         err = map->ops->map_direct_value_addr(map, &addr, off);
5999         if (err)
6000                 return err;
6001         ptr = (void *)(long)addr + off;
6002
6003         switch (size) {
6004         case sizeof(u8):
6005                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6006                 break;
6007         case sizeof(u16):
6008                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6009                 break;
6010         case sizeof(u32):
6011                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6012                 break;
6013         case sizeof(u64):
6014                 *val = *(u64 *)ptr;
6015                 break;
6016         default:
6017                 return -EINVAL;
6018         }
6019         return 0;
6020 }
6021
6022 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6023 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6024 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6025
6026 /*
6027  * Allow list few fields as RCU trusted or full trusted.
6028  * This logic doesn't allow mix tagging and will be removed once GCC supports
6029  * btf_type_tag.
6030  */
6031
6032 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6033 BTF_TYPE_SAFE_RCU(struct task_struct) {
6034         const cpumask_t *cpus_ptr;
6035         struct css_set __rcu *cgroups;
6036         struct task_struct __rcu *real_parent;
6037         struct task_struct *group_leader;
6038 };
6039
6040 BTF_TYPE_SAFE_RCU(struct cgroup) {
6041         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6042         struct kernfs_node *kn;
6043 };
6044
6045 BTF_TYPE_SAFE_RCU(struct css_set) {
6046         struct cgroup *dfl_cgrp;
6047 };
6048
6049 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6050 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6051         struct file __rcu *exe_file;
6052 };
6053
6054 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6055  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6056  */
6057 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6058         struct sock *sk;
6059 };
6060
6061 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6062         struct sock *sk;
6063 };
6064
6065 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6066 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6067         struct seq_file *seq;
6068 };
6069
6070 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6071         struct bpf_iter_meta *meta;
6072         struct task_struct *task;
6073 };
6074
6075 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6076         struct file *file;
6077 };
6078
6079 BTF_TYPE_SAFE_TRUSTED(struct file) {
6080         struct inode *f_inode;
6081 };
6082
6083 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6084         /* no negative dentry-s in places where bpf can see it */
6085         struct inode *d_inode;
6086 };
6087
6088 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6089         struct sock *sk;
6090 };
6091
6092 static bool type_is_rcu(struct bpf_verifier_env *env,
6093                         struct bpf_reg_state *reg,
6094                         const char *field_name, u32 btf_id)
6095 {
6096         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6097         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6098         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6099
6100         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6101 }
6102
6103 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6104                                 struct bpf_reg_state *reg,
6105                                 const char *field_name, u32 btf_id)
6106 {
6107         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6108         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6109         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6110
6111         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6112 }
6113
6114 static bool type_is_trusted(struct bpf_verifier_env *env,
6115                             struct bpf_reg_state *reg,
6116                             const char *field_name, u32 btf_id)
6117 {
6118         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6119         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6120         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6121         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6122         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6123         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6124
6125         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6126 }
6127
6128 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6129                                    struct bpf_reg_state *regs,
6130                                    int regno, int off, int size,
6131                                    enum bpf_access_type atype,
6132                                    int value_regno)
6133 {
6134         struct bpf_reg_state *reg = regs + regno;
6135         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6136         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6137         const char *field_name = NULL;
6138         enum bpf_type_flag flag = 0;
6139         u32 btf_id = 0;
6140         int ret;
6141
6142         if (!env->allow_ptr_leaks) {
6143                 verbose(env,
6144                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6145                         tname);
6146                 return -EPERM;
6147         }
6148         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6149                 verbose(env,
6150                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6151                         tname);
6152                 return -EINVAL;
6153         }
6154         if (off < 0) {
6155                 verbose(env,
6156                         "R%d is ptr_%s invalid negative access: off=%d\n",
6157                         regno, tname, off);
6158                 return -EACCES;
6159         }
6160         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6161                 char tn_buf[48];
6162
6163                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6164                 verbose(env,
6165                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6166                         regno, tname, off, tn_buf);
6167                 return -EACCES;
6168         }
6169
6170         if (reg->type & MEM_USER) {
6171                 verbose(env,
6172                         "R%d is ptr_%s access user memory: off=%d\n",
6173                         regno, tname, off);
6174                 return -EACCES;
6175         }
6176
6177         if (reg->type & MEM_PERCPU) {
6178                 verbose(env,
6179                         "R%d is ptr_%s access percpu memory: off=%d\n",
6180                         regno, tname, off);
6181                 return -EACCES;
6182         }
6183
6184         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6185                 if (!btf_is_kernel(reg->btf)) {
6186                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6187                         return -EFAULT;
6188                 }
6189                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6190         } else {
6191                 /* Writes are permitted with default btf_struct_access for
6192                  * program allocated objects (which always have ref_obj_id > 0),
6193                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6194                  */
6195                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6196                         verbose(env, "only read is supported\n");
6197                         return -EACCES;
6198                 }
6199
6200                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6201                     !reg->ref_obj_id) {
6202                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6203                         return -EFAULT;
6204                 }
6205
6206                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6207         }
6208
6209         if (ret < 0)
6210                 return ret;
6211
6212         if (ret != PTR_TO_BTF_ID) {
6213                 /* just mark; */
6214
6215         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6216                 /* If this is an untrusted pointer, all pointers formed by walking it
6217                  * also inherit the untrusted flag.
6218                  */
6219                 flag = PTR_UNTRUSTED;
6220
6221         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6222                 /* By default any pointer obtained from walking a trusted pointer is no
6223                  * longer trusted, unless the field being accessed has explicitly been
6224                  * marked as inheriting its parent's state of trust (either full or RCU).
6225                  * For example:
6226                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6227                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6228                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6229                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6230                  *
6231                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6232                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6233                  */
6234                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6235                         flag |= PTR_TRUSTED;
6236                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6237                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6238                                 /* ignore __rcu tag and mark it MEM_RCU */
6239                                 flag |= MEM_RCU;
6240                         } else if (flag & MEM_RCU ||
6241                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6242                                 /* __rcu tagged pointers can be NULL */
6243                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6244
6245                                 /* We always trust them */
6246                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6247                                     flag & PTR_UNTRUSTED)
6248                                         flag &= ~PTR_UNTRUSTED;
6249                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6250                                 /* keep as-is */
6251                         } else {
6252                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6253                                 clear_trusted_flags(&flag);
6254                         }
6255                 } else {
6256                         /*
6257                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6258                          * aggressively mark as untrusted otherwise such
6259                          * pointers will be plain PTR_TO_BTF_ID without flags
6260                          * and will be allowed to be passed into helpers for
6261                          * compat reasons.
6262                          */
6263                         flag = PTR_UNTRUSTED;
6264                 }
6265         } else {
6266                 /* Old compat. Deprecated */
6267                 clear_trusted_flags(&flag);
6268         }
6269
6270         if (atype == BPF_READ && value_regno >= 0)
6271                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6272
6273         return 0;
6274 }
6275
6276 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6277                                    struct bpf_reg_state *regs,
6278                                    int regno, int off, int size,
6279                                    enum bpf_access_type atype,
6280                                    int value_regno)
6281 {
6282         struct bpf_reg_state *reg = regs + regno;
6283         struct bpf_map *map = reg->map_ptr;
6284         struct bpf_reg_state map_reg;
6285         enum bpf_type_flag flag = 0;
6286         const struct btf_type *t;
6287         const char *tname;
6288         u32 btf_id;
6289         int ret;
6290
6291         if (!btf_vmlinux) {
6292                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6293                 return -ENOTSUPP;
6294         }
6295
6296         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6297                 verbose(env, "map_ptr access not supported for map type %d\n",
6298                         map->map_type);
6299                 return -ENOTSUPP;
6300         }
6301
6302         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6303         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6304
6305         if (!env->allow_ptr_leaks) {
6306                 verbose(env,
6307                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6308                         tname);
6309                 return -EPERM;
6310         }
6311
6312         if (off < 0) {
6313                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6314                         regno, tname, off);
6315                 return -EACCES;
6316         }
6317
6318         if (atype != BPF_READ) {
6319                 verbose(env, "only read from %s is supported\n", tname);
6320                 return -EACCES;
6321         }
6322
6323         /* Simulate access to a PTR_TO_BTF_ID */
6324         memset(&map_reg, 0, sizeof(map_reg));
6325         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6326         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6327         if (ret < 0)
6328                 return ret;
6329
6330         if (value_regno >= 0)
6331                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6332
6333         return 0;
6334 }
6335
6336 /* Check that the stack access at the given offset is within bounds. The
6337  * maximum valid offset is -1.
6338  *
6339  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6340  * -state->allocated_stack for reads.
6341  */
6342 static int check_stack_slot_within_bounds(int off,
6343                                           struct bpf_func_state *state,
6344                                           enum bpf_access_type t)
6345 {
6346         int min_valid_off;
6347
6348         if (t == BPF_WRITE)
6349                 min_valid_off = -MAX_BPF_STACK;
6350         else
6351                 min_valid_off = -state->allocated_stack;
6352
6353         if (off < min_valid_off || off > -1)
6354                 return -EACCES;
6355         return 0;
6356 }
6357
6358 /* Check that the stack access at 'regno + off' falls within the maximum stack
6359  * bounds.
6360  *
6361  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6362  */
6363 static int check_stack_access_within_bounds(
6364                 struct bpf_verifier_env *env,
6365                 int regno, int off, int access_size,
6366                 enum bpf_access_src src, enum bpf_access_type type)
6367 {
6368         struct bpf_reg_state *regs = cur_regs(env);
6369         struct bpf_reg_state *reg = regs + regno;
6370         struct bpf_func_state *state = func(env, reg);
6371         int min_off, max_off;
6372         int err;
6373         char *err_extra;
6374
6375         if (src == ACCESS_HELPER)
6376                 /* We don't know if helpers are reading or writing (or both). */
6377                 err_extra = " indirect access to";
6378         else if (type == BPF_READ)
6379                 err_extra = " read from";
6380         else
6381                 err_extra = " write to";
6382
6383         if (tnum_is_const(reg->var_off)) {
6384                 min_off = reg->var_off.value + off;
6385                 if (access_size > 0)
6386                         max_off = min_off + access_size - 1;
6387                 else
6388                         max_off = min_off;
6389         } else {
6390                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6391                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6392                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6393                                 err_extra, regno);
6394                         return -EACCES;
6395                 }
6396                 min_off = reg->smin_value + off;
6397                 if (access_size > 0)
6398                         max_off = reg->smax_value + off + access_size - 1;
6399                 else
6400                         max_off = min_off;
6401         }
6402
6403         err = check_stack_slot_within_bounds(min_off, state, type);
6404         if (!err)
6405                 err = check_stack_slot_within_bounds(max_off, state, type);
6406
6407         if (err) {
6408                 if (tnum_is_const(reg->var_off)) {
6409                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6410                                 err_extra, regno, off, access_size);
6411                 } else {
6412                         char tn_buf[48];
6413
6414                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6415                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6416                                 err_extra, regno, tn_buf, access_size);
6417                 }
6418         }
6419         return err;
6420 }
6421
6422 /* check whether memory at (regno + off) is accessible for t = (read | write)
6423  * if t==write, value_regno is a register which value is stored into memory
6424  * if t==read, value_regno is a register which will receive the value from memory
6425  * if t==write && value_regno==-1, some unknown value is stored into memory
6426  * if t==read && value_regno==-1, don't care what we read from memory
6427  */
6428 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6429                             int off, int bpf_size, enum bpf_access_type t,
6430                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6431 {
6432         struct bpf_reg_state *regs = cur_regs(env);
6433         struct bpf_reg_state *reg = regs + regno;
6434         struct bpf_func_state *state;
6435         int size, err = 0;
6436
6437         size = bpf_size_to_bytes(bpf_size);
6438         if (size < 0)
6439                 return size;
6440
6441         /* alignment checks will add in reg->off themselves */
6442         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6443         if (err)
6444                 return err;
6445
6446         /* for access checks, reg->off is just part of off */
6447         off += reg->off;
6448
6449         if (reg->type == PTR_TO_MAP_KEY) {
6450                 if (t == BPF_WRITE) {
6451                         verbose(env, "write to change key R%d not allowed\n", regno);
6452                         return -EACCES;
6453                 }
6454
6455                 err = check_mem_region_access(env, regno, off, size,
6456                                               reg->map_ptr->key_size, false);
6457                 if (err)
6458                         return err;
6459                 if (value_regno >= 0)
6460                         mark_reg_unknown(env, regs, value_regno);
6461         } else if (reg->type == PTR_TO_MAP_VALUE) {
6462                 struct btf_field *kptr_field = NULL;
6463
6464                 if (t == BPF_WRITE && value_regno >= 0 &&
6465                     is_pointer_value(env, value_regno)) {
6466                         verbose(env, "R%d leaks addr into map\n", value_regno);
6467                         return -EACCES;
6468                 }
6469                 err = check_map_access_type(env, regno, off, size, t);
6470                 if (err)
6471                         return err;
6472                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6473                 if (err)
6474                         return err;
6475                 if (tnum_is_const(reg->var_off))
6476                         kptr_field = btf_record_find(reg->map_ptr->record,
6477                                                      off + reg->var_off.value, BPF_KPTR);
6478                 if (kptr_field) {
6479                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6480                 } else if (t == BPF_READ && value_regno >= 0) {
6481                         struct bpf_map *map = reg->map_ptr;
6482
6483                         /* if map is read-only, track its contents as scalars */
6484                         if (tnum_is_const(reg->var_off) &&
6485                             bpf_map_is_rdonly(map) &&
6486                             map->ops->map_direct_value_addr) {
6487                                 int map_off = off + reg->var_off.value;
6488                                 u64 val = 0;
6489
6490                                 err = bpf_map_direct_read(map, map_off, size,
6491                                                           &val, is_ldsx);
6492                                 if (err)
6493                                         return err;
6494
6495                                 regs[value_regno].type = SCALAR_VALUE;
6496                                 __mark_reg_known(&regs[value_regno], val);
6497                         } else {
6498                                 mark_reg_unknown(env, regs, value_regno);
6499                         }
6500                 }
6501         } else if (base_type(reg->type) == PTR_TO_MEM) {
6502                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6503
6504                 if (type_may_be_null(reg->type)) {
6505                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6506                                 reg_type_str(env, reg->type));
6507                         return -EACCES;
6508                 }
6509
6510                 if (t == BPF_WRITE && rdonly_mem) {
6511                         verbose(env, "R%d cannot write into %s\n",
6512                                 regno, reg_type_str(env, reg->type));
6513                         return -EACCES;
6514                 }
6515
6516                 if (t == BPF_WRITE && value_regno >= 0 &&
6517                     is_pointer_value(env, value_regno)) {
6518                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6519                         return -EACCES;
6520                 }
6521
6522                 err = check_mem_region_access(env, regno, off, size,
6523                                               reg->mem_size, false);
6524                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6525                         mark_reg_unknown(env, regs, value_regno);
6526         } else if (reg->type == PTR_TO_CTX) {
6527                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6528                 struct btf *btf = NULL;
6529                 u32 btf_id = 0;
6530
6531                 if (t == BPF_WRITE && value_regno >= 0 &&
6532                     is_pointer_value(env, value_regno)) {
6533                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6534                         return -EACCES;
6535                 }
6536
6537                 err = check_ptr_off_reg(env, reg, regno);
6538                 if (err < 0)
6539                         return err;
6540
6541                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6542                                        &btf_id);
6543                 if (err)
6544                         verbose_linfo(env, insn_idx, "; ");
6545                 if (!err && t == BPF_READ && value_regno >= 0) {
6546                         /* ctx access returns either a scalar, or a
6547                          * PTR_TO_PACKET[_META,_END]. In the latter
6548                          * case, we know the offset is zero.
6549                          */
6550                         if (reg_type == SCALAR_VALUE) {
6551                                 mark_reg_unknown(env, regs, value_regno);
6552                         } else {
6553                                 mark_reg_known_zero(env, regs,
6554                                                     value_regno);
6555                                 if (type_may_be_null(reg_type))
6556                                         regs[value_regno].id = ++env->id_gen;
6557                                 /* A load of ctx field could have different
6558                                  * actual load size with the one encoded in the
6559                                  * insn. When the dst is PTR, it is for sure not
6560                                  * a sub-register.
6561                                  */
6562                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6563                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6564                                         regs[value_regno].btf = btf;
6565                                         regs[value_regno].btf_id = btf_id;
6566                                 }
6567                         }
6568                         regs[value_regno].type = reg_type;
6569                 }
6570
6571         } else if (reg->type == PTR_TO_STACK) {
6572                 /* Basic bounds checks. */
6573                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6574                 if (err)
6575                         return err;
6576
6577                 state = func(env, reg);
6578                 err = update_stack_depth(env, state, off);
6579                 if (err)
6580                         return err;
6581
6582                 if (t == BPF_READ)
6583                         err = check_stack_read(env, regno, off, size,
6584                                                value_regno);
6585                 else
6586                         err = check_stack_write(env, regno, off, size,
6587                                                 value_regno, insn_idx);
6588         } else if (reg_is_pkt_pointer(reg)) {
6589                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6590                         verbose(env, "cannot write into packet\n");
6591                         return -EACCES;
6592                 }
6593                 if (t == BPF_WRITE && value_regno >= 0 &&
6594                     is_pointer_value(env, value_regno)) {
6595                         verbose(env, "R%d leaks addr into packet\n",
6596                                 value_regno);
6597                         return -EACCES;
6598                 }
6599                 err = check_packet_access(env, regno, off, size, false);
6600                 if (!err && t == BPF_READ && value_regno >= 0)
6601                         mark_reg_unknown(env, regs, value_regno);
6602         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6603                 if (t == BPF_WRITE && value_regno >= 0 &&
6604                     is_pointer_value(env, value_regno)) {
6605                         verbose(env, "R%d leaks addr into flow keys\n",
6606                                 value_regno);
6607                         return -EACCES;
6608                 }
6609
6610                 err = check_flow_keys_access(env, off, size);
6611                 if (!err && t == BPF_READ && value_regno >= 0)
6612                         mark_reg_unknown(env, regs, value_regno);
6613         } else if (type_is_sk_pointer(reg->type)) {
6614                 if (t == BPF_WRITE) {
6615                         verbose(env, "R%d cannot write into %s\n",
6616                                 regno, reg_type_str(env, reg->type));
6617                         return -EACCES;
6618                 }
6619                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6620                 if (!err && value_regno >= 0)
6621                         mark_reg_unknown(env, regs, value_regno);
6622         } else if (reg->type == PTR_TO_TP_BUFFER) {
6623                 err = check_tp_buffer_access(env, reg, regno, off, size);
6624                 if (!err && t == BPF_READ && value_regno >= 0)
6625                         mark_reg_unknown(env, regs, value_regno);
6626         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6627                    !type_may_be_null(reg->type)) {
6628                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6629                                               value_regno);
6630         } else if (reg->type == CONST_PTR_TO_MAP) {
6631                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6632                                               value_regno);
6633         } else if (base_type(reg->type) == PTR_TO_BUF) {
6634                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6635                 u32 *max_access;
6636
6637                 if (rdonly_mem) {
6638                         if (t == BPF_WRITE) {
6639                                 verbose(env, "R%d cannot write into %s\n",
6640                                         regno, reg_type_str(env, reg->type));
6641                                 return -EACCES;
6642                         }
6643                         max_access = &env->prog->aux->max_rdonly_access;
6644                 } else {
6645                         max_access = &env->prog->aux->max_rdwr_access;
6646                 }
6647
6648                 err = check_buffer_access(env, reg, regno, off, size, false,
6649                                           max_access);
6650
6651                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6652                         mark_reg_unknown(env, regs, value_regno);
6653         } else {
6654                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6655                         reg_type_str(env, reg->type));
6656                 return -EACCES;
6657         }
6658
6659         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6660             regs[value_regno].type == SCALAR_VALUE) {
6661                 if (!is_ldsx)
6662                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6663                         coerce_reg_to_size(&regs[value_regno], size);
6664                 else
6665                         coerce_reg_to_size_sx(&regs[value_regno], size);
6666         }
6667         return err;
6668 }
6669
6670 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6671 {
6672         int load_reg;
6673         int err;
6674
6675         switch (insn->imm) {
6676         case BPF_ADD:
6677         case BPF_ADD | BPF_FETCH:
6678         case BPF_AND:
6679         case BPF_AND | BPF_FETCH:
6680         case BPF_OR:
6681         case BPF_OR | BPF_FETCH:
6682         case BPF_XOR:
6683         case BPF_XOR | BPF_FETCH:
6684         case BPF_XCHG:
6685         case BPF_CMPXCHG:
6686                 break;
6687         default:
6688                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6689                 return -EINVAL;
6690         }
6691
6692         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6693                 verbose(env, "invalid atomic operand size\n");
6694                 return -EINVAL;
6695         }
6696
6697         /* check src1 operand */
6698         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6699         if (err)
6700                 return err;
6701
6702         /* check src2 operand */
6703         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6704         if (err)
6705                 return err;
6706
6707         if (insn->imm == BPF_CMPXCHG) {
6708                 /* Check comparison of R0 with memory location */
6709                 const u32 aux_reg = BPF_REG_0;
6710
6711                 err = check_reg_arg(env, aux_reg, SRC_OP);
6712                 if (err)
6713                         return err;
6714
6715                 if (is_pointer_value(env, aux_reg)) {
6716                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6717                         return -EACCES;
6718                 }
6719         }
6720
6721         if (is_pointer_value(env, insn->src_reg)) {
6722                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6723                 return -EACCES;
6724         }
6725
6726         if (is_ctx_reg(env, insn->dst_reg) ||
6727             is_pkt_reg(env, insn->dst_reg) ||
6728             is_flow_key_reg(env, insn->dst_reg) ||
6729             is_sk_reg(env, insn->dst_reg)) {
6730                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6731                         insn->dst_reg,
6732                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6733                 return -EACCES;
6734         }
6735
6736         if (insn->imm & BPF_FETCH) {
6737                 if (insn->imm == BPF_CMPXCHG)
6738                         load_reg = BPF_REG_0;
6739                 else
6740                         load_reg = insn->src_reg;
6741
6742                 /* check and record load of old value */
6743                 err = check_reg_arg(env, load_reg, DST_OP);
6744                 if (err)
6745                         return err;
6746         } else {
6747                 /* This instruction accesses a memory location but doesn't
6748                  * actually load it into a register.
6749                  */
6750                 load_reg = -1;
6751         }
6752
6753         /* Check whether we can read the memory, with second call for fetch
6754          * case to simulate the register fill.
6755          */
6756         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6757                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6758         if (!err && load_reg >= 0)
6759                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6760                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6761                                        true, false);
6762         if (err)
6763                 return err;
6764
6765         /* Check whether we can write into the same memory. */
6766         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6767                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6768         if (err)
6769                 return err;
6770
6771         return 0;
6772 }
6773
6774 /* When register 'regno' is used to read the stack (either directly or through
6775  * a helper function) make sure that it's within stack boundary and, depending
6776  * on the access type, that all elements of the stack are initialized.
6777  *
6778  * 'off' includes 'regno->off', but not its dynamic part (if any).
6779  *
6780  * All registers that have been spilled on the stack in the slots within the
6781  * read offsets are marked as read.
6782  */
6783 static int check_stack_range_initialized(
6784                 struct bpf_verifier_env *env, int regno, int off,
6785                 int access_size, bool zero_size_allowed,
6786                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6787 {
6788         struct bpf_reg_state *reg = reg_state(env, regno);
6789         struct bpf_func_state *state = func(env, reg);
6790         int err, min_off, max_off, i, j, slot, spi;
6791         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6792         enum bpf_access_type bounds_check_type;
6793         /* Some accesses can write anything into the stack, others are
6794          * read-only.
6795          */
6796         bool clobber = false;
6797
6798         if (access_size == 0 && !zero_size_allowed) {
6799                 verbose(env, "invalid zero-sized read\n");
6800                 return -EACCES;
6801         }
6802
6803         if (type == ACCESS_HELPER) {
6804                 /* The bounds checks for writes are more permissive than for
6805                  * reads. However, if raw_mode is not set, we'll do extra
6806                  * checks below.
6807                  */
6808                 bounds_check_type = BPF_WRITE;
6809                 clobber = true;
6810         } else {
6811                 bounds_check_type = BPF_READ;
6812         }
6813         err = check_stack_access_within_bounds(env, regno, off, access_size,
6814                                                type, bounds_check_type);
6815         if (err)
6816                 return err;
6817
6818
6819         if (tnum_is_const(reg->var_off)) {
6820                 min_off = max_off = reg->var_off.value + off;
6821         } else {
6822                 /* Variable offset is prohibited for unprivileged mode for
6823                  * simplicity since it requires corresponding support in
6824                  * Spectre masking for stack ALU.
6825                  * See also retrieve_ptr_limit().
6826                  */
6827                 if (!env->bypass_spec_v1) {
6828                         char tn_buf[48];
6829
6830                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6831                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6832                                 regno, err_extra, tn_buf);
6833                         return -EACCES;
6834                 }
6835                 /* Only initialized buffer on stack is allowed to be accessed
6836                  * with variable offset. With uninitialized buffer it's hard to
6837                  * guarantee that whole memory is marked as initialized on
6838                  * helper return since specific bounds are unknown what may
6839                  * cause uninitialized stack leaking.
6840                  */
6841                 if (meta && meta->raw_mode)
6842                         meta = NULL;
6843
6844                 min_off = reg->smin_value + off;
6845                 max_off = reg->smax_value + off;
6846         }
6847
6848         if (meta && meta->raw_mode) {
6849                 /* Ensure we won't be overwriting dynptrs when simulating byte
6850                  * by byte access in check_helper_call using meta.access_size.
6851                  * This would be a problem if we have a helper in the future
6852                  * which takes:
6853                  *
6854                  *      helper(uninit_mem, len, dynptr)
6855                  *
6856                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6857                  * may end up writing to dynptr itself when touching memory from
6858                  * arg 1. This can be relaxed on a case by case basis for known
6859                  * safe cases, but reject due to the possibilitiy of aliasing by
6860                  * default.
6861                  */
6862                 for (i = min_off; i < max_off + access_size; i++) {
6863                         int stack_off = -i - 1;
6864
6865                         spi = __get_spi(i);
6866                         /* raw_mode may write past allocated_stack */
6867                         if (state->allocated_stack <= stack_off)
6868                                 continue;
6869                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6870                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6871                                 return -EACCES;
6872                         }
6873                 }
6874                 meta->access_size = access_size;
6875                 meta->regno = regno;
6876                 return 0;
6877         }
6878
6879         for (i = min_off; i < max_off + access_size; i++) {
6880                 u8 *stype;
6881
6882                 slot = -i - 1;
6883                 spi = slot / BPF_REG_SIZE;
6884                 if (state->allocated_stack <= slot)
6885                         goto err;
6886                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6887                 if (*stype == STACK_MISC)
6888                         goto mark;
6889                 if ((*stype == STACK_ZERO) ||
6890                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6891                         if (clobber) {
6892                                 /* helper can write anything into the stack */
6893                                 *stype = STACK_MISC;
6894                         }
6895                         goto mark;
6896                 }
6897
6898                 if (is_spilled_reg(&state->stack[spi]) &&
6899                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6900                      env->allow_ptr_leaks)) {
6901                         if (clobber) {
6902                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6903                                 for (j = 0; j < BPF_REG_SIZE; j++)
6904                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6905                         }
6906                         goto mark;
6907                 }
6908
6909 err:
6910                 if (tnum_is_const(reg->var_off)) {
6911                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6912                                 err_extra, regno, min_off, i - min_off, access_size);
6913                 } else {
6914                         char tn_buf[48];
6915
6916                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6917                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6918                                 err_extra, regno, tn_buf, i - min_off, access_size);
6919                 }
6920                 return -EACCES;
6921 mark:
6922                 /* reading any byte out of 8-byte 'spill_slot' will cause
6923                  * the whole slot to be marked as 'read'
6924                  */
6925                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6926                               state->stack[spi].spilled_ptr.parent,
6927                               REG_LIVE_READ64);
6928                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6929                  * be sure that whether stack slot is written to or not. Hence,
6930                  * we must still conservatively propagate reads upwards even if
6931                  * helper may write to the entire memory range.
6932                  */
6933         }
6934         return update_stack_depth(env, state, min_off);
6935 }
6936
6937 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6938                                    int access_size, bool zero_size_allowed,
6939                                    struct bpf_call_arg_meta *meta)
6940 {
6941         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6942         u32 *max_access;
6943
6944         switch (base_type(reg->type)) {
6945         case PTR_TO_PACKET:
6946         case PTR_TO_PACKET_META:
6947                 return check_packet_access(env, regno, reg->off, access_size,
6948                                            zero_size_allowed);
6949         case PTR_TO_MAP_KEY:
6950                 if (meta && meta->raw_mode) {
6951                         verbose(env, "R%d cannot write into %s\n", regno,
6952                                 reg_type_str(env, reg->type));
6953                         return -EACCES;
6954                 }
6955                 return check_mem_region_access(env, regno, reg->off, access_size,
6956                                                reg->map_ptr->key_size, false);
6957         case PTR_TO_MAP_VALUE:
6958                 if (check_map_access_type(env, regno, reg->off, access_size,
6959                                           meta && meta->raw_mode ? BPF_WRITE :
6960                                           BPF_READ))
6961                         return -EACCES;
6962                 return check_map_access(env, regno, reg->off, access_size,
6963                                         zero_size_allowed, ACCESS_HELPER);
6964         case PTR_TO_MEM:
6965                 if (type_is_rdonly_mem(reg->type)) {
6966                         if (meta && meta->raw_mode) {
6967                                 verbose(env, "R%d cannot write into %s\n", regno,
6968                                         reg_type_str(env, reg->type));
6969                                 return -EACCES;
6970                         }
6971                 }
6972                 return check_mem_region_access(env, regno, reg->off,
6973                                                access_size, reg->mem_size,
6974                                                zero_size_allowed);
6975         case PTR_TO_BUF:
6976                 if (type_is_rdonly_mem(reg->type)) {
6977                         if (meta && meta->raw_mode) {
6978                                 verbose(env, "R%d cannot write into %s\n", regno,
6979                                         reg_type_str(env, reg->type));
6980                                 return -EACCES;
6981                         }
6982
6983                         max_access = &env->prog->aux->max_rdonly_access;
6984                 } else {
6985                         max_access = &env->prog->aux->max_rdwr_access;
6986                 }
6987                 return check_buffer_access(env, reg, regno, reg->off,
6988                                            access_size, zero_size_allowed,
6989                                            max_access);
6990         case PTR_TO_STACK:
6991                 return check_stack_range_initialized(
6992                                 env,
6993                                 regno, reg->off, access_size,
6994                                 zero_size_allowed, ACCESS_HELPER, meta);
6995         case PTR_TO_BTF_ID:
6996                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
6997                                                access_size, BPF_READ, -1);
6998         case PTR_TO_CTX:
6999                 /* in case the function doesn't know how to access the context,
7000                  * (because we are in a program of type SYSCALL for example), we
7001                  * can not statically check its size.
7002                  * Dynamically check it now.
7003                  */
7004                 if (!env->ops->convert_ctx_access) {
7005                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7006                         int offset = access_size - 1;
7007
7008                         /* Allow zero-byte read from PTR_TO_CTX */
7009                         if (access_size == 0)
7010                                 return zero_size_allowed ? 0 : -EACCES;
7011
7012                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7013                                                 atype, -1, false, false);
7014                 }
7015
7016                 fallthrough;
7017         default: /* scalar_value or invalid ptr */
7018                 /* Allow zero-byte read from NULL, regardless of pointer type */
7019                 if (zero_size_allowed && access_size == 0 &&
7020                     register_is_null(reg))
7021                         return 0;
7022
7023                 verbose(env, "R%d type=%s ", regno,
7024                         reg_type_str(env, reg->type));
7025                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7026                 return -EACCES;
7027         }
7028 }
7029
7030 static int check_mem_size_reg(struct bpf_verifier_env *env,
7031                               struct bpf_reg_state *reg, u32 regno,
7032                               bool zero_size_allowed,
7033                               struct bpf_call_arg_meta *meta)
7034 {
7035         int err;
7036
7037         /* This is used to refine r0 return value bounds for helpers
7038          * that enforce this value as an upper bound on return values.
7039          * See do_refine_retval_range() for helpers that can refine
7040          * the return value. C type of helper is u32 so we pull register
7041          * bound from umax_value however, if negative verifier errors
7042          * out. Only upper bounds can be learned because retval is an
7043          * int type and negative retvals are allowed.
7044          */
7045         meta->msize_max_value = reg->umax_value;
7046
7047         /* The register is SCALAR_VALUE; the access check
7048          * happens using its boundaries.
7049          */
7050         if (!tnum_is_const(reg->var_off))
7051                 /* For unprivileged variable accesses, disable raw
7052                  * mode so that the program is required to
7053                  * initialize all the memory that the helper could
7054                  * just partially fill up.
7055                  */
7056                 meta = NULL;
7057
7058         if (reg->smin_value < 0) {
7059                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7060                         regno);
7061                 return -EACCES;
7062         }
7063
7064         if (reg->umin_value == 0) {
7065                 err = check_helper_mem_access(env, regno - 1, 0,
7066                                               zero_size_allowed,
7067                                               meta);
7068                 if (err)
7069                         return err;
7070         }
7071
7072         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7073                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7074                         regno);
7075                 return -EACCES;
7076         }
7077         err = check_helper_mem_access(env, regno - 1,
7078                                       reg->umax_value,
7079                                       zero_size_allowed, meta);
7080         if (!err)
7081                 err = mark_chain_precision(env, regno);
7082         return err;
7083 }
7084
7085 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7086                    u32 regno, u32 mem_size)
7087 {
7088         bool may_be_null = type_may_be_null(reg->type);
7089         struct bpf_reg_state saved_reg;
7090         struct bpf_call_arg_meta meta;
7091         int err;
7092
7093         if (register_is_null(reg))
7094                 return 0;
7095
7096         memset(&meta, 0, sizeof(meta));
7097         /* Assuming that the register contains a value check if the memory
7098          * access is safe. Temporarily save and restore the register's state as
7099          * the conversion shouldn't be visible to a caller.
7100          */
7101         if (may_be_null) {
7102                 saved_reg = *reg;
7103                 mark_ptr_not_null_reg(reg);
7104         }
7105
7106         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7107         /* Check access for BPF_WRITE */
7108         meta.raw_mode = true;
7109         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7110
7111         if (may_be_null)
7112                 *reg = saved_reg;
7113
7114         return err;
7115 }
7116
7117 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7118                                     u32 regno)
7119 {
7120         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7121         bool may_be_null = type_may_be_null(mem_reg->type);
7122         struct bpf_reg_state saved_reg;
7123         struct bpf_call_arg_meta meta;
7124         int err;
7125
7126         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7127
7128         memset(&meta, 0, sizeof(meta));
7129
7130         if (may_be_null) {
7131                 saved_reg = *mem_reg;
7132                 mark_ptr_not_null_reg(mem_reg);
7133         }
7134
7135         err = check_mem_size_reg(env, reg, regno, true, &meta);
7136         /* Check access for BPF_WRITE */
7137         meta.raw_mode = true;
7138         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7139
7140         if (may_be_null)
7141                 *mem_reg = saved_reg;
7142         return err;
7143 }
7144
7145 /* Implementation details:
7146  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7147  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7148  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7149  * Two separate bpf_obj_new will also have different reg->id.
7150  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7151  * clears reg->id after value_or_null->value transition, since the verifier only
7152  * cares about the range of access to valid map value pointer and doesn't care
7153  * about actual address of the map element.
7154  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7155  * reg->id > 0 after value_or_null->value transition. By doing so
7156  * two bpf_map_lookups will be considered two different pointers that
7157  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7158  * returned from bpf_obj_new.
7159  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7160  * dead-locks.
7161  * Since only one bpf_spin_lock is allowed the checks are simpler than
7162  * reg_is_refcounted() logic. The verifier needs to remember only
7163  * one spin_lock instead of array of acquired_refs.
7164  * cur_state->active_lock remembers which map value element or allocated
7165  * object got locked and clears it after bpf_spin_unlock.
7166  */
7167 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7168                              bool is_lock)
7169 {
7170         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7171         struct bpf_verifier_state *cur = env->cur_state;
7172         bool is_const = tnum_is_const(reg->var_off);
7173         u64 val = reg->var_off.value;
7174         struct bpf_map *map = NULL;
7175         struct btf *btf = NULL;
7176         struct btf_record *rec;
7177
7178         if (!is_const) {
7179                 verbose(env,
7180                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7181                         regno);
7182                 return -EINVAL;
7183         }
7184         if (reg->type == PTR_TO_MAP_VALUE) {
7185                 map = reg->map_ptr;
7186                 if (!map->btf) {
7187                         verbose(env,
7188                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7189                                 map->name);
7190                         return -EINVAL;
7191                 }
7192         } else {
7193                 btf = reg->btf;
7194         }
7195
7196         rec = reg_btf_record(reg);
7197         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7198                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7199                         map ? map->name : "kptr");
7200                 return -EINVAL;
7201         }
7202         if (rec->spin_lock_off != val + reg->off) {
7203                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7204                         val + reg->off, rec->spin_lock_off);
7205                 return -EINVAL;
7206         }
7207         if (is_lock) {
7208                 if (cur->active_lock.ptr) {
7209                         verbose(env,
7210                                 "Locking two bpf_spin_locks are not allowed\n");
7211                         return -EINVAL;
7212                 }
7213                 if (map)
7214                         cur->active_lock.ptr = map;
7215                 else
7216                         cur->active_lock.ptr = btf;
7217                 cur->active_lock.id = reg->id;
7218         } else {
7219                 void *ptr;
7220
7221                 if (map)
7222                         ptr = map;
7223                 else
7224                         ptr = btf;
7225
7226                 if (!cur->active_lock.ptr) {
7227                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7228                         return -EINVAL;
7229                 }
7230                 if (cur->active_lock.ptr != ptr ||
7231                     cur->active_lock.id != reg->id) {
7232                         verbose(env, "bpf_spin_unlock of different lock\n");
7233                         return -EINVAL;
7234                 }
7235
7236                 invalidate_non_owning_refs(env);
7237
7238                 cur->active_lock.ptr = NULL;
7239                 cur->active_lock.id = 0;
7240         }
7241         return 0;
7242 }
7243
7244 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7245                               struct bpf_call_arg_meta *meta)
7246 {
7247         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7248         bool is_const = tnum_is_const(reg->var_off);
7249         struct bpf_map *map = reg->map_ptr;
7250         u64 val = reg->var_off.value;
7251
7252         if (!is_const) {
7253                 verbose(env,
7254                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7255                         regno);
7256                 return -EINVAL;
7257         }
7258         if (!map->btf) {
7259                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7260                         map->name);
7261                 return -EINVAL;
7262         }
7263         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7264                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7265                 return -EINVAL;
7266         }
7267         if (map->record->timer_off != val + reg->off) {
7268                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7269                         val + reg->off, map->record->timer_off);
7270                 return -EINVAL;
7271         }
7272         if (meta->map_ptr) {
7273                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7274                 return -EFAULT;
7275         }
7276         meta->map_uid = reg->map_uid;
7277         meta->map_ptr = map;
7278         return 0;
7279 }
7280
7281 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7282                              struct bpf_call_arg_meta *meta)
7283 {
7284         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7285         struct bpf_map *map_ptr = reg->map_ptr;
7286         struct btf_field *kptr_field;
7287         u32 kptr_off;
7288
7289         if (!tnum_is_const(reg->var_off)) {
7290                 verbose(env,
7291                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7292                         regno);
7293                 return -EINVAL;
7294         }
7295         if (!map_ptr->btf) {
7296                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7297                         map_ptr->name);
7298                 return -EINVAL;
7299         }
7300         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7301                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7302                 return -EINVAL;
7303         }
7304
7305         meta->map_ptr = map_ptr;
7306         kptr_off = reg->off + reg->var_off.value;
7307         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7308         if (!kptr_field) {
7309                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7310                 return -EACCES;
7311         }
7312         if (kptr_field->type != BPF_KPTR_REF) {
7313                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7314                 return -EACCES;
7315         }
7316         meta->kptr_field = kptr_field;
7317         return 0;
7318 }
7319
7320 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7321  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7322  *
7323  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7324  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7325  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7326  *
7327  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7328  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7329  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7330  * mutate the view of the dynptr and also possibly destroy it. In the latter
7331  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7332  * memory that dynptr points to.
7333  *
7334  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7335  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7336  * readonly dynptr view yet, hence only the first case is tracked and checked.
7337  *
7338  * This is consistent with how C applies the const modifier to a struct object,
7339  * where the pointer itself inside bpf_dynptr becomes const but not what it
7340  * points to.
7341  *
7342  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7343  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7344  */
7345 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7346                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7347 {
7348         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7349         int err;
7350
7351         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7352          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7353          */
7354         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7355                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7356                 return -EFAULT;
7357         }
7358
7359         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7360          *               constructing a mutable bpf_dynptr object.
7361          *
7362          *               Currently, this is only possible with PTR_TO_STACK
7363          *               pointing to a region of at least 16 bytes which doesn't
7364          *               contain an existing bpf_dynptr.
7365          *
7366          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7367          *               mutated or destroyed. However, the memory it points to
7368          *               may be mutated.
7369          *
7370          *  None       - Points to a initialized dynptr that can be mutated and
7371          *               destroyed, including mutation of the memory it points
7372          *               to.
7373          */
7374         if (arg_type & MEM_UNINIT) {
7375                 int i;
7376
7377                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7378                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7379                         return -EINVAL;
7380                 }
7381
7382                 /* we write BPF_DW bits (8 bytes) at a time */
7383                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7384                         err = check_mem_access(env, insn_idx, regno,
7385                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7386                         if (err)
7387                                 return err;
7388                 }
7389
7390                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7391         } else /* MEM_RDONLY and None case from above */ {
7392                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7393                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7394                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7395                         return -EINVAL;
7396                 }
7397
7398                 if (!is_dynptr_reg_valid_init(env, reg)) {
7399                         verbose(env,
7400                                 "Expected an initialized dynptr as arg #%d\n",
7401                                 regno);
7402                         return -EINVAL;
7403                 }
7404
7405                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7406                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7407                         verbose(env,
7408                                 "Expected a dynptr of type %s as arg #%d\n",
7409                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7410                         return -EINVAL;
7411                 }
7412
7413                 err = mark_dynptr_read(env, reg);
7414         }
7415         return err;
7416 }
7417
7418 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7419 {
7420         struct bpf_func_state *state = func(env, reg);
7421
7422         return state->stack[spi].spilled_ptr.ref_obj_id;
7423 }
7424
7425 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7426 {
7427         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7428 }
7429
7430 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7431 {
7432         return meta->kfunc_flags & KF_ITER_NEW;
7433 }
7434
7435 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7436 {
7437         return meta->kfunc_flags & KF_ITER_NEXT;
7438 }
7439
7440 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7441 {
7442         return meta->kfunc_flags & KF_ITER_DESTROY;
7443 }
7444
7445 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7446 {
7447         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7448          * kfunc is iter state pointer
7449          */
7450         return arg == 0 && is_iter_kfunc(meta);
7451 }
7452
7453 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7454                             struct bpf_kfunc_call_arg_meta *meta)
7455 {
7456         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7457         const struct btf_type *t;
7458         const struct btf_param *arg;
7459         int spi, err, i, nr_slots;
7460         u32 btf_id;
7461
7462         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7463         arg = &btf_params(meta->func_proto)[0];
7464         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7465         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7466         nr_slots = t->size / BPF_REG_SIZE;
7467
7468         if (is_iter_new_kfunc(meta)) {
7469                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7470                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7471                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7472                                 iter_type_str(meta->btf, btf_id), regno);
7473                         return -EINVAL;
7474                 }
7475
7476                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7477                         err = check_mem_access(env, insn_idx, regno,
7478                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7479                         if (err)
7480                                 return err;
7481                 }
7482
7483                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7484                 if (err)
7485                         return err;
7486         } else {
7487                 /* iter_next() or iter_destroy() expect initialized iter state*/
7488                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7489                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7490                                 iter_type_str(meta->btf, btf_id), regno);
7491                         return -EINVAL;
7492                 }
7493
7494                 spi = iter_get_spi(env, reg, nr_slots);
7495                 if (spi < 0)
7496                         return spi;
7497
7498                 err = mark_iter_read(env, reg, spi, nr_slots);
7499                 if (err)
7500                         return err;
7501
7502                 /* remember meta->iter info for process_iter_next_call() */
7503                 meta->iter.spi = spi;
7504                 meta->iter.frameno = reg->frameno;
7505                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7506
7507                 if (is_iter_destroy_kfunc(meta)) {
7508                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7509                         if (err)
7510                                 return err;
7511                 }
7512         }
7513
7514         return 0;
7515 }
7516
7517 /* process_iter_next_call() is called when verifier gets to iterator's next
7518  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7519  * to it as just "iter_next()" in comments below.
7520  *
7521  * BPF verifier relies on a crucial contract for any iter_next()
7522  * implementation: it should *eventually* return NULL, and once that happens
7523  * it should keep returning NULL. That is, once iterator exhausts elements to
7524  * iterate, it should never reset or spuriously return new elements.
7525  *
7526  * With the assumption of such contract, process_iter_next_call() simulates
7527  * a fork in the verifier state to validate loop logic correctness and safety
7528  * without having to simulate infinite amount of iterations.
7529  *
7530  * In current state, we first assume that iter_next() returned NULL and
7531  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7532  * conditions we should not form an infinite loop and should eventually reach
7533  * exit.
7534  *
7535  * Besides that, we also fork current state and enqueue it for later
7536  * verification. In a forked state we keep iterator state as ACTIVE
7537  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7538  * also bump iteration depth to prevent erroneous infinite loop detection
7539  * later on (see iter_active_depths_differ() comment for details). In this
7540  * state we assume that we'll eventually loop back to another iter_next()
7541  * calls (it could be in exactly same location or in some other instruction,
7542  * it doesn't matter, we don't make any unnecessary assumptions about this,
7543  * everything revolves around iterator state in a stack slot, not which
7544  * instruction is calling iter_next()). When that happens, we either will come
7545  * to iter_next() with equivalent state and can conclude that next iteration
7546  * will proceed in exactly the same way as we just verified, so it's safe to
7547  * assume that loop converges. If not, we'll go on another iteration
7548  * simulation with a different input state, until all possible starting states
7549  * are validated or we reach maximum number of instructions limit.
7550  *
7551  * This way, we will either exhaustively discover all possible input states
7552  * that iterator loop can start with and eventually will converge, or we'll
7553  * effectively regress into bounded loop simulation logic and either reach
7554  * maximum number of instructions if loop is not provably convergent, or there
7555  * is some statically known limit on number of iterations (e.g., if there is
7556  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7557  *
7558  * One very subtle but very important aspect is that we *always* simulate NULL
7559  * condition first (as the current state) before we simulate non-NULL case.
7560  * This has to do with intricacies of scalar precision tracking. By simulating
7561  * "exit condition" of iter_next() returning NULL first, we make sure all the
7562  * relevant precision marks *that will be set **after** we exit iterator loop*
7563  * are propagated backwards to common parent state of NULL and non-NULL
7564  * branches. Thanks to that, state equivalence checks done later in forked
7565  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7566  * precision marks are finalized and won't change. Because simulating another
7567  * ACTIVE iterator iteration won't change them (because given same input
7568  * states we'll end up with exactly same output states which we are currently
7569  * comparing; and verification after the loop already propagated back what
7570  * needs to be **additionally** tracked as precise). It's subtle, grok
7571  * precision tracking for more intuitive understanding.
7572  */
7573 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7574                                   struct bpf_kfunc_call_arg_meta *meta)
7575 {
7576         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7577         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7578         struct bpf_reg_state *cur_iter, *queued_iter;
7579         int iter_frameno = meta->iter.frameno;
7580         int iter_spi = meta->iter.spi;
7581
7582         BTF_TYPE_EMIT(struct bpf_iter);
7583
7584         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7585
7586         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7587             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7588                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7589                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7590                 return -EFAULT;
7591         }
7592
7593         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7594                 /* branch out active iter state */
7595                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7596                 if (!queued_st)
7597                         return -ENOMEM;
7598
7599                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7600                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7601                 queued_iter->iter.depth++;
7602
7603                 queued_fr = queued_st->frame[queued_st->curframe];
7604                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7605         }
7606
7607         /* switch to DRAINED state, but keep the depth unchanged */
7608         /* mark current iter state as drained and assume returned NULL */
7609         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7610         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7611
7612         return 0;
7613 }
7614
7615 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7616 {
7617         return type == ARG_CONST_SIZE ||
7618                type == ARG_CONST_SIZE_OR_ZERO;
7619 }
7620
7621 static bool arg_type_is_release(enum bpf_arg_type type)
7622 {
7623         return type & OBJ_RELEASE;
7624 }
7625
7626 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7627 {
7628         return base_type(type) == ARG_PTR_TO_DYNPTR;
7629 }
7630
7631 static int int_ptr_type_to_size(enum bpf_arg_type type)
7632 {
7633         if (type == ARG_PTR_TO_INT)
7634                 return sizeof(u32);
7635         else if (type == ARG_PTR_TO_LONG)
7636                 return sizeof(u64);
7637
7638         return -EINVAL;
7639 }
7640
7641 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7642                                  const struct bpf_call_arg_meta *meta,
7643                                  enum bpf_arg_type *arg_type)
7644 {
7645         if (!meta->map_ptr) {
7646                 /* kernel subsystem misconfigured verifier */
7647                 verbose(env, "invalid map_ptr to access map->type\n");
7648                 return -EACCES;
7649         }
7650
7651         switch (meta->map_ptr->map_type) {
7652         case BPF_MAP_TYPE_SOCKMAP:
7653         case BPF_MAP_TYPE_SOCKHASH:
7654                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7655                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7656                 } else {
7657                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7658                         return -EINVAL;
7659                 }
7660                 break;
7661         case BPF_MAP_TYPE_BLOOM_FILTER:
7662                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7663                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7664                 break;
7665         default:
7666                 break;
7667         }
7668         return 0;
7669 }
7670
7671 struct bpf_reg_types {
7672         const enum bpf_reg_type types[10];
7673         u32 *btf_id;
7674 };
7675
7676 static const struct bpf_reg_types sock_types = {
7677         .types = {
7678                 PTR_TO_SOCK_COMMON,
7679                 PTR_TO_SOCKET,
7680                 PTR_TO_TCP_SOCK,
7681                 PTR_TO_XDP_SOCK,
7682         },
7683 };
7684
7685 #ifdef CONFIG_NET
7686 static const struct bpf_reg_types btf_id_sock_common_types = {
7687         .types = {
7688                 PTR_TO_SOCK_COMMON,
7689                 PTR_TO_SOCKET,
7690                 PTR_TO_TCP_SOCK,
7691                 PTR_TO_XDP_SOCK,
7692                 PTR_TO_BTF_ID,
7693                 PTR_TO_BTF_ID | PTR_TRUSTED,
7694         },
7695         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7696 };
7697 #endif
7698
7699 static const struct bpf_reg_types mem_types = {
7700         .types = {
7701                 PTR_TO_STACK,
7702                 PTR_TO_PACKET,
7703                 PTR_TO_PACKET_META,
7704                 PTR_TO_MAP_KEY,
7705                 PTR_TO_MAP_VALUE,
7706                 PTR_TO_MEM,
7707                 PTR_TO_MEM | MEM_RINGBUF,
7708                 PTR_TO_BUF,
7709                 PTR_TO_BTF_ID | PTR_TRUSTED,
7710         },
7711 };
7712
7713 static const struct bpf_reg_types int_ptr_types = {
7714         .types = {
7715                 PTR_TO_STACK,
7716                 PTR_TO_PACKET,
7717                 PTR_TO_PACKET_META,
7718                 PTR_TO_MAP_KEY,
7719                 PTR_TO_MAP_VALUE,
7720         },
7721 };
7722
7723 static const struct bpf_reg_types spin_lock_types = {
7724         .types = {
7725                 PTR_TO_MAP_VALUE,
7726                 PTR_TO_BTF_ID | MEM_ALLOC,
7727         }
7728 };
7729
7730 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7731 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7732 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7733 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7734 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7735 static const struct bpf_reg_types btf_ptr_types = {
7736         .types = {
7737                 PTR_TO_BTF_ID,
7738                 PTR_TO_BTF_ID | PTR_TRUSTED,
7739                 PTR_TO_BTF_ID | MEM_RCU,
7740         },
7741 };
7742 static const struct bpf_reg_types percpu_btf_ptr_types = {
7743         .types = {
7744                 PTR_TO_BTF_ID | MEM_PERCPU,
7745                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7746         }
7747 };
7748 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7749 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7750 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7751 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7752 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7753 static const struct bpf_reg_types dynptr_types = {
7754         .types = {
7755                 PTR_TO_STACK,
7756                 CONST_PTR_TO_DYNPTR,
7757         }
7758 };
7759
7760 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7761         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7762         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7763         [ARG_CONST_SIZE]                = &scalar_types,
7764         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7765         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7766         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7767         [ARG_PTR_TO_CTX]                = &context_types,
7768         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7769 #ifdef CONFIG_NET
7770         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7771 #endif
7772         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7773         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7774         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7775         [ARG_PTR_TO_MEM]                = &mem_types,
7776         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7777         [ARG_PTR_TO_INT]                = &int_ptr_types,
7778         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7779         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7780         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7781         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7782         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7783         [ARG_PTR_TO_TIMER]              = &timer_types,
7784         [ARG_PTR_TO_KPTR]               = &kptr_types,
7785         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7786 };
7787
7788 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7789                           enum bpf_arg_type arg_type,
7790                           const u32 *arg_btf_id,
7791                           struct bpf_call_arg_meta *meta)
7792 {
7793         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7794         enum bpf_reg_type expected, type = reg->type;
7795         const struct bpf_reg_types *compatible;
7796         int i, j;
7797
7798         compatible = compatible_reg_types[base_type(arg_type)];
7799         if (!compatible) {
7800                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7801                 return -EFAULT;
7802         }
7803
7804         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7805          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7806          *
7807          * Same for MAYBE_NULL:
7808          *
7809          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7810          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7811          *
7812          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7813          *
7814          * Therefore we fold these flags depending on the arg_type before comparison.
7815          */
7816         if (arg_type & MEM_RDONLY)
7817                 type &= ~MEM_RDONLY;
7818         if (arg_type & PTR_MAYBE_NULL)
7819                 type &= ~PTR_MAYBE_NULL;
7820         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7821                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7822
7823         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7824                 type &= ~MEM_ALLOC;
7825
7826         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7827                 expected = compatible->types[i];
7828                 if (expected == NOT_INIT)
7829                         break;
7830
7831                 if (type == expected)
7832                         goto found;
7833         }
7834
7835         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7836         for (j = 0; j + 1 < i; j++)
7837                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7838         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7839         return -EACCES;
7840
7841 found:
7842         if (base_type(reg->type) != PTR_TO_BTF_ID)
7843                 return 0;
7844
7845         if (compatible == &mem_types) {
7846                 if (!(arg_type & MEM_RDONLY)) {
7847                         verbose(env,
7848                                 "%s() may write into memory pointed by R%d type=%s\n",
7849                                 func_id_name(meta->func_id),
7850                                 regno, reg_type_str(env, reg->type));
7851                         return -EACCES;
7852                 }
7853                 return 0;
7854         }
7855
7856         switch ((int)reg->type) {
7857         case PTR_TO_BTF_ID:
7858         case PTR_TO_BTF_ID | PTR_TRUSTED:
7859         case PTR_TO_BTF_ID | MEM_RCU:
7860         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7861         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7862         {
7863                 /* For bpf_sk_release, it needs to match against first member
7864                  * 'struct sock_common', hence make an exception for it. This
7865                  * allows bpf_sk_release to work for multiple socket types.
7866                  */
7867                 bool strict_type_match = arg_type_is_release(arg_type) &&
7868                                          meta->func_id != BPF_FUNC_sk_release;
7869
7870                 if (type_may_be_null(reg->type) &&
7871                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7872                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7873                         return -EACCES;
7874                 }
7875
7876                 if (!arg_btf_id) {
7877                         if (!compatible->btf_id) {
7878                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7879                                 return -EFAULT;
7880                         }
7881                         arg_btf_id = compatible->btf_id;
7882                 }
7883
7884                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7885                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7886                                 return -EACCES;
7887                 } else {
7888                         if (arg_btf_id == BPF_PTR_POISON) {
7889                                 verbose(env, "verifier internal error:");
7890                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7891                                         regno);
7892                                 return -EACCES;
7893                         }
7894
7895                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7896                                                   btf_vmlinux, *arg_btf_id,
7897                                                   strict_type_match)) {
7898                                 verbose(env, "R%d is of type %s but %s is expected\n",
7899                                         regno, btf_type_name(reg->btf, reg->btf_id),
7900                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7901                                 return -EACCES;
7902                         }
7903                 }
7904                 break;
7905         }
7906         case PTR_TO_BTF_ID | MEM_ALLOC:
7907                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7908                     meta->func_id != BPF_FUNC_kptr_xchg) {
7909                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7910                         return -EFAULT;
7911                 }
7912                 /* Handled by helper specific checks */
7913                 break;
7914         case PTR_TO_BTF_ID | MEM_PERCPU:
7915         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7916                 /* Handled by helper specific checks */
7917                 break;
7918         default:
7919                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7920                 return -EFAULT;
7921         }
7922         return 0;
7923 }
7924
7925 static struct btf_field *
7926 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7927 {
7928         struct btf_field *field;
7929         struct btf_record *rec;
7930
7931         rec = reg_btf_record(reg);
7932         if (!rec)
7933                 return NULL;
7934
7935         field = btf_record_find(rec, off, fields);
7936         if (!field)
7937                 return NULL;
7938
7939         return field;
7940 }
7941
7942 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7943                            const struct bpf_reg_state *reg, int regno,
7944                            enum bpf_arg_type arg_type)
7945 {
7946         u32 type = reg->type;
7947
7948         /* When referenced register is passed to release function, its fixed
7949          * offset must be 0.
7950          *
7951          * We will check arg_type_is_release reg has ref_obj_id when storing
7952          * meta->release_regno.
7953          */
7954         if (arg_type_is_release(arg_type)) {
7955                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7956                  * may not directly point to the object being released, but to
7957                  * dynptr pointing to such object, which might be at some offset
7958                  * on the stack. In that case, we simply to fallback to the
7959                  * default handling.
7960                  */
7961                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7962                         return 0;
7963
7964                 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) {
7965                         if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT))
7966                                 return __check_ptr_off_reg(env, reg, regno, true);
7967
7968                         verbose(env, "R%d must have zero offset when passed to release func\n",
7969                                 regno);
7970                         verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno,
7971                                 btf_type_name(reg->btf, reg->btf_id), reg->off);
7972                         return -EINVAL;
7973                 }
7974
7975                 /* Doing check_ptr_off_reg check for the offset will catch this
7976                  * because fixed_off_ok is false, but checking here allows us
7977                  * to give the user a better error message.
7978                  */
7979                 if (reg->off) {
7980                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
7981                                 regno);
7982                         return -EINVAL;
7983                 }
7984                 return __check_ptr_off_reg(env, reg, regno, false);
7985         }
7986
7987         switch (type) {
7988         /* Pointer types where both fixed and variable offset is explicitly allowed: */
7989         case PTR_TO_STACK:
7990         case PTR_TO_PACKET:
7991         case PTR_TO_PACKET_META:
7992         case PTR_TO_MAP_KEY:
7993         case PTR_TO_MAP_VALUE:
7994         case PTR_TO_MEM:
7995         case PTR_TO_MEM | MEM_RDONLY:
7996         case PTR_TO_MEM | MEM_RINGBUF:
7997         case PTR_TO_BUF:
7998         case PTR_TO_BUF | MEM_RDONLY:
7999         case SCALAR_VALUE:
8000                 return 0;
8001         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8002          * fixed offset.
8003          */
8004         case PTR_TO_BTF_ID:
8005         case PTR_TO_BTF_ID | MEM_ALLOC:
8006         case PTR_TO_BTF_ID | PTR_TRUSTED:
8007         case PTR_TO_BTF_ID | MEM_RCU:
8008         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8009                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8010                  * its fixed offset must be 0. In the other cases, fixed offset
8011                  * can be non-zero. This was already checked above. So pass
8012                  * fixed_off_ok as true to allow fixed offset for all other
8013                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8014                  * still need to do checks instead of returning.
8015                  */
8016                 return __check_ptr_off_reg(env, reg, regno, true);
8017         default:
8018                 return __check_ptr_off_reg(env, reg, regno, false);
8019         }
8020 }
8021
8022 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8023                                                 const struct bpf_func_proto *fn,
8024                                                 struct bpf_reg_state *regs)
8025 {
8026         struct bpf_reg_state *state = NULL;
8027         int i;
8028
8029         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8030                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8031                         if (state) {
8032                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8033                                 return NULL;
8034                         }
8035                         state = &regs[BPF_REG_1 + i];
8036                 }
8037
8038         if (!state)
8039                 verbose(env, "verifier internal error: no dynptr arg found\n");
8040
8041         return state;
8042 }
8043
8044 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8045 {
8046         struct bpf_func_state *state = func(env, reg);
8047         int spi;
8048
8049         if (reg->type == CONST_PTR_TO_DYNPTR)
8050                 return reg->id;
8051         spi = dynptr_get_spi(env, reg);
8052         if (spi < 0)
8053                 return spi;
8054         return state->stack[spi].spilled_ptr.id;
8055 }
8056
8057 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8058 {
8059         struct bpf_func_state *state = func(env, reg);
8060         int spi;
8061
8062         if (reg->type == CONST_PTR_TO_DYNPTR)
8063                 return reg->ref_obj_id;
8064         spi = dynptr_get_spi(env, reg);
8065         if (spi < 0)
8066                 return spi;
8067         return state->stack[spi].spilled_ptr.ref_obj_id;
8068 }
8069
8070 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8071                                             struct bpf_reg_state *reg)
8072 {
8073         struct bpf_func_state *state = func(env, reg);
8074         int spi;
8075
8076         if (reg->type == CONST_PTR_TO_DYNPTR)
8077                 return reg->dynptr.type;
8078
8079         spi = __get_spi(reg->off);
8080         if (spi < 0) {
8081                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8082                 return BPF_DYNPTR_TYPE_INVALID;
8083         }
8084
8085         return state->stack[spi].spilled_ptr.dynptr.type;
8086 }
8087
8088 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8089                           struct bpf_call_arg_meta *meta,
8090                           const struct bpf_func_proto *fn,
8091                           int insn_idx)
8092 {
8093         u32 regno = BPF_REG_1 + arg;
8094         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8095         enum bpf_arg_type arg_type = fn->arg_type[arg];
8096         enum bpf_reg_type type = reg->type;
8097         u32 *arg_btf_id = NULL;
8098         int err = 0;
8099
8100         if (arg_type == ARG_DONTCARE)
8101                 return 0;
8102
8103         err = check_reg_arg(env, regno, SRC_OP);
8104         if (err)
8105                 return err;
8106
8107         if (arg_type == ARG_ANYTHING) {
8108                 if (is_pointer_value(env, regno)) {
8109                         verbose(env, "R%d leaks addr into helper function\n",
8110                                 regno);
8111                         return -EACCES;
8112                 }
8113                 return 0;
8114         }
8115
8116         if (type_is_pkt_pointer(type) &&
8117             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8118                 verbose(env, "helper access to the packet is not allowed\n");
8119                 return -EACCES;
8120         }
8121
8122         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8123                 err = resolve_map_arg_type(env, meta, &arg_type);
8124                 if (err)
8125                         return err;
8126         }
8127
8128         if (register_is_null(reg) && type_may_be_null(arg_type))
8129                 /* A NULL register has a SCALAR_VALUE type, so skip
8130                  * type checking.
8131                  */
8132                 goto skip_type_check;
8133
8134         /* arg_btf_id and arg_size are in a union. */
8135         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8136             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8137                 arg_btf_id = fn->arg_btf_id[arg];
8138
8139         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8140         if (err)
8141                 return err;
8142
8143         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8144         if (err)
8145                 return err;
8146
8147 skip_type_check:
8148         if (arg_type_is_release(arg_type)) {
8149                 if (arg_type_is_dynptr(arg_type)) {
8150                         struct bpf_func_state *state = func(env, reg);
8151                         int spi;
8152
8153                         /* Only dynptr created on stack can be released, thus
8154                          * the get_spi and stack state checks for spilled_ptr
8155                          * should only be done before process_dynptr_func for
8156                          * PTR_TO_STACK.
8157                          */
8158                         if (reg->type == PTR_TO_STACK) {
8159                                 spi = dynptr_get_spi(env, reg);
8160                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8161                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8162                                         return -EINVAL;
8163                                 }
8164                         } else {
8165                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8166                                 return -EINVAL;
8167                         }
8168                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8169                         verbose(env, "R%d must be referenced when passed to release function\n",
8170                                 regno);
8171                         return -EINVAL;
8172                 }
8173                 if (meta->release_regno) {
8174                         verbose(env, "verifier internal error: more than one release argument\n");
8175                         return -EFAULT;
8176                 }
8177                 meta->release_regno = regno;
8178         }
8179
8180         if (reg->ref_obj_id) {
8181                 if (meta->ref_obj_id) {
8182                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8183                                 regno, reg->ref_obj_id,
8184                                 meta->ref_obj_id);
8185                         return -EFAULT;
8186                 }
8187                 meta->ref_obj_id = reg->ref_obj_id;
8188         }
8189
8190         switch (base_type(arg_type)) {
8191         case ARG_CONST_MAP_PTR:
8192                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8193                 if (meta->map_ptr) {
8194                         /* Use map_uid (which is unique id of inner map) to reject:
8195                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8196                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8197                          * if (inner_map1 && inner_map2) {
8198                          *     timer = bpf_map_lookup_elem(inner_map1);
8199                          *     if (timer)
8200                          *         // mismatch would have been allowed
8201                          *         bpf_timer_init(timer, inner_map2);
8202                          * }
8203                          *
8204                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8205                          */
8206                         if (meta->map_ptr != reg->map_ptr ||
8207                             meta->map_uid != reg->map_uid) {
8208                                 verbose(env,
8209                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8210                                         meta->map_uid, reg->map_uid);
8211                                 return -EINVAL;
8212                         }
8213                 }
8214                 meta->map_ptr = reg->map_ptr;
8215                 meta->map_uid = reg->map_uid;
8216                 break;
8217         case ARG_PTR_TO_MAP_KEY:
8218                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8219                  * check that [key, key + map->key_size) are within
8220                  * stack limits and initialized
8221                  */
8222                 if (!meta->map_ptr) {
8223                         /* in function declaration map_ptr must come before
8224                          * map_key, so that it's verified and known before
8225                          * we have to check map_key here. Otherwise it means
8226                          * that kernel subsystem misconfigured verifier
8227                          */
8228                         verbose(env, "invalid map_ptr to access map->key\n");
8229                         return -EACCES;
8230                 }
8231                 err = check_helper_mem_access(env, regno,
8232                                               meta->map_ptr->key_size, false,
8233                                               NULL);
8234                 break;
8235         case ARG_PTR_TO_MAP_VALUE:
8236                 if (type_may_be_null(arg_type) && register_is_null(reg))
8237                         return 0;
8238
8239                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8240                  * check [value, value + map->value_size) validity
8241                  */
8242                 if (!meta->map_ptr) {
8243                         /* kernel subsystem misconfigured verifier */
8244                         verbose(env, "invalid map_ptr to access map->value\n");
8245                         return -EACCES;
8246                 }
8247                 meta->raw_mode = arg_type & MEM_UNINIT;
8248                 err = check_helper_mem_access(env, regno,
8249                                               meta->map_ptr->value_size, false,
8250                                               meta);
8251                 break;
8252         case ARG_PTR_TO_PERCPU_BTF_ID:
8253                 if (!reg->btf_id) {
8254                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8255                         return -EACCES;
8256                 }
8257                 meta->ret_btf = reg->btf;
8258                 meta->ret_btf_id = reg->btf_id;
8259                 break;
8260         case ARG_PTR_TO_SPIN_LOCK:
8261                 if (in_rbtree_lock_required_cb(env)) {
8262                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8263                         return -EACCES;
8264                 }
8265                 if (meta->func_id == BPF_FUNC_spin_lock) {
8266                         err = process_spin_lock(env, regno, true);
8267                         if (err)
8268                                 return err;
8269                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8270                         err = process_spin_lock(env, regno, false);
8271                         if (err)
8272                                 return err;
8273                 } else {
8274                         verbose(env, "verifier internal error\n");
8275                         return -EFAULT;
8276                 }
8277                 break;
8278         case ARG_PTR_TO_TIMER:
8279                 err = process_timer_func(env, regno, meta);
8280                 if (err)
8281                         return err;
8282                 break;
8283         case ARG_PTR_TO_FUNC:
8284                 meta->subprogno = reg->subprogno;
8285                 break;
8286         case ARG_PTR_TO_MEM:
8287                 /* The access to this pointer is only checked when we hit the
8288                  * next is_mem_size argument below.
8289                  */
8290                 meta->raw_mode = arg_type & MEM_UNINIT;
8291                 if (arg_type & MEM_FIXED_SIZE) {
8292                         err = check_helper_mem_access(env, regno,
8293                                                       fn->arg_size[arg], false,
8294                                                       meta);
8295                 }
8296                 break;
8297         case ARG_CONST_SIZE:
8298                 err = check_mem_size_reg(env, reg, regno, false, meta);
8299                 break;
8300         case ARG_CONST_SIZE_OR_ZERO:
8301                 err = check_mem_size_reg(env, reg, regno, true, meta);
8302                 break;
8303         case ARG_PTR_TO_DYNPTR:
8304                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8305                 if (err)
8306                         return err;
8307                 break;
8308         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8309                 if (!tnum_is_const(reg->var_off)) {
8310                         verbose(env, "R%d is not a known constant'\n",
8311                                 regno);
8312                         return -EACCES;
8313                 }
8314                 meta->mem_size = reg->var_off.value;
8315                 err = mark_chain_precision(env, regno);
8316                 if (err)
8317                         return err;
8318                 break;
8319         case ARG_PTR_TO_INT:
8320         case ARG_PTR_TO_LONG:
8321         {
8322                 int size = int_ptr_type_to_size(arg_type);
8323
8324                 err = check_helper_mem_access(env, regno, size, false, meta);
8325                 if (err)
8326                         return err;
8327                 err = check_ptr_alignment(env, reg, 0, size, true);
8328                 break;
8329         }
8330         case ARG_PTR_TO_CONST_STR:
8331         {
8332                 struct bpf_map *map = reg->map_ptr;
8333                 int map_off;
8334                 u64 map_addr;
8335                 char *str_ptr;
8336
8337                 if (!bpf_map_is_rdonly(map)) {
8338                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8339                         return -EACCES;
8340                 }
8341
8342                 if (!tnum_is_const(reg->var_off)) {
8343                         verbose(env, "R%d is not a constant address'\n", regno);
8344                         return -EACCES;
8345                 }
8346
8347                 if (!map->ops->map_direct_value_addr) {
8348                         verbose(env, "no direct value access support for this map type\n");
8349                         return -EACCES;
8350                 }
8351
8352                 err = check_map_access(env, regno, reg->off,
8353                                        map->value_size - reg->off, false,
8354                                        ACCESS_HELPER);
8355                 if (err)
8356                         return err;
8357
8358                 map_off = reg->off + reg->var_off.value;
8359                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8360                 if (err) {
8361                         verbose(env, "direct value access on string failed\n");
8362                         return err;
8363                 }
8364
8365                 str_ptr = (char *)(long)(map_addr);
8366                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8367                         verbose(env, "string is not zero-terminated\n");
8368                         return -EINVAL;
8369                 }
8370                 break;
8371         }
8372         case ARG_PTR_TO_KPTR:
8373                 err = process_kptr_func(env, regno, meta);
8374                 if (err)
8375                         return err;
8376                 break;
8377         }
8378
8379         return err;
8380 }
8381
8382 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8383 {
8384         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8385         enum bpf_prog_type type = resolve_prog_type(env->prog);
8386
8387         if (func_id != BPF_FUNC_map_update_elem)
8388                 return false;
8389
8390         /* It's not possible to get access to a locked struct sock in these
8391          * contexts, so updating is safe.
8392          */
8393         switch (type) {
8394         case BPF_PROG_TYPE_TRACING:
8395                 if (eatype == BPF_TRACE_ITER)
8396                         return true;
8397                 break;
8398         case BPF_PROG_TYPE_SOCKET_FILTER:
8399         case BPF_PROG_TYPE_SCHED_CLS:
8400         case BPF_PROG_TYPE_SCHED_ACT:
8401         case BPF_PROG_TYPE_XDP:
8402         case BPF_PROG_TYPE_SK_REUSEPORT:
8403         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8404         case BPF_PROG_TYPE_SK_LOOKUP:
8405                 return true;
8406         default:
8407                 break;
8408         }
8409
8410         verbose(env, "cannot update sockmap in this context\n");
8411         return false;
8412 }
8413
8414 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8415 {
8416         return env->prog->jit_requested &&
8417                bpf_jit_supports_subprog_tailcalls();
8418 }
8419
8420 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8421                                         struct bpf_map *map, int func_id)
8422 {
8423         if (!map)
8424                 return 0;
8425
8426         /* We need a two way check, first is from map perspective ... */
8427         switch (map->map_type) {
8428         case BPF_MAP_TYPE_PROG_ARRAY:
8429                 if (func_id != BPF_FUNC_tail_call)
8430                         goto error;
8431                 break;
8432         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8433                 if (func_id != BPF_FUNC_perf_event_read &&
8434                     func_id != BPF_FUNC_perf_event_output &&
8435                     func_id != BPF_FUNC_skb_output &&
8436                     func_id != BPF_FUNC_perf_event_read_value &&
8437                     func_id != BPF_FUNC_xdp_output)
8438                         goto error;
8439                 break;
8440         case BPF_MAP_TYPE_RINGBUF:
8441                 if (func_id != BPF_FUNC_ringbuf_output &&
8442                     func_id != BPF_FUNC_ringbuf_reserve &&
8443                     func_id != BPF_FUNC_ringbuf_query &&
8444                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8445                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8446                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8447                         goto error;
8448                 break;
8449         case BPF_MAP_TYPE_USER_RINGBUF:
8450                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8451                         goto error;
8452                 break;
8453         case BPF_MAP_TYPE_STACK_TRACE:
8454                 if (func_id != BPF_FUNC_get_stackid)
8455                         goto error;
8456                 break;
8457         case BPF_MAP_TYPE_CGROUP_ARRAY:
8458                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8459                     func_id != BPF_FUNC_current_task_under_cgroup)
8460                         goto error;
8461                 break;
8462         case BPF_MAP_TYPE_CGROUP_STORAGE:
8463         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8464                 if (func_id != BPF_FUNC_get_local_storage)
8465                         goto error;
8466                 break;
8467         case BPF_MAP_TYPE_DEVMAP:
8468         case BPF_MAP_TYPE_DEVMAP_HASH:
8469                 if (func_id != BPF_FUNC_redirect_map &&
8470                     func_id != BPF_FUNC_map_lookup_elem)
8471                         goto error;
8472                 break;
8473         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8474          * appear.
8475          */
8476         case BPF_MAP_TYPE_CPUMAP:
8477                 if (func_id != BPF_FUNC_redirect_map)
8478                         goto error;
8479                 break;
8480         case BPF_MAP_TYPE_XSKMAP:
8481                 if (func_id != BPF_FUNC_redirect_map &&
8482                     func_id != BPF_FUNC_map_lookup_elem)
8483                         goto error;
8484                 break;
8485         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8486         case BPF_MAP_TYPE_HASH_OF_MAPS:
8487                 if (func_id != BPF_FUNC_map_lookup_elem)
8488                         goto error;
8489                 break;
8490         case BPF_MAP_TYPE_SOCKMAP:
8491                 if (func_id != BPF_FUNC_sk_redirect_map &&
8492                     func_id != BPF_FUNC_sock_map_update &&
8493                     func_id != BPF_FUNC_map_delete_elem &&
8494                     func_id != BPF_FUNC_msg_redirect_map &&
8495                     func_id != BPF_FUNC_sk_select_reuseport &&
8496                     func_id != BPF_FUNC_map_lookup_elem &&
8497                     !may_update_sockmap(env, func_id))
8498                         goto error;
8499                 break;
8500         case BPF_MAP_TYPE_SOCKHASH:
8501                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8502                     func_id != BPF_FUNC_sock_hash_update &&
8503                     func_id != BPF_FUNC_map_delete_elem &&
8504                     func_id != BPF_FUNC_msg_redirect_hash &&
8505                     func_id != BPF_FUNC_sk_select_reuseport &&
8506                     func_id != BPF_FUNC_map_lookup_elem &&
8507                     !may_update_sockmap(env, func_id))
8508                         goto error;
8509                 break;
8510         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8511                 if (func_id != BPF_FUNC_sk_select_reuseport)
8512                         goto error;
8513                 break;
8514         case BPF_MAP_TYPE_QUEUE:
8515         case BPF_MAP_TYPE_STACK:
8516                 if (func_id != BPF_FUNC_map_peek_elem &&
8517                     func_id != BPF_FUNC_map_pop_elem &&
8518                     func_id != BPF_FUNC_map_push_elem)
8519                         goto error;
8520                 break;
8521         case BPF_MAP_TYPE_SK_STORAGE:
8522                 if (func_id != BPF_FUNC_sk_storage_get &&
8523                     func_id != BPF_FUNC_sk_storage_delete &&
8524                     func_id != BPF_FUNC_kptr_xchg)
8525                         goto error;
8526                 break;
8527         case BPF_MAP_TYPE_INODE_STORAGE:
8528                 if (func_id != BPF_FUNC_inode_storage_get &&
8529                     func_id != BPF_FUNC_inode_storage_delete &&
8530                     func_id != BPF_FUNC_kptr_xchg)
8531                         goto error;
8532                 break;
8533         case BPF_MAP_TYPE_TASK_STORAGE:
8534                 if (func_id != BPF_FUNC_task_storage_get &&
8535                     func_id != BPF_FUNC_task_storage_delete &&
8536                     func_id != BPF_FUNC_kptr_xchg)
8537                         goto error;
8538                 break;
8539         case BPF_MAP_TYPE_CGRP_STORAGE:
8540                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8541                     func_id != BPF_FUNC_cgrp_storage_delete &&
8542                     func_id != BPF_FUNC_kptr_xchg)
8543                         goto error;
8544                 break;
8545         case BPF_MAP_TYPE_BLOOM_FILTER:
8546                 if (func_id != BPF_FUNC_map_peek_elem &&
8547                     func_id != BPF_FUNC_map_push_elem)
8548                         goto error;
8549                 break;
8550         default:
8551                 break;
8552         }
8553
8554         /* ... and second from the function itself. */
8555         switch (func_id) {
8556         case BPF_FUNC_tail_call:
8557                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8558                         goto error;
8559                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8560                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8561                         return -EINVAL;
8562                 }
8563                 break;
8564         case BPF_FUNC_perf_event_read:
8565         case BPF_FUNC_perf_event_output:
8566         case BPF_FUNC_perf_event_read_value:
8567         case BPF_FUNC_skb_output:
8568         case BPF_FUNC_xdp_output:
8569                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8570                         goto error;
8571                 break;
8572         case BPF_FUNC_ringbuf_output:
8573         case BPF_FUNC_ringbuf_reserve:
8574         case BPF_FUNC_ringbuf_query:
8575         case BPF_FUNC_ringbuf_reserve_dynptr:
8576         case BPF_FUNC_ringbuf_submit_dynptr:
8577         case BPF_FUNC_ringbuf_discard_dynptr:
8578                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8579                         goto error;
8580                 break;
8581         case BPF_FUNC_user_ringbuf_drain:
8582                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8583                         goto error;
8584                 break;
8585         case BPF_FUNC_get_stackid:
8586                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8587                         goto error;
8588                 break;
8589         case BPF_FUNC_current_task_under_cgroup:
8590         case BPF_FUNC_skb_under_cgroup:
8591                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8592                         goto error;
8593                 break;
8594         case BPF_FUNC_redirect_map:
8595                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8596                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8597                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8598                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8599                         goto error;
8600                 break;
8601         case BPF_FUNC_sk_redirect_map:
8602         case BPF_FUNC_msg_redirect_map:
8603         case BPF_FUNC_sock_map_update:
8604                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8605                         goto error;
8606                 break;
8607         case BPF_FUNC_sk_redirect_hash:
8608         case BPF_FUNC_msg_redirect_hash:
8609         case BPF_FUNC_sock_hash_update:
8610                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8611                         goto error;
8612                 break;
8613         case BPF_FUNC_get_local_storage:
8614                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8615                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8616                         goto error;
8617                 break;
8618         case BPF_FUNC_sk_select_reuseport:
8619                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8620                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8621                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8622                         goto error;
8623                 break;
8624         case BPF_FUNC_map_pop_elem:
8625                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8626                     map->map_type != BPF_MAP_TYPE_STACK)
8627                         goto error;
8628                 break;
8629         case BPF_FUNC_map_peek_elem:
8630         case BPF_FUNC_map_push_elem:
8631                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8632                     map->map_type != BPF_MAP_TYPE_STACK &&
8633                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8634                         goto error;
8635                 break;
8636         case BPF_FUNC_map_lookup_percpu_elem:
8637                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8638                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8639                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8640                         goto error;
8641                 break;
8642         case BPF_FUNC_sk_storage_get:
8643         case BPF_FUNC_sk_storage_delete:
8644                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8645                         goto error;
8646                 break;
8647         case BPF_FUNC_inode_storage_get:
8648         case BPF_FUNC_inode_storage_delete:
8649                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8650                         goto error;
8651                 break;
8652         case BPF_FUNC_task_storage_get:
8653         case BPF_FUNC_task_storage_delete:
8654                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8655                         goto error;
8656                 break;
8657         case BPF_FUNC_cgrp_storage_get:
8658         case BPF_FUNC_cgrp_storage_delete:
8659                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8660                         goto error;
8661                 break;
8662         default:
8663                 break;
8664         }
8665
8666         return 0;
8667 error:
8668         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8669                 map->map_type, func_id_name(func_id), func_id);
8670         return -EINVAL;
8671 }
8672
8673 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8674 {
8675         int count = 0;
8676
8677         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8678                 count++;
8679         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8680                 count++;
8681         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8682                 count++;
8683         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8684                 count++;
8685         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8686                 count++;
8687
8688         /* We only support one arg being in raw mode at the moment,
8689          * which is sufficient for the helper functions we have
8690          * right now.
8691          */
8692         return count <= 1;
8693 }
8694
8695 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8696 {
8697         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8698         bool has_size = fn->arg_size[arg] != 0;
8699         bool is_next_size = false;
8700
8701         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8702                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8703
8704         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8705                 return is_next_size;
8706
8707         return has_size == is_next_size || is_next_size == is_fixed;
8708 }
8709
8710 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8711 {
8712         /* bpf_xxx(..., buf, len) call will access 'len'
8713          * bytes from memory 'buf'. Both arg types need
8714          * to be paired, so make sure there's no buggy
8715          * helper function specification.
8716          */
8717         if (arg_type_is_mem_size(fn->arg1_type) ||
8718             check_args_pair_invalid(fn, 0) ||
8719             check_args_pair_invalid(fn, 1) ||
8720             check_args_pair_invalid(fn, 2) ||
8721             check_args_pair_invalid(fn, 3) ||
8722             check_args_pair_invalid(fn, 4))
8723                 return false;
8724
8725         return true;
8726 }
8727
8728 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8729 {
8730         int i;
8731
8732         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8733                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8734                         return !!fn->arg_btf_id[i];
8735                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8736                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8737                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8738                     /* arg_btf_id and arg_size are in a union. */
8739                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8740                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8741                         return false;
8742         }
8743
8744         return true;
8745 }
8746
8747 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8748 {
8749         return check_raw_mode_ok(fn) &&
8750                check_arg_pair_ok(fn) &&
8751                check_btf_id_ok(fn) ? 0 : -EINVAL;
8752 }
8753
8754 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8755  * are now invalid, so turn them into unknown SCALAR_VALUE.
8756  *
8757  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8758  * since these slices point to packet data.
8759  */
8760 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8761 {
8762         struct bpf_func_state *state;
8763         struct bpf_reg_state *reg;
8764
8765         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8766                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8767                         mark_reg_invalid(env, reg);
8768         }));
8769 }
8770
8771 enum {
8772         AT_PKT_END = -1,
8773         BEYOND_PKT_END = -2,
8774 };
8775
8776 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8777 {
8778         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8779         struct bpf_reg_state *reg = &state->regs[regn];
8780
8781         if (reg->type != PTR_TO_PACKET)
8782                 /* PTR_TO_PACKET_META is not supported yet */
8783                 return;
8784
8785         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8786          * How far beyond pkt_end it goes is unknown.
8787          * if (!range_open) it's the case of pkt >= pkt_end
8788          * if (range_open) it's the case of pkt > pkt_end
8789          * hence this pointer is at least 1 byte bigger than pkt_end
8790          */
8791         if (range_open)
8792                 reg->range = BEYOND_PKT_END;
8793         else
8794                 reg->range = AT_PKT_END;
8795 }
8796
8797 /* The pointer with the specified id has released its reference to kernel
8798  * resources. Identify all copies of the same pointer and clear the reference.
8799  */
8800 static int release_reference(struct bpf_verifier_env *env,
8801                              int ref_obj_id)
8802 {
8803         struct bpf_func_state *state;
8804         struct bpf_reg_state *reg;
8805         int err;
8806
8807         err = release_reference_state(cur_func(env), ref_obj_id);
8808         if (err)
8809                 return err;
8810
8811         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8812                 if (reg->ref_obj_id == ref_obj_id)
8813                         mark_reg_invalid(env, reg);
8814         }));
8815
8816         return 0;
8817 }
8818
8819 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8820 {
8821         struct bpf_func_state *unused;
8822         struct bpf_reg_state *reg;
8823
8824         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8825                 if (type_is_non_owning_ref(reg->type))
8826                         mark_reg_invalid(env, reg);
8827         }));
8828 }
8829
8830 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8831                                     struct bpf_reg_state *regs)
8832 {
8833         int i;
8834
8835         /* after the call registers r0 - r5 were scratched */
8836         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8837                 mark_reg_not_init(env, regs, caller_saved[i]);
8838                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8839         }
8840 }
8841
8842 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8843                                    struct bpf_func_state *caller,
8844                                    struct bpf_func_state *callee,
8845                                    int insn_idx);
8846
8847 static int set_callee_state(struct bpf_verifier_env *env,
8848                             struct bpf_func_state *caller,
8849                             struct bpf_func_state *callee, int insn_idx);
8850
8851 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8852                              int *insn_idx, int subprog,
8853                              set_callee_state_fn set_callee_state_cb)
8854 {
8855         struct bpf_verifier_state *state = env->cur_state;
8856         struct bpf_func_state *caller, *callee;
8857         int err;
8858
8859         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8860                 verbose(env, "the call stack of %d frames is too deep\n",
8861                         state->curframe + 2);
8862                 return -E2BIG;
8863         }
8864
8865         caller = state->frame[state->curframe];
8866         if (state->frame[state->curframe + 1]) {
8867                 verbose(env, "verifier bug. Frame %d already allocated\n",
8868                         state->curframe + 1);
8869                 return -EFAULT;
8870         }
8871
8872         err = btf_check_subprog_call(env, subprog, caller->regs);
8873         if (err == -EFAULT)
8874                 return err;
8875         if (subprog_is_global(env, subprog)) {
8876                 if (err) {
8877                         verbose(env, "Caller passes invalid args into func#%d\n",
8878                                 subprog);
8879                         return err;
8880                 } else {
8881                         if (env->log.level & BPF_LOG_LEVEL)
8882                                 verbose(env,
8883                                         "Func#%d is global and valid. Skipping.\n",
8884                                         subprog);
8885                         clear_caller_saved_regs(env, caller->regs);
8886
8887                         /* All global functions return a 64-bit SCALAR_VALUE */
8888                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8889                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8890
8891                         /* continue with next insn after call */
8892                         return 0;
8893                 }
8894         }
8895
8896         /* set_callee_state is used for direct subprog calls, but we are
8897          * interested in validating only BPF helpers that can call subprogs as
8898          * callbacks
8899          */
8900         if (set_callee_state_cb != set_callee_state) {
8901                 if (bpf_pseudo_kfunc_call(insn) &&
8902                     !is_callback_calling_kfunc(insn->imm)) {
8903                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8904                                 func_id_name(insn->imm), insn->imm);
8905                         return -EFAULT;
8906                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8907                            !is_callback_calling_function(insn->imm)) { /* helper */
8908                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8909                                 func_id_name(insn->imm), insn->imm);
8910                         return -EFAULT;
8911                 }
8912         }
8913
8914         if (insn->code == (BPF_JMP | BPF_CALL) &&
8915             insn->src_reg == 0 &&
8916             insn->imm == BPF_FUNC_timer_set_callback) {
8917                 struct bpf_verifier_state *async_cb;
8918
8919                 /* there is no real recursion here. timer callbacks are async */
8920                 env->subprog_info[subprog].is_async_cb = true;
8921                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8922                                          *insn_idx, subprog);
8923                 if (!async_cb)
8924                         return -EFAULT;
8925                 callee = async_cb->frame[0];
8926                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8927
8928                 /* Convert bpf_timer_set_callback() args into timer callback args */
8929                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8930                 if (err)
8931                         return err;
8932
8933                 clear_caller_saved_regs(env, caller->regs);
8934                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8935                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8936                 /* continue with next insn after call */
8937                 return 0;
8938         }
8939
8940         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8941         if (!callee)
8942                 return -ENOMEM;
8943         state->frame[state->curframe + 1] = callee;
8944
8945         /* callee cannot access r0, r6 - r9 for reading and has to write
8946          * into its own stack before reading from it.
8947          * callee can read/write into caller's stack
8948          */
8949         init_func_state(env, callee,
8950                         /* remember the callsite, it will be used by bpf_exit */
8951                         *insn_idx /* callsite */,
8952                         state->curframe + 1 /* frameno within this callchain */,
8953                         subprog /* subprog number within this prog */);
8954
8955         /* Transfer references to the callee */
8956         err = copy_reference_state(callee, caller);
8957         if (err)
8958                 goto err_out;
8959
8960         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8961         if (err)
8962                 goto err_out;
8963
8964         clear_caller_saved_regs(env, caller->regs);
8965
8966         /* only increment it after check_reg_arg() finished */
8967         state->curframe++;
8968
8969         /* and go analyze first insn of the callee */
8970         *insn_idx = env->subprog_info[subprog].start - 1;
8971
8972         if (env->log.level & BPF_LOG_LEVEL) {
8973                 verbose(env, "caller:\n");
8974                 print_verifier_state(env, caller, true);
8975                 verbose(env, "callee:\n");
8976                 print_verifier_state(env, callee, true);
8977         }
8978         return 0;
8979
8980 err_out:
8981         free_func_state(callee);
8982         state->frame[state->curframe + 1] = NULL;
8983         return err;
8984 }
8985
8986 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
8987                                    struct bpf_func_state *caller,
8988                                    struct bpf_func_state *callee)
8989 {
8990         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
8991          *      void *callback_ctx, u64 flags);
8992          * callback_fn(struct bpf_map *map, void *key, void *value,
8993          *      void *callback_ctx);
8994          */
8995         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
8996
8997         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
8998         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
8999         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9000
9001         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9002         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9003         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9004
9005         /* pointer to stack or null */
9006         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9007
9008         /* unused */
9009         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9010         return 0;
9011 }
9012
9013 static int set_callee_state(struct bpf_verifier_env *env,
9014                             struct bpf_func_state *caller,
9015                             struct bpf_func_state *callee, int insn_idx)
9016 {
9017         int i;
9018
9019         /* copy r1 - r5 args that callee can access.  The copy includes parent
9020          * pointers, which connects us up to the liveness chain
9021          */
9022         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9023                 callee->regs[i] = caller->regs[i];
9024         return 0;
9025 }
9026
9027 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9028                            int *insn_idx)
9029 {
9030         int subprog, target_insn;
9031
9032         target_insn = *insn_idx + insn->imm + 1;
9033         subprog = find_subprog(env, target_insn);
9034         if (subprog < 0) {
9035                 verbose(env, "verifier bug. No program starts at insn %d\n",
9036                         target_insn);
9037                 return -EFAULT;
9038         }
9039
9040         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9041 }
9042
9043 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9044                                        struct bpf_func_state *caller,
9045                                        struct bpf_func_state *callee,
9046                                        int insn_idx)
9047 {
9048         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9049         struct bpf_map *map;
9050         int err;
9051
9052         if (bpf_map_ptr_poisoned(insn_aux)) {
9053                 verbose(env, "tail_call abusing map_ptr\n");
9054                 return -EINVAL;
9055         }
9056
9057         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9058         if (!map->ops->map_set_for_each_callback_args ||
9059             !map->ops->map_for_each_callback) {
9060                 verbose(env, "callback function not allowed for map\n");
9061                 return -ENOTSUPP;
9062         }
9063
9064         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9065         if (err)
9066                 return err;
9067
9068         callee->in_callback_fn = true;
9069         callee->callback_ret_range = tnum_range(0, 1);
9070         return 0;
9071 }
9072
9073 static int set_loop_callback_state(struct bpf_verifier_env *env,
9074                                    struct bpf_func_state *caller,
9075                                    struct bpf_func_state *callee,
9076                                    int insn_idx)
9077 {
9078         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9079          *          u64 flags);
9080          * callback_fn(u32 index, void *callback_ctx);
9081          */
9082         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9083         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9084
9085         /* unused */
9086         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9087         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9088         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9089
9090         callee->in_callback_fn = true;
9091         callee->callback_ret_range = tnum_range(0, 1);
9092         return 0;
9093 }
9094
9095 static int set_timer_callback_state(struct bpf_verifier_env *env,
9096                                     struct bpf_func_state *caller,
9097                                     struct bpf_func_state *callee,
9098                                     int insn_idx)
9099 {
9100         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9101
9102         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9103          * callback_fn(struct bpf_map *map, void *key, void *value);
9104          */
9105         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9106         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9107         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9108
9109         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9110         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9111         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9112
9113         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9114         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9115         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9116
9117         /* unused */
9118         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9119         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9120         callee->in_async_callback_fn = true;
9121         callee->callback_ret_range = tnum_range(0, 1);
9122         return 0;
9123 }
9124
9125 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9126                                        struct bpf_func_state *caller,
9127                                        struct bpf_func_state *callee,
9128                                        int insn_idx)
9129 {
9130         /* bpf_find_vma(struct task_struct *task, u64 addr,
9131          *               void *callback_fn, void *callback_ctx, u64 flags)
9132          * (callback_fn)(struct task_struct *task,
9133          *               struct vm_area_struct *vma, void *callback_ctx);
9134          */
9135         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9136
9137         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9138         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9139         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9140         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9141
9142         /* pointer to stack or null */
9143         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9144
9145         /* unused */
9146         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9147         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9148         callee->in_callback_fn = true;
9149         callee->callback_ret_range = tnum_range(0, 1);
9150         return 0;
9151 }
9152
9153 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9154                                            struct bpf_func_state *caller,
9155                                            struct bpf_func_state *callee,
9156                                            int insn_idx)
9157 {
9158         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9159          *                        callback_ctx, u64 flags);
9160          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9161          */
9162         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9163         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9164         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9165
9166         /* unused */
9167         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9168         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9169         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9170
9171         callee->in_callback_fn = true;
9172         callee->callback_ret_range = tnum_range(0, 1);
9173         return 0;
9174 }
9175
9176 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9177                                          struct bpf_func_state *caller,
9178                                          struct bpf_func_state *callee,
9179                                          int insn_idx)
9180 {
9181         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9182          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9183          *
9184          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9185          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9186          * by this point, so look at 'root'
9187          */
9188         struct btf_field *field;
9189
9190         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9191                                       BPF_RB_ROOT);
9192         if (!field || !field->graph_root.value_btf_id)
9193                 return -EFAULT;
9194
9195         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9196         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9197         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9198         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9199
9200         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9201         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9202         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9203         callee->in_callback_fn = true;
9204         callee->callback_ret_range = tnum_range(0, 1);
9205         return 0;
9206 }
9207
9208 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9209
9210 /* Are we currently verifying the callback for a rbtree helper that must
9211  * be called with lock held? If so, no need to complain about unreleased
9212  * lock
9213  */
9214 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9215 {
9216         struct bpf_verifier_state *state = env->cur_state;
9217         struct bpf_insn *insn = env->prog->insnsi;
9218         struct bpf_func_state *callee;
9219         int kfunc_btf_id;
9220
9221         if (!state->curframe)
9222                 return false;
9223
9224         callee = state->frame[state->curframe];
9225
9226         if (!callee->in_callback_fn)
9227                 return false;
9228
9229         kfunc_btf_id = insn[callee->callsite].imm;
9230         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9231 }
9232
9233 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9234 {
9235         struct bpf_verifier_state *state = env->cur_state;
9236         struct bpf_func_state *caller, *callee;
9237         struct bpf_reg_state *r0;
9238         int err;
9239
9240         callee = state->frame[state->curframe];
9241         r0 = &callee->regs[BPF_REG_0];
9242         if (r0->type == PTR_TO_STACK) {
9243                 /* technically it's ok to return caller's stack pointer
9244                  * (or caller's caller's pointer) back to the caller,
9245                  * since these pointers are valid. Only current stack
9246                  * pointer will be invalid as soon as function exits,
9247                  * but let's be conservative
9248                  */
9249                 verbose(env, "cannot return stack pointer to the caller\n");
9250                 return -EINVAL;
9251         }
9252
9253         caller = state->frame[state->curframe - 1];
9254         if (callee->in_callback_fn) {
9255                 /* enforce R0 return value range [0, 1]. */
9256                 struct tnum range = callee->callback_ret_range;
9257
9258                 if (r0->type != SCALAR_VALUE) {
9259                         verbose(env, "R0 not a scalar value\n");
9260                         return -EACCES;
9261                 }
9262                 if (!tnum_in(range, r0->var_off)) {
9263                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9264                         return -EINVAL;
9265                 }
9266         } else {
9267                 /* return to the caller whatever r0 had in the callee */
9268                 caller->regs[BPF_REG_0] = *r0;
9269         }
9270
9271         /* callback_fn frame should have released its own additions to parent's
9272          * reference state at this point, or check_reference_leak would
9273          * complain, hence it must be the same as the caller. There is no need
9274          * to copy it back.
9275          */
9276         if (!callee->in_callback_fn) {
9277                 /* Transfer references to the caller */
9278                 err = copy_reference_state(caller, callee);
9279                 if (err)
9280                         return err;
9281         }
9282
9283         *insn_idx = callee->callsite + 1;
9284         if (env->log.level & BPF_LOG_LEVEL) {
9285                 verbose(env, "returning from callee:\n");
9286                 print_verifier_state(env, callee, true);
9287                 verbose(env, "to caller at %d:\n", *insn_idx);
9288                 print_verifier_state(env, caller, true);
9289         }
9290         /* clear everything in the callee */
9291         free_func_state(callee);
9292         state->frame[state->curframe--] = NULL;
9293         return 0;
9294 }
9295
9296 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9297                                    int func_id,
9298                                    struct bpf_call_arg_meta *meta)
9299 {
9300         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9301
9302         if (ret_type != RET_INTEGER)
9303                 return;
9304
9305         switch (func_id) {
9306         case BPF_FUNC_get_stack:
9307         case BPF_FUNC_get_task_stack:
9308         case BPF_FUNC_probe_read_str:
9309         case BPF_FUNC_probe_read_kernel_str:
9310         case BPF_FUNC_probe_read_user_str:
9311                 ret_reg->smax_value = meta->msize_max_value;
9312                 ret_reg->s32_max_value = meta->msize_max_value;
9313                 ret_reg->smin_value = -MAX_ERRNO;
9314                 ret_reg->s32_min_value = -MAX_ERRNO;
9315                 reg_bounds_sync(ret_reg);
9316                 break;
9317         case BPF_FUNC_get_smp_processor_id:
9318                 ret_reg->umax_value = nr_cpu_ids - 1;
9319                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9320                 ret_reg->smax_value = nr_cpu_ids - 1;
9321                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9322                 ret_reg->umin_value = 0;
9323                 ret_reg->u32_min_value = 0;
9324                 ret_reg->smin_value = 0;
9325                 ret_reg->s32_min_value = 0;
9326                 reg_bounds_sync(ret_reg);
9327                 break;
9328         }
9329 }
9330
9331 static int
9332 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9333                 int func_id, int insn_idx)
9334 {
9335         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9336         struct bpf_map *map = meta->map_ptr;
9337
9338         if (func_id != BPF_FUNC_tail_call &&
9339             func_id != BPF_FUNC_map_lookup_elem &&
9340             func_id != BPF_FUNC_map_update_elem &&
9341             func_id != BPF_FUNC_map_delete_elem &&
9342             func_id != BPF_FUNC_map_push_elem &&
9343             func_id != BPF_FUNC_map_pop_elem &&
9344             func_id != BPF_FUNC_map_peek_elem &&
9345             func_id != BPF_FUNC_for_each_map_elem &&
9346             func_id != BPF_FUNC_redirect_map &&
9347             func_id != BPF_FUNC_map_lookup_percpu_elem)
9348                 return 0;
9349
9350         if (map == NULL) {
9351                 verbose(env, "kernel subsystem misconfigured verifier\n");
9352                 return -EINVAL;
9353         }
9354
9355         /* In case of read-only, some additional restrictions
9356          * need to be applied in order to prevent altering the
9357          * state of the map from program side.
9358          */
9359         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9360             (func_id == BPF_FUNC_map_delete_elem ||
9361              func_id == BPF_FUNC_map_update_elem ||
9362              func_id == BPF_FUNC_map_push_elem ||
9363              func_id == BPF_FUNC_map_pop_elem)) {
9364                 verbose(env, "write into map forbidden\n");
9365                 return -EACCES;
9366         }
9367
9368         if (!BPF_MAP_PTR(aux->map_ptr_state))
9369                 bpf_map_ptr_store(aux, meta->map_ptr,
9370                                   !meta->map_ptr->bypass_spec_v1);
9371         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9372                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9373                                   !meta->map_ptr->bypass_spec_v1);
9374         return 0;
9375 }
9376
9377 static int
9378 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9379                 int func_id, int insn_idx)
9380 {
9381         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9382         struct bpf_reg_state *regs = cur_regs(env), *reg;
9383         struct bpf_map *map = meta->map_ptr;
9384         u64 val, max;
9385         int err;
9386
9387         if (func_id != BPF_FUNC_tail_call)
9388                 return 0;
9389         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9390                 verbose(env, "kernel subsystem misconfigured verifier\n");
9391                 return -EINVAL;
9392         }
9393
9394         reg = &regs[BPF_REG_3];
9395         val = reg->var_off.value;
9396         max = map->max_entries;
9397
9398         if (!(register_is_const(reg) && val < max)) {
9399                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9400                 return 0;
9401         }
9402
9403         err = mark_chain_precision(env, BPF_REG_3);
9404         if (err)
9405                 return err;
9406         if (bpf_map_key_unseen(aux))
9407                 bpf_map_key_store(aux, val);
9408         else if (!bpf_map_key_poisoned(aux) &&
9409                   bpf_map_key_immediate(aux) != val)
9410                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9411         return 0;
9412 }
9413
9414 static int check_reference_leak(struct bpf_verifier_env *env)
9415 {
9416         struct bpf_func_state *state = cur_func(env);
9417         bool refs_lingering = false;
9418         int i;
9419
9420         if (state->frameno && !state->in_callback_fn)
9421                 return 0;
9422
9423         for (i = 0; i < state->acquired_refs; i++) {
9424                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9425                         continue;
9426                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9427                         state->refs[i].id, state->refs[i].insn_idx);
9428                 refs_lingering = true;
9429         }
9430         return refs_lingering ? -EINVAL : 0;
9431 }
9432
9433 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9434                                    struct bpf_reg_state *regs)
9435 {
9436         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9437         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9438         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9439         struct bpf_bprintf_data data = {};
9440         int err, fmt_map_off, num_args;
9441         u64 fmt_addr;
9442         char *fmt;
9443
9444         /* data must be an array of u64 */
9445         if (data_len_reg->var_off.value % 8)
9446                 return -EINVAL;
9447         num_args = data_len_reg->var_off.value / 8;
9448
9449         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9450          * and map_direct_value_addr is set.
9451          */
9452         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9453         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9454                                                   fmt_map_off);
9455         if (err) {
9456                 verbose(env, "verifier bug\n");
9457                 return -EFAULT;
9458         }
9459         fmt = (char *)(long)fmt_addr + fmt_map_off;
9460
9461         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9462          * can focus on validating the format specifiers.
9463          */
9464         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9465         if (err < 0)
9466                 verbose(env, "Invalid format string\n");
9467
9468         return err;
9469 }
9470
9471 static int check_get_func_ip(struct bpf_verifier_env *env)
9472 {
9473         enum bpf_prog_type type = resolve_prog_type(env->prog);
9474         int func_id = BPF_FUNC_get_func_ip;
9475
9476         if (type == BPF_PROG_TYPE_TRACING) {
9477                 if (!bpf_prog_has_trampoline(env->prog)) {
9478                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9479                                 func_id_name(func_id), func_id);
9480                         return -ENOTSUPP;
9481                 }
9482                 return 0;
9483         } else if (type == BPF_PROG_TYPE_KPROBE) {
9484                 return 0;
9485         }
9486
9487         verbose(env, "func %s#%d not supported for program type %d\n",
9488                 func_id_name(func_id), func_id, type);
9489         return -ENOTSUPP;
9490 }
9491
9492 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9493 {
9494         return &env->insn_aux_data[env->insn_idx];
9495 }
9496
9497 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9498 {
9499         struct bpf_reg_state *regs = cur_regs(env);
9500         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9501         bool reg_is_null = register_is_null(reg);
9502
9503         if (reg_is_null)
9504                 mark_chain_precision(env, BPF_REG_4);
9505
9506         return reg_is_null;
9507 }
9508
9509 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9510 {
9511         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9512
9513         if (!state->initialized) {
9514                 state->initialized = 1;
9515                 state->fit_for_inline = loop_flag_is_zero(env);
9516                 state->callback_subprogno = subprogno;
9517                 return;
9518         }
9519
9520         if (!state->fit_for_inline)
9521                 return;
9522
9523         state->fit_for_inline = (loop_flag_is_zero(env) &&
9524                                  state->callback_subprogno == subprogno);
9525 }
9526
9527 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9528                              int *insn_idx_p)
9529 {
9530         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9531         const struct bpf_func_proto *fn = NULL;
9532         enum bpf_return_type ret_type;
9533         enum bpf_type_flag ret_flag;
9534         struct bpf_reg_state *regs;
9535         struct bpf_call_arg_meta meta;
9536         int insn_idx = *insn_idx_p;
9537         bool changes_data;
9538         int i, err, func_id;
9539
9540         /* find function prototype */
9541         func_id = insn->imm;
9542         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9543                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9544                         func_id);
9545                 return -EINVAL;
9546         }
9547
9548         if (env->ops->get_func_proto)
9549                 fn = env->ops->get_func_proto(func_id, env->prog);
9550         if (!fn) {
9551                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9552                         func_id);
9553                 return -EINVAL;
9554         }
9555
9556         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9557         if (!env->prog->gpl_compatible && fn->gpl_only) {
9558                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9559                 return -EINVAL;
9560         }
9561
9562         if (fn->allowed && !fn->allowed(env->prog)) {
9563                 verbose(env, "helper call is not allowed in probe\n");
9564                 return -EINVAL;
9565         }
9566
9567         if (!env->prog->aux->sleepable && fn->might_sleep) {
9568                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9569                 return -EINVAL;
9570         }
9571
9572         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9573         changes_data = bpf_helper_changes_pkt_data(fn->func);
9574         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9575                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9576                         func_id_name(func_id), func_id);
9577                 return -EINVAL;
9578         }
9579
9580         memset(&meta, 0, sizeof(meta));
9581         meta.pkt_access = fn->pkt_access;
9582
9583         err = check_func_proto(fn, func_id);
9584         if (err) {
9585                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9586                         func_id_name(func_id), func_id);
9587                 return err;
9588         }
9589
9590         if (env->cur_state->active_rcu_lock) {
9591                 if (fn->might_sleep) {
9592                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9593                                 func_id_name(func_id), func_id);
9594                         return -EINVAL;
9595                 }
9596
9597                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9598                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9599         }
9600
9601         meta.func_id = func_id;
9602         /* check args */
9603         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9604                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9605                 if (err)
9606                         return err;
9607         }
9608
9609         err = record_func_map(env, &meta, func_id, insn_idx);
9610         if (err)
9611                 return err;
9612
9613         err = record_func_key(env, &meta, func_id, insn_idx);
9614         if (err)
9615                 return err;
9616
9617         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9618          * is inferred from register state.
9619          */
9620         for (i = 0; i < meta.access_size; i++) {
9621                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9622                                        BPF_WRITE, -1, false, false);
9623                 if (err)
9624                         return err;
9625         }
9626
9627         regs = cur_regs(env);
9628
9629         if (meta.release_regno) {
9630                 err = -EINVAL;
9631                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9632                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9633                  * is safe to do directly.
9634                  */
9635                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9636                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9637                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9638                                 return -EFAULT;
9639                         }
9640                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9641                 } else if (meta.ref_obj_id) {
9642                         err = release_reference(env, meta.ref_obj_id);
9643                 } else if (register_is_null(&regs[meta.release_regno])) {
9644                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9645                          * released is NULL, which must be > R0.
9646                          */
9647                         err = 0;
9648                 }
9649                 if (err) {
9650                         verbose(env, "func %s#%d reference has not been acquired before\n",
9651                                 func_id_name(func_id), func_id);
9652                         return err;
9653                 }
9654         }
9655
9656         switch (func_id) {
9657         case BPF_FUNC_tail_call:
9658                 err = check_reference_leak(env);
9659                 if (err) {
9660                         verbose(env, "tail_call would lead to reference leak\n");
9661                         return err;
9662                 }
9663                 break;
9664         case BPF_FUNC_get_local_storage:
9665                 /* check that flags argument in get_local_storage(map, flags) is 0,
9666                  * this is required because get_local_storage() can't return an error.
9667                  */
9668                 if (!register_is_null(&regs[BPF_REG_2])) {
9669                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9670                         return -EINVAL;
9671                 }
9672                 break;
9673         case BPF_FUNC_for_each_map_elem:
9674                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9675                                         set_map_elem_callback_state);
9676                 break;
9677         case BPF_FUNC_timer_set_callback:
9678                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9679                                         set_timer_callback_state);
9680                 break;
9681         case BPF_FUNC_find_vma:
9682                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9683                                         set_find_vma_callback_state);
9684                 break;
9685         case BPF_FUNC_snprintf:
9686                 err = check_bpf_snprintf_call(env, regs);
9687                 break;
9688         case BPF_FUNC_loop:
9689                 update_loop_inline_state(env, meta.subprogno);
9690                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9691                                         set_loop_callback_state);
9692                 break;
9693         case BPF_FUNC_dynptr_from_mem:
9694                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9695                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9696                                 reg_type_str(env, regs[BPF_REG_1].type));
9697                         return -EACCES;
9698                 }
9699                 break;
9700         case BPF_FUNC_set_retval:
9701                 if (prog_type == BPF_PROG_TYPE_LSM &&
9702                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9703                         if (!env->prog->aux->attach_func_proto->type) {
9704                                 /* Make sure programs that attach to void
9705                                  * hooks don't try to modify return value.
9706                                  */
9707                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9708                                 return -EINVAL;
9709                         }
9710                 }
9711                 break;
9712         case BPF_FUNC_dynptr_data:
9713         {
9714                 struct bpf_reg_state *reg;
9715                 int id, ref_obj_id;
9716
9717                 reg = get_dynptr_arg_reg(env, fn, regs);
9718                 if (!reg)
9719                         return -EFAULT;
9720
9721
9722                 if (meta.dynptr_id) {
9723                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9724                         return -EFAULT;
9725                 }
9726                 if (meta.ref_obj_id) {
9727                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9728                         return -EFAULT;
9729                 }
9730
9731                 id = dynptr_id(env, reg);
9732                 if (id < 0) {
9733                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9734                         return id;
9735                 }
9736
9737                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9738                 if (ref_obj_id < 0) {
9739                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9740                         return ref_obj_id;
9741                 }
9742
9743                 meta.dynptr_id = id;
9744                 meta.ref_obj_id = ref_obj_id;
9745
9746                 break;
9747         }
9748         case BPF_FUNC_dynptr_write:
9749         {
9750                 enum bpf_dynptr_type dynptr_type;
9751                 struct bpf_reg_state *reg;
9752
9753                 reg = get_dynptr_arg_reg(env, fn, regs);
9754                 if (!reg)
9755                         return -EFAULT;
9756
9757                 dynptr_type = dynptr_get_type(env, reg);
9758                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9759                         return -EFAULT;
9760
9761                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9762                         /* this will trigger clear_all_pkt_pointers(), which will
9763                          * invalidate all dynptr slices associated with the skb
9764                          */
9765                         changes_data = true;
9766
9767                 break;
9768         }
9769         case BPF_FUNC_user_ringbuf_drain:
9770                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9771                                         set_user_ringbuf_callback_state);
9772                 break;
9773         }
9774
9775         if (err)
9776                 return err;
9777
9778         /* reset caller saved regs */
9779         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9780                 mark_reg_not_init(env, regs, caller_saved[i]);
9781                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9782         }
9783
9784         /* helper call returns 64-bit value. */
9785         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9786
9787         /* update return register (already marked as written above) */
9788         ret_type = fn->ret_type;
9789         ret_flag = type_flag(ret_type);
9790
9791         switch (base_type(ret_type)) {
9792         case RET_INTEGER:
9793                 /* sets type to SCALAR_VALUE */
9794                 mark_reg_unknown(env, regs, BPF_REG_0);
9795                 break;
9796         case RET_VOID:
9797                 regs[BPF_REG_0].type = NOT_INIT;
9798                 break;
9799         case RET_PTR_TO_MAP_VALUE:
9800                 /* There is no offset yet applied, variable or fixed */
9801                 mark_reg_known_zero(env, regs, BPF_REG_0);
9802                 /* remember map_ptr, so that check_map_access()
9803                  * can check 'value_size' boundary of memory access
9804                  * to map element returned from bpf_map_lookup_elem()
9805                  */
9806                 if (meta.map_ptr == NULL) {
9807                         verbose(env,
9808                                 "kernel subsystem misconfigured verifier\n");
9809                         return -EINVAL;
9810                 }
9811                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9812                 regs[BPF_REG_0].map_uid = meta.map_uid;
9813                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9814                 if (!type_may_be_null(ret_type) &&
9815                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9816                         regs[BPF_REG_0].id = ++env->id_gen;
9817                 }
9818                 break;
9819         case RET_PTR_TO_SOCKET:
9820                 mark_reg_known_zero(env, regs, BPF_REG_0);
9821                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9822                 break;
9823         case RET_PTR_TO_SOCK_COMMON:
9824                 mark_reg_known_zero(env, regs, BPF_REG_0);
9825                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9826                 break;
9827         case RET_PTR_TO_TCP_SOCK:
9828                 mark_reg_known_zero(env, regs, BPF_REG_0);
9829                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9830                 break;
9831         case RET_PTR_TO_MEM:
9832                 mark_reg_known_zero(env, regs, BPF_REG_0);
9833                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9834                 regs[BPF_REG_0].mem_size = meta.mem_size;
9835                 break;
9836         case RET_PTR_TO_MEM_OR_BTF_ID:
9837         {
9838                 const struct btf_type *t;
9839
9840                 mark_reg_known_zero(env, regs, BPF_REG_0);
9841                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9842                 if (!btf_type_is_struct(t)) {
9843                         u32 tsize;
9844                         const struct btf_type *ret;
9845                         const char *tname;
9846
9847                         /* resolve the type size of ksym. */
9848                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9849                         if (IS_ERR(ret)) {
9850                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9851                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9852                                         tname, PTR_ERR(ret));
9853                                 return -EINVAL;
9854                         }
9855                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9856                         regs[BPF_REG_0].mem_size = tsize;
9857                 } else {
9858                         /* MEM_RDONLY may be carried from ret_flag, but it
9859                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9860                          * it will confuse the check of PTR_TO_BTF_ID in
9861                          * check_mem_access().
9862                          */
9863                         ret_flag &= ~MEM_RDONLY;
9864
9865                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9866                         regs[BPF_REG_0].btf = meta.ret_btf;
9867                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9868                 }
9869                 break;
9870         }
9871         case RET_PTR_TO_BTF_ID:
9872         {
9873                 struct btf *ret_btf;
9874                 int ret_btf_id;
9875
9876                 mark_reg_known_zero(env, regs, BPF_REG_0);
9877                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9878                 if (func_id == BPF_FUNC_kptr_xchg) {
9879                         ret_btf = meta.kptr_field->kptr.btf;
9880                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9881                         if (!btf_is_kernel(ret_btf))
9882                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9883                 } else {
9884                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9885                                 verbose(env, "verifier internal error:");
9886                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9887                                         func_id_name(func_id));
9888                                 return -EINVAL;
9889                         }
9890                         ret_btf = btf_vmlinux;
9891                         ret_btf_id = *fn->ret_btf_id;
9892                 }
9893                 if (ret_btf_id == 0) {
9894                         verbose(env, "invalid return type %u of func %s#%d\n",
9895                                 base_type(ret_type), func_id_name(func_id),
9896                                 func_id);
9897                         return -EINVAL;
9898                 }
9899                 regs[BPF_REG_0].btf = ret_btf;
9900                 regs[BPF_REG_0].btf_id = ret_btf_id;
9901                 break;
9902         }
9903         default:
9904                 verbose(env, "unknown return type %u of func %s#%d\n",
9905                         base_type(ret_type), func_id_name(func_id), func_id);
9906                 return -EINVAL;
9907         }
9908
9909         if (type_may_be_null(regs[BPF_REG_0].type))
9910                 regs[BPF_REG_0].id = ++env->id_gen;
9911
9912         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9913                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9914                         func_id_name(func_id), func_id);
9915                 return -EFAULT;
9916         }
9917
9918         if (is_dynptr_ref_function(func_id))
9919                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9920
9921         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9922                 /* For release_reference() */
9923                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9924         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9925                 int id = acquire_reference_state(env, insn_idx);
9926
9927                 if (id < 0)
9928                         return id;
9929                 /* For mark_ptr_or_null_reg() */
9930                 regs[BPF_REG_0].id = id;
9931                 /* For release_reference() */
9932                 regs[BPF_REG_0].ref_obj_id = id;
9933         }
9934
9935         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9936
9937         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9938         if (err)
9939                 return err;
9940
9941         if ((func_id == BPF_FUNC_get_stack ||
9942              func_id == BPF_FUNC_get_task_stack) &&
9943             !env->prog->has_callchain_buf) {
9944                 const char *err_str;
9945
9946 #ifdef CONFIG_PERF_EVENTS
9947                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9948                 err_str = "cannot get callchain buffer for func %s#%d\n";
9949 #else
9950                 err = -ENOTSUPP;
9951                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9952 #endif
9953                 if (err) {
9954                         verbose(env, err_str, func_id_name(func_id), func_id);
9955                         return err;
9956                 }
9957
9958                 env->prog->has_callchain_buf = true;
9959         }
9960
9961         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9962                 env->prog->call_get_stack = true;
9963
9964         if (func_id == BPF_FUNC_get_func_ip) {
9965                 if (check_get_func_ip(env))
9966                         return -ENOTSUPP;
9967                 env->prog->call_get_func_ip = true;
9968         }
9969
9970         if (changes_data)
9971                 clear_all_pkt_pointers(env);
9972         return 0;
9973 }
9974
9975 /* mark_btf_func_reg_size() is used when the reg size is determined by
9976  * the BTF func_proto's return value size and argument.
9977  */
9978 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
9979                                    size_t reg_size)
9980 {
9981         struct bpf_reg_state *reg = &cur_regs(env)[regno];
9982
9983         if (regno == BPF_REG_0) {
9984                 /* Function return value */
9985                 reg->live |= REG_LIVE_WRITTEN;
9986                 reg->subreg_def = reg_size == sizeof(u64) ?
9987                         DEF_NOT_SUBREG : env->insn_idx + 1;
9988         } else {
9989                 /* Function argument */
9990                 if (reg_size == sizeof(u64)) {
9991                         mark_insn_zext(env, reg);
9992                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
9993                 } else {
9994                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
9995                 }
9996         }
9997 }
9998
9999 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10000 {
10001         return meta->kfunc_flags & KF_ACQUIRE;
10002 }
10003
10004 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10005 {
10006         return meta->kfunc_flags & KF_RELEASE;
10007 }
10008
10009 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10010 {
10011         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10012 }
10013
10014 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10015 {
10016         return meta->kfunc_flags & KF_SLEEPABLE;
10017 }
10018
10019 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10020 {
10021         return meta->kfunc_flags & KF_DESTRUCTIVE;
10022 }
10023
10024 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10025 {
10026         return meta->kfunc_flags & KF_RCU;
10027 }
10028
10029 static bool __kfunc_param_match_suffix(const struct btf *btf,
10030                                        const struct btf_param *arg,
10031                                        const char *suffix)
10032 {
10033         int suffix_len = strlen(suffix), len;
10034         const char *param_name;
10035
10036         /* In the future, this can be ported to use BTF tagging */
10037         param_name = btf_name_by_offset(btf, arg->name_off);
10038         if (str_is_empty(param_name))
10039                 return false;
10040         len = strlen(param_name);
10041         if (len < suffix_len)
10042                 return false;
10043         param_name += len - suffix_len;
10044         return !strncmp(param_name, suffix, suffix_len);
10045 }
10046
10047 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10048                                   const struct btf_param *arg,
10049                                   const struct bpf_reg_state *reg)
10050 {
10051         const struct btf_type *t;
10052
10053         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10054         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10055                 return false;
10056
10057         return __kfunc_param_match_suffix(btf, arg, "__sz");
10058 }
10059
10060 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10061                                         const struct btf_param *arg,
10062                                         const struct bpf_reg_state *reg)
10063 {
10064         const struct btf_type *t;
10065
10066         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10067         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10068                 return false;
10069
10070         return __kfunc_param_match_suffix(btf, arg, "__szk");
10071 }
10072
10073 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10074 {
10075         return __kfunc_param_match_suffix(btf, arg, "__opt");
10076 }
10077
10078 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10079 {
10080         return __kfunc_param_match_suffix(btf, arg, "__k");
10081 }
10082
10083 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10084 {
10085         return __kfunc_param_match_suffix(btf, arg, "__ign");
10086 }
10087
10088 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10089 {
10090         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10091 }
10092
10093 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10094 {
10095         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10096 }
10097
10098 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10099 {
10100         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10101 }
10102
10103 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10104                                           const struct btf_param *arg,
10105                                           const char *name)
10106 {
10107         int len, target_len = strlen(name);
10108         const char *param_name;
10109
10110         param_name = btf_name_by_offset(btf, arg->name_off);
10111         if (str_is_empty(param_name))
10112                 return false;
10113         len = strlen(param_name);
10114         if (len != target_len)
10115                 return false;
10116         if (strcmp(param_name, name))
10117                 return false;
10118
10119         return true;
10120 }
10121
10122 enum {
10123         KF_ARG_DYNPTR_ID,
10124         KF_ARG_LIST_HEAD_ID,
10125         KF_ARG_LIST_NODE_ID,
10126         KF_ARG_RB_ROOT_ID,
10127         KF_ARG_RB_NODE_ID,
10128 };
10129
10130 BTF_ID_LIST(kf_arg_btf_ids)
10131 BTF_ID(struct, bpf_dynptr_kern)
10132 BTF_ID(struct, bpf_list_head)
10133 BTF_ID(struct, bpf_list_node)
10134 BTF_ID(struct, bpf_rb_root)
10135 BTF_ID(struct, bpf_rb_node)
10136
10137 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10138                                     const struct btf_param *arg, int type)
10139 {
10140         const struct btf_type *t;
10141         u32 res_id;
10142
10143         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10144         if (!t)
10145                 return false;
10146         if (!btf_type_is_ptr(t))
10147                 return false;
10148         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10149         if (!t)
10150                 return false;
10151         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10152 }
10153
10154 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10155 {
10156         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10157 }
10158
10159 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10160 {
10161         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10162 }
10163
10164 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10165 {
10166         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10167 }
10168
10169 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10170 {
10171         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10172 }
10173
10174 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10175 {
10176         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10177 }
10178
10179 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10180                                   const struct btf_param *arg)
10181 {
10182         const struct btf_type *t;
10183
10184         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10185         if (!t)
10186                 return false;
10187
10188         return true;
10189 }
10190
10191 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10192 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10193                                         const struct btf *btf,
10194                                         const struct btf_type *t, int rec)
10195 {
10196         const struct btf_type *member_type;
10197         const struct btf_member *member;
10198         u32 i;
10199
10200         if (!btf_type_is_struct(t))
10201                 return false;
10202
10203         for_each_member(i, t, member) {
10204                 const struct btf_array *array;
10205
10206                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10207                 if (btf_type_is_struct(member_type)) {
10208                         if (rec >= 3) {
10209                                 verbose(env, "max struct nesting depth exceeded\n");
10210                                 return false;
10211                         }
10212                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10213                                 return false;
10214                         continue;
10215                 }
10216                 if (btf_type_is_array(member_type)) {
10217                         array = btf_array(member_type);
10218                         if (!array->nelems)
10219                                 return false;
10220                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10221                         if (!btf_type_is_scalar(member_type))
10222                                 return false;
10223                         continue;
10224                 }
10225                 if (!btf_type_is_scalar(member_type))
10226                         return false;
10227         }
10228         return true;
10229 }
10230
10231 enum kfunc_ptr_arg_type {
10232         KF_ARG_PTR_TO_CTX,
10233         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10234         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10235         KF_ARG_PTR_TO_DYNPTR,
10236         KF_ARG_PTR_TO_ITER,
10237         KF_ARG_PTR_TO_LIST_HEAD,
10238         KF_ARG_PTR_TO_LIST_NODE,
10239         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10240         KF_ARG_PTR_TO_MEM,
10241         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10242         KF_ARG_PTR_TO_CALLBACK,
10243         KF_ARG_PTR_TO_RB_ROOT,
10244         KF_ARG_PTR_TO_RB_NODE,
10245 };
10246
10247 enum special_kfunc_type {
10248         KF_bpf_obj_new_impl,
10249         KF_bpf_obj_drop_impl,
10250         KF_bpf_refcount_acquire_impl,
10251         KF_bpf_list_push_front_impl,
10252         KF_bpf_list_push_back_impl,
10253         KF_bpf_list_pop_front,
10254         KF_bpf_list_pop_back,
10255         KF_bpf_cast_to_kern_ctx,
10256         KF_bpf_rdonly_cast,
10257         KF_bpf_rcu_read_lock,
10258         KF_bpf_rcu_read_unlock,
10259         KF_bpf_rbtree_remove,
10260         KF_bpf_rbtree_add_impl,
10261         KF_bpf_rbtree_first,
10262         KF_bpf_dynptr_from_skb,
10263         KF_bpf_dynptr_from_xdp,
10264         KF_bpf_dynptr_slice,
10265         KF_bpf_dynptr_slice_rdwr,
10266         KF_bpf_dynptr_clone,
10267 };
10268
10269 BTF_SET_START(special_kfunc_set)
10270 BTF_ID(func, bpf_obj_new_impl)
10271 BTF_ID(func, bpf_obj_drop_impl)
10272 BTF_ID(func, bpf_refcount_acquire_impl)
10273 BTF_ID(func, bpf_list_push_front_impl)
10274 BTF_ID(func, bpf_list_push_back_impl)
10275 BTF_ID(func, bpf_list_pop_front)
10276 BTF_ID(func, bpf_list_pop_back)
10277 BTF_ID(func, bpf_cast_to_kern_ctx)
10278 BTF_ID(func, bpf_rdonly_cast)
10279 BTF_ID(func, bpf_rbtree_remove)
10280 BTF_ID(func, bpf_rbtree_add_impl)
10281 BTF_ID(func, bpf_rbtree_first)
10282 BTF_ID(func, bpf_dynptr_from_skb)
10283 BTF_ID(func, bpf_dynptr_from_xdp)
10284 BTF_ID(func, bpf_dynptr_slice)
10285 BTF_ID(func, bpf_dynptr_slice_rdwr)
10286 BTF_ID(func, bpf_dynptr_clone)
10287 BTF_SET_END(special_kfunc_set)
10288
10289 BTF_ID_LIST(special_kfunc_list)
10290 BTF_ID(func, bpf_obj_new_impl)
10291 BTF_ID(func, bpf_obj_drop_impl)
10292 BTF_ID(func, bpf_refcount_acquire_impl)
10293 BTF_ID(func, bpf_list_push_front_impl)
10294 BTF_ID(func, bpf_list_push_back_impl)
10295 BTF_ID(func, bpf_list_pop_front)
10296 BTF_ID(func, bpf_list_pop_back)
10297 BTF_ID(func, bpf_cast_to_kern_ctx)
10298 BTF_ID(func, bpf_rdonly_cast)
10299 BTF_ID(func, bpf_rcu_read_lock)
10300 BTF_ID(func, bpf_rcu_read_unlock)
10301 BTF_ID(func, bpf_rbtree_remove)
10302 BTF_ID(func, bpf_rbtree_add_impl)
10303 BTF_ID(func, bpf_rbtree_first)
10304 BTF_ID(func, bpf_dynptr_from_skb)
10305 BTF_ID(func, bpf_dynptr_from_xdp)
10306 BTF_ID(func, bpf_dynptr_slice)
10307 BTF_ID(func, bpf_dynptr_slice_rdwr)
10308 BTF_ID(func, bpf_dynptr_clone)
10309
10310 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10311 {
10312         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10313             meta->arg_owning_ref) {
10314                 return false;
10315         }
10316
10317         return meta->kfunc_flags & KF_RET_NULL;
10318 }
10319
10320 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10321 {
10322         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10323 }
10324
10325 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10326 {
10327         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10328 }
10329
10330 static enum kfunc_ptr_arg_type
10331 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10332                        struct bpf_kfunc_call_arg_meta *meta,
10333                        const struct btf_type *t, const struct btf_type *ref_t,
10334                        const char *ref_tname, const struct btf_param *args,
10335                        int argno, int nargs)
10336 {
10337         u32 regno = argno + 1;
10338         struct bpf_reg_state *regs = cur_regs(env);
10339         struct bpf_reg_state *reg = &regs[regno];
10340         bool arg_mem_size = false;
10341
10342         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10343                 return KF_ARG_PTR_TO_CTX;
10344
10345         /* In this function, we verify the kfunc's BTF as per the argument type,
10346          * leaving the rest of the verification with respect to the register
10347          * type to our caller. When a set of conditions hold in the BTF type of
10348          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10349          */
10350         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10351                 return KF_ARG_PTR_TO_CTX;
10352
10353         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10354                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10355
10356         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10357                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10358
10359         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10360                 return KF_ARG_PTR_TO_DYNPTR;
10361
10362         if (is_kfunc_arg_iter(meta, argno))
10363                 return KF_ARG_PTR_TO_ITER;
10364
10365         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10366                 return KF_ARG_PTR_TO_LIST_HEAD;
10367
10368         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10369                 return KF_ARG_PTR_TO_LIST_NODE;
10370
10371         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10372                 return KF_ARG_PTR_TO_RB_ROOT;
10373
10374         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10375                 return KF_ARG_PTR_TO_RB_NODE;
10376
10377         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10378                 if (!btf_type_is_struct(ref_t)) {
10379                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10380                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10381                         return -EINVAL;
10382                 }
10383                 return KF_ARG_PTR_TO_BTF_ID;
10384         }
10385
10386         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10387                 return KF_ARG_PTR_TO_CALLBACK;
10388
10389
10390         if (argno + 1 < nargs &&
10391             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10392              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10393                 arg_mem_size = true;
10394
10395         /* This is the catch all argument type of register types supported by
10396          * check_helper_mem_access. However, we only allow when argument type is
10397          * pointer to scalar, or struct composed (recursively) of scalars. When
10398          * arg_mem_size is true, the pointer can be void *.
10399          */
10400         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10401             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10402                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10403                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10404                 return -EINVAL;
10405         }
10406         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10407 }
10408
10409 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10410                                         struct bpf_reg_state *reg,
10411                                         const struct btf_type *ref_t,
10412                                         const char *ref_tname, u32 ref_id,
10413                                         struct bpf_kfunc_call_arg_meta *meta,
10414                                         int argno)
10415 {
10416         const struct btf_type *reg_ref_t;
10417         bool strict_type_match = false;
10418         const struct btf *reg_btf;
10419         const char *reg_ref_tname;
10420         u32 reg_ref_id;
10421
10422         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10423                 reg_btf = reg->btf;
10424                 reg_ref_id = reg->btf_id;
10425         } else {
10426                 reg_btf = btf_vmlinux;
10427                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10428         }
10429
10430         /* Enforce strict type matching for calls to kfuncs that are acquiring
10431          * or releasing a reference, or are no-cast aliases. We do _not_
10432          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10433          * as we want to enable BPF programs to pass types that are bitwise
10434          * equivalent without forcing them to explicitly cast with something
10435          * like bpf_cast_to_kern_ctx().
10436          *
10437          * For example, say we had a type like the following:
10438          *
10439          * struct bpf_cpumask {
10440          *      cpumask_t cpumask;
10441          *      refcount_t usage;
10442          * };
10443          *
10444          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10445          * to a struct cpumask, so it would be safe to pass a struct
10446          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10447          *
10448          * The philosophy here is similar to how we allow scalars of different
10449          * types to be passed to kfuncs as long as the size is the same. The
10450          * only difference here is that we're simply allowing
10451          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10452          * resolve types.
10453          */
10454         if (is_kfunc_acquire(meta) ||
10455             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10456             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10457                 strict_type_match = true;
10458
10459         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10460
10461         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10462         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10463         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10464                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10465                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10466                         btf_type_str(reg_ref_t), reg_ref_tname);
10467                 return -EINVAL;
10468         }
10469         return 0;
10470 }
10471
10472 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10473 {
10474         struct bpf_verifier_state *state = env->cur_state;
10475
10476         if (!state->active_lock.ptr) {
10477                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10478                 return -EFAULT;
10479         }
10480
10481         if (type_flag(reg->type) & NON_OWN_REF) {
10482                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10483                 return -EFAULT;
10484         }
10485
10486         reg->type |= NON_OWN_REF;
10487         return 0;
10488 }
10489
10490 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10491 {
10492         struct bpf_func_state *state, *unused;
10493         struct bpf_reg_state *reg;
10494         int i;
10495
10496         state = cur_func(env);
10497
10498         if (!ref_obj_id) {
10499                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10500                              "owning -> non-owning conversion\n");
10501                 return -EFAULT;
10502         }
10503
10504         for (i = 0; i < state->acquired_refs; i++) {
10505                 if (state->refs[i].id != ref_obj_id)
10506                         continue;
10507
10508                 /* Clear ref_obj_id here so release_reference doesn't clobber
10509                  * the whole reg
10510                  */
10511                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10512                         if (reg->ref_obj_id == ref_obj_id) {
10513                                 reg->ref_obj_id = 0;
10514                                 ref_set_non_owning(env, reg);
10515                         }
10516                 }));
10517                 return 0;
10518         }
10519
10520         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10521         return -EFAULT;
10522 }
10523
10524 /* Implementation details:
10525  *
10526  * Each register points to some region of memory, which we define as an
10527  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10528  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10529  * allocation. The lock and the data it protects are colocated in the same
10530  * memory region.
10531  *
10532  * Hence, everytime a register holds a pointer value pointing to such
10533  * allocation, the verifier preserves a unique reg->id for it.
10534  *
10535  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10536  * bpf_spin_lock is called.
10537  *
10538  * To enable this, lock state in the verifier captures two values:
10539  *      active_lock.ptr = Register's type specific pointer
10540  *      active_lock.id  = A unique ID for each register pointer value
10541  *
10542  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10543  * supported register types.
10544  *
10545  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10546  * allocated objects is the reg->btf pointer.
10547  *
10548  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10549  * can establish the provenance of the map value statically for each distinct
10550  * lookup into such maps. They always contain a single map value hence unique
10551  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10552  *
10553  * So, in case of global variables, they use array maps with max_entries = 1,
10554  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10555  * into the same map value as max_entries is 1, as described above).
10556  *
10557  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10558  * outer map pointer (in verifier context), but each lookup into an inner map
10559  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10560  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10561  * will get different reg->id assigned to each lookup, hence different
10562  * active_lock.id.
10563  *
10564  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10565  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10566  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10567  */
10568 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10569 {
10570         void *ptr;
10571         u32 id;
10572
10573         switch ((int)reg->type) {
10574         case PTR_TO_MAP_VALUE:
10575                 ptr = reg->map_ptr;
10576                 break;
10577         case PTR_TO_BTF_ID | MEM_ALLOC:
10578                 ptr = reg->btf;
10579                 break;
10580         default:
10581                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10582                 return -EFAULT;
10583         }
10584         id = reg->id;
10585
10586         if (!env->cur_state->active_lock.ptr)
10587                 return -EINVAL;
10588         if (env->cur_state->active_lock.ptr != ptr ||
10589             env->cur_state->active_lock.id != id) {
10590                 verbose(env, "held lock and object are not in the same allocation\n");
10591                 return -EINVAL;
10592         }
10593         return 0;
10594 }
10595
10596 static bool is_bpf_list_api_kfunc(u32 btf_id)
10597 {
10598         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10599                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10600                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10601                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10602 }
10603
10604 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10605 {
10606         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10607                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10608                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10609 }
10610
10611 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10612 {
10613         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10614                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10615 }
10616
10617 static bool is_callback_calling_kfunc(u32 btf_id)
10618 {
10619         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10620 }
10621
10622 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10623 {
10624         return is_bpf_rbtree_api_kfunc(btf_id);
10625 }
10626
10627 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10628                                           enum btf_field_type head_field_type,
10629                                           u32 kfunc_btf_id)
10630 {
10631         bool ret;
10632
10633         switch (head_field_type) {
10634         case BPF_LIST_HEAD:
10635                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10636                 break;
10637         case BPF_RB_ROOT:
10638                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10639                 break;
10640         default:
10641                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10642                         btf_field_type_name(head_field_type));
10643                 return false;
10644         }
10645
10646         if (!ret)
10647                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10648                         btf_field_type_name(head_field_type));
10649         return ret;
10650 }
10651
10652 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10653                                           enum btf_field_type node_field_type,
10654                                           u32 kfunc_btf_id)
10655 {
10656         bool ret;
10657
10658         switch (node_field_type) {
10659         case BPF_LIST_NODE:
10660                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10661                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10662                 break;
10663         case BPF_RB_NODE:
10664                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10665                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10666                 break;
10667         default:
10668                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10669                         btf_field_type_name(node_field_type));
10670                 return false;
10671         }
10672
10673         if (!ret)
10674                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10675                         btf_field_type_name(node_field_type));
10676         return ret;
10677 }
10678
10679 static int
10680 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10681                                    struct bpf_reg_state *reg, u32 regno,
10682                                    struct bpf_kfunc_call_arg_meta *meta,
10683                                    enum btf_field_type head_field_type,
10684                                    struct btf_field **head_field)
10685 {
10686         const char *head_type_name;
10687         struct btf_field *field;
10688         struct btf_record *rec;
10689         u32 head_off;
10690
10691         if (meta->btf != btf_vmlinux) {
10692                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10693                 return -EFAULT;
10694         }
10695
10696         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10697                 return -EFAULT;
10698
10699         head_type_name = btf_field_type_name(head_field_type);
10700         if (!tnum_is_const(reg->var_off)) {
10701                 verbose(env,
10702                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10703                         regno, head_type_name);
10704                 return -EINVAL;
10705         }
10706
10707         rec = reg_btf_record(reg);
10708         head_off = reg->off + reg->var_off.value;
10709         field = btf_record_find(rec, head_off, head_field_type);
10710         if (!field) {
10711                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10712                 return -EINVAL;
10713         }
10714
10715         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10716         if (check_reg_allocation_locked(env, reg)) {
10717                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10718                         rec->spin_lock_off, head_type_name);
10719                 return -EINVAL;
10720         }
10721
10722         if (*head_field) {
10723                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10724                 return -EFAULT;
10725         }
10726         *head_field = field;
10727         return 0;
10728 }
10729
10730 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10731                                            struct bpf_reg_state *reg, u32 regno,
10732                                            struct bpf_kfunc_call_arg_meta *meta)
10733 {
10734         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10735                                                           &meta->arg_list_head.field);
10736 }
10737
10738 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10739                                              struct bpf_reg_state *reg, u32 regno,
10740                                              struct bpf_kfunc_call_arg_meta *meta)
10741 {
10742         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10743                                                           &meta->arg_rbtree_root.field);
10744 }
10745
10746 static int
10747 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10748                                    struct bpf_reg_state *reg, u32 regno,
10749                                    struct bpf_kfunc_call_arg_meta *meta,
10750                                    enum btf_field_type head_field_type,
10751                                    enum btf_field_type node_field_type,
10752                                    struct btf_field **node_field)
10753 {
10754         const char *node_type_name;
10755         const struct btf_type *et, *t;
10756         struct btf_field *field;
10757         u32 node_off;
10758
10759         if (meta->btf != btf_vmlinux) {
10760                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10761                 return -EFAULT;
10762         }
10763
10764         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10765                 return -EFAULT;
10766
10767         node_type_name = btf_field_type_name(node_field_type);
10768         if (!tnum_is_const(reg->var_off)) {
10769                 verbose(env,
10770                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10771                         regno, node_type_name);
10772                 return -EINVAL;
10773         }
10774
10775         node_off = reg->off + reg->var_off.value;
10776         field = reg_find_field_offset(reg, node_off, node_field_type);
10777         if (!field || field->offset != node_off) {
10778                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10779                 return -EINVAL;
10780         }
10781
10782         field = *node_field;
10783
10784         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10785         t = btf_type_by_id(reg->btf, reg->btf_id);
10786         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10787                                   field->graph_root.value_btf_id, true)) {
10788                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10789                         "in struct %s, but arg is at offset=%d in struct %s\n",
10790                         btf_field_type_name(head_field_type),
10791                         btf_field_type_name(node_field_type),
10792                         field->graph_root.node_offset,
10793                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10794                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10795                 return -EINVAL;
10796         }
10797         meta->arg_btf = reg->btf;
10798         meta->arg_btf_id = reg->btf_id;
10799
10800         if (node_off != field->graph_root.node_offset) {
10801                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10802                         node_off, btf_field_type_name(node_field_type),
10803                         field->graph_root.node_offset,
10804                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10805                 return -EINVAL;
10806         }
10807
10808         return 0;
10809 }
10810
10811 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10812                                            struct bpf_reg_state *reg, u32 regno,
10813                                            struct bpf_kfunc_call_arg_meta *meta)
10814 {
10815         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10816                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10817                                                   &meta->arg_list_head.field);
10818 }
10819
10820 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10821                                              struct bpf_reg_state *reg, u32 regno,
10822                                              struct bpf_kfunc_call_arg_meta *meta)
10823 {
10824         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10825                                                   BPF_RB_ROOT, BPF_RB_NODE,
10826                                                   &meta->arg_rbtree_root.field);
10827 }
10828
10829 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10830                             int insn_idx)
10831 {
10832         const char *func_name = meta->func_name, *ref_tname;
10833         const struct btf *btf = meta->btf;
10834         const struct btf_param *args;
10835         struct btf_record *rec;
10836         u32 i, nargs;
10837         int ret;
10838
10839         args = (const struct btf_param *)(meta->func_proto + 1);
10840         nargs = btf_type_vlen(meta->func_proto);
10841         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10842                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10843                         MAX_BPF_FUNC_REG_ARGS);
10844                 return -EINVAL;
10845         }
10846
10847         /* Check that BTF function arguments match actual types that the
10848          * verifier sees.
10849          */
10850         for (i = 0; i < nargs; i++) {
10851                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10852                 const struct btf_type *t, *ref_t, *resolve_ret;
10853                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10854                 u32 regno = i + 1, ref_id, type_size;
10855                 bool is_ret_buf_sz = false;
10856                 int kf_arg_type;
10857
10858                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10859
10860                 if (is_kfunc_arg_ignore(btf, &args[i]))
10861                         continue;
10862
10863                 if (btf_type_is_scalar(t)) {
10864                         if (reg->type != SCALAR_VALUE) {
10865                                 verbose(env, "R%d is not a scalar\n", regno);
10866                                 return -EINVAL;
10867                         }
10868
10869                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10870                                 if (meta->arg_constant.found) {
10871                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10872                                         return -EFAULT;
10873                                 }
10874                                 if (!tnum_is_const(reg->var_off)) {
10875                                         verbose(env, "R%d must be a known constant\n", regno);
10876                                         return -EINVAL;
10877                                 }
10878                                 ret = mark_chain_precision(env, regno);
10879                                 if (ret < 0)
10880                                         return ret;
10881                                 meta->arg_constant.found = true;
10882                                 meta->arg_constant.value = reg->var_off.value;
10883                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10884                                 meta->r0_rdonly = true;
10885                                 is_ret_buf_sz = true;
10886                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10887                                 is_ret_buf_sz = true;
10888                         }
10889
10890                         if (is_ret_buf_sz) {
10891                                 if (meta->r0_size) {
10892                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10893                                         return -EINVAL;
10894                                 }
10895
10896                                 if (!tnum_is_const(reg->var_off)) {
10897                                         verbose(env, "R%d is not a const\n", regno);
10898                                         return -EINVAL;
10899                                 }
10900
10901                                 meta->r0_size = reg->var_off.value;
10902                                 ret = mark_chain_precision(env, regno);
10903                                 if (ret)
10904                                         return ret;
10905                         }
10906                         continue;
10907                 }
10908
10909                 if (!btf_type_is_ptr(t)) {
10910                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10911                         return -EINVAL;
10912                 }
10913
10914                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10915                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10916                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10917                         return -EACCES;
10918                 }
10919
10920                 if (reg->ref_obj_id) {
10921                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10922                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10923                                         regno, reg->ref_obj_id,
10924                                         meta->ref_obj_id);
10925                                 return -EFAULT;
10926                         }
10927                         meta->ref_obj_id = reg->ref_obj_id;
10928                         if (is_kfunc_release(meta))
10929                                 meta->release_regno = regno;
10930                 }
10931
10932                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10933                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10934
10935                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10936                 if (kf_arg_type < 0)
10937                         return kf_arg_type;
10938
10939                 switch (kf_arg_type) {
10940                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10941                 case KF_ARG_PTR_TO_BTF_ID:
10942                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10943                                 break;
10944
10945                         if (!is_trusted_reg(reg)) {
10946                                 if (!is_kfunc_rcu(meta)) {
10947                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10948                                         return -EINVAL;
10949                                 }
10950                                 if (!is_rcu_reg(reg)) {
10951                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10952                                         return -EINVAL;
10953                                 }
10954                         }
10955
10956                         fallthrough;
10957                 case KF_ARG_PTR_TO_CTX:
10958                         /* Trusted arguments have the same offset checks as release arguments */
10959                         arg_type |= OBJ_RELEASE;
10960                         break;
10961                 case KF_ARG_PTR_TO_DYNPTR:
10962                 case KF_ARG_PTR_TO_ITER:
10963                 case KF_ARG_PTR_TO_LIST_HEAD:
10964                 case KF_ARG_PTR_TO_LIST_NODE:
10965                 case KF_ARG_PTR_TO_RB_ROOT:
10966                 case KF_ARG_PTR_TO_RB_NODE:
10967                 case KF_ARG_PTR_TO_MEM:
10968                 case KF_ARG_PTR_TO_MEM_SIZE:
10969                 case KF_ARG_PTR_TO_CALLBACK:
10970                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
10971                         /* Trusted by default */
10972                         break;
10973                 default:
10974                         WARN_ON_ONCE(1);
10975                         return -EFAULT;
10976                 }
10977
10978                 if (is_kfunc_release(meta) && reg->ref_obj_id)
10979                         arg_type |= OBJ_RELEASE;
10980                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
10981                 if (ret < 0)
10982                         return ret;
10983
10984                 switch (kf_arg_type) {
10985                 case KF_ARG_PTR_TO_CTX:
10986                         if (reg->type != PTR_TO_CTX) {
10987                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
10988                                 return -EINVAL;
10989                         }
10990
10991                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
10992                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
10993                                 if (ret < 0)
10994                                         return -EINVAL;
10995                                 meta->ret_btf_id  = ret;
10996                         }
10997                         break;
10998                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10999                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11000                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11001                                 return -EINVAL;
11002                         }
11003                         if (!reg->ref_obj_id) {
11004                                 verbose(env, "allocated object must be referenced\n");
11005                                 return -EINVAL;
11006                         }
11007                         if (meta->btf == btf_vmlinux &&
11008                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11009                                 meta->arg_btf = reg->btf;
11010                                 meta->arg_btf_id = reg->btf_id;
11011                         }
11012                         break;
11013                 case KF_ARG_PTR_TO_DYNPTR:
11014                 {
11015                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11016                         int clone_ref_obj_id = 0;
11017
11018                         if (reg->type != PTR_TO_STACK &&
11019                             reg->type != CONST_PTR_TO_DYNPTR) {
11020                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11021                                 return -EINVAL;
11022                         }
11023
11024                         if (reg->type == CONST_PTR_TO_DYNPTR)
11025                                 dynptr_arg_type |= MEM_RDONLY;
11026
11027                         if (is_kfunc_arg_uninit(btf, &args[i]))
11028                                 dynptr_arg_type |= MEM_UNINIT;
11029
11030                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11031                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11032                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11033                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11034                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11035                                    (dynptr_arg_type & MEM_UNINIT)) {
11036                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11037
11038                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11039                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11040                                         return -EFAULT;
11041                                 }
11042
11043                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11044                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11045                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11046                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11047                                         return -EFAULT;
11048                                 }
11049                         }
11050
11051                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11052                         if (ret < 0)
11053                                 return ret;
11054
11055                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11056                                 int id = dynptr_id(env, reg);
11057
11058                                 if (id < 0) {
11059                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11060                                         return id;
11061                                 }
11062                                 meta->initialized_dynptr.id = id;
11063                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11064                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11065                         }
11066
11067                         break;
11068                 }
11069                 case KF_ARG_PTR_TO_ITER:
11070                         ret = process_iter_arg(env, regno, insn_idx, meta);
11071                         if (ret < 0)
11072                                 return ret;
11073                         break;
11074                 case KF_ARG_PTR_TO_LIST_HEAD:
11075                         if (reg->type != PTR_TO_MAP_VALUE &&
11076                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11077                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11078                                 return -EINVAL;
11079                         }
11080                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11081                                 verbose(env, "allocated object must be referenced\n");
11082                                 return -EINVAL;
11083                         }
11084                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11085                         if (ret < 0)
11086                                 return ret;
11087                         break;
11088                 case KF_ARG_PTR_TO_RB_ROOT:
11089                         if (reg->type != PTR_TO_MAP_VALUE &&
11090                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11091                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11092                                 return -EINVAL;
11093                         }
11094                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11095                                 verbose(env, "allocated object must be referenced\n");
11096                                 return -EINVAL;
11097                         }
11098                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11099                         if (ret < 0)
11100                                 return ret;
11101                         break;
11102                 case KF_ARG_PTR_TO_LIST_NODE:
11103                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11104                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11105                                 return -EINVAL;
11106                         }
11107                         if (!reg->ref_obj_id) {
11108                                 verbose(env, "allocated object must be referenced\n");
11109                                 return -EINVAL;
11110                         }
11111                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11112                         if (ret < 0)
11113                                 return ret;
11114                         break;
11115                 case KF_ARG_PTR_TO_RB_NODE:
11116                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11117                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11118                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11119                                         return -EINVAL;
11120                                 }
11121                                 if (in_rbtree_lock_required_cb(env)) {
11122                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11123                                         return -EINVAL;
11124                                 }
11125                         } else {
11126                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11127                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11128                                         return -EINVAL;
11129                                 }
11130                                 if (!reg->ref_obj_id) {
11131                                         verbose(env, "allocated object must be referenced\n");
11132                                         return -EINVAL;
11133                                 }
11134                         }
11135
11136                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11137                         if (ret < 0)
11138                                 return ret;
11139                         break;
11140                 case KF_ARG_PTR_TO_BTF_ID:
11141                         /* Only base_type is checked, further checks are done here */
11142                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11143                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11144                             !reg2btf_ids[base_type(reg->type)]) {
11145                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11146                                 verbose(env, "expected %s or socket\n",
11147                                         reg_type_str(env, base_type(reg->type) |
11148                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11149                                 return -EINVAL;
11150                         }
11151                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11152                         if (ret < 0)
11153                                 return ret;
11154                         break;
11155                 case KF_ARG_PTR_TO_MEM:
11156                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11157                         if (IS_ERR(resolve_ret)) {
11158                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11159                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11160                                 return -EINVAL;
11161                         }
11162                         ret = check_mem_reg(env, reg, regno, type_size);
11163                         if (ret < 0)
11164                                 return ret;
11165                         break;
11166                 case KF_ARG_PTR_TO_MEM_SIZE:
11167                 {
11168                         struct bpf_reg_state *buff_reg = &regs[regno];
11169                         const struct btf_param *buff_arg = &args[i];
11170                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11171                         const struct btf_param *size_arg = &args[i + 1];
11172
11173                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11174                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11175                                 if (ret < 0) {
11176                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11177                                         return ret;
11178                                 }
11179                         }
11180
11181                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11182                                 if (meta->arg_constant.found) {
11183                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11184                                         return -EFAULT;
11185                                 }
11186                                 if (!tnum_is_const(size_reg->var_off)) {
11187                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11188                                         return -EINVAL;
11189                                 }
11190                                 meta->arg_constant.found = true;
11191                                 meta->arg_constant.value = size_reg->var_off.value;
11192                         }
11193
11194                         /* Skip next '__sz' or '__szk' argument */
11195                         i++;
11196                         break;
11197                 }
11198                 case KF_ARG_PTR_TO_CALLBACK:
11199                         meta->subprogno = reg->subprogno;
11200                         break;
11201                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11202                         if (!type_is_ptr_alloc_obj(reg->type)) {
11203                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11204                                 return -EINVAL;
11205                         }
11206                         if (!type_is_non_owning_ref(reg->type))
11207                                 meta->arg_owning_ref = true;
11208
11209                         rec = reg_btf_record(reg);
11210                         if (!rec) {
11211                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11212                                 return -EFAULT;
11213                         }
11214
11215                         if (rec->refcount_off < 0) {
11216                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11217                                 return -EINVAL;
11218                         }
11219                         if (rec->refcount_off >= 0) {
11220                                 verbose(env, "bpf_refcount_acquire calls are disabled for now\n");
11221                                 return -EINVAL;
11222                         }
11223                         meta->arg_btf = reg->btf;
11224                         meta->arg_btf_id = reg->btf_id;
11225                         break;
11226                 }
11227         }
11228
11229         if (is_kfunc_release(meta) && !meta->release_regno) {
11230                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11231                         func_name);
11232                 return -EINVAL;
11233         }
11234
11235         return 0;
11236 }
11237
11238 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11239                             struct bpf_insn *insn,
11240                             struct bpf_kfunc_call_arg_meta *meta,
11241                             const char **kfunc_name)
11242 {
11243         const struct btf_type *func, *func_proto;
11244         u32 func_id, *kfunc_flags;
11245         const char *func_name;
11246         struct btf *desc_btf;
11247
11248         if (kfunc_name)
11249                 *kfunc_name = NULL;
11250
11251         if (!insn->imm)
11252                 return -EINVAL;
11253
11254         desc_btf = find_kfunc_desc_btf(env, insn->off);
11255         if (IS_ERR(desc_btf))
11256                 return PTR_ERR(desc_btf);
11257
11258         func_id = insn->imm;
11259         func = btf_type_by_id(desc_btf, func_id);
11260         func_name = btf_name_by_offset(desc_btf, func->name_off);
11261         if (kfunc_name)
11262                 *kfunc_name = func_name;
11263         func_proto = btf_type_by_id(desc_btf, func->type);
11264
11265         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11266         if (!kfunc_flags) {
11267                 return -EACCES;
11268         }
11269
11270         memset(meta, 0, sizeof(*meta));
11271         meta->btf = desc_btf;
11272         meta->func_id = func_id;
11273         meta->kfunc_flags = *kfunc_flags;
11274         meta->func_proto = func_proto;
11275         meta->func_name = func_name;
11276
11277         return 0;
11278 }
11279
11280 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11281                             int *insn_idx_p)
11282 {
11283         const struct btf_type *t, *ptr_type;
11284         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11285         struct bpf_reg_state *regs = cur_regs(env);
11286         const char *func_name, *ptr_type_name;
11287         bool sleepable, rcu_lock, rcu_unlock;
11288         struct bpf_kfunc_call_arg_meta meta;
11289         struct bpf_insn_aux_data *insn_aux;
11290         int err, insn_idx = *insn_idx_p;
11291         const struct btf_param *args;
11292         const struct btf_type *ret_t;
11293         struct btf *desc_btf;
11294
11295         /* skip for now, but return error when we find this in fixup_kfunc_call */
11296         if (!insn->imm)
11297                 return 0;
11298
11299         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11300         if (err == -EACCES && func_name)
11301                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11302         if (err)
11303                 return err;
11304         desc_btf = meta.btf;
11305         insn_aux = &env->insn_aux_data[insn_idx];
11306
11307         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11308
11309         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11310                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11311                 return -EACCES;
11312         }
11313
11314         sleepable = is_kfunc_sleepable(&meta);
11315         if (sleepable && !env->prog->aux->sleepable) {
11316                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11317                 return -EACCES;
11318         }
11319
11320         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11321         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11322
11323         if (env->cur_state->active_rcu_lock) {
11324                 struct bpf_func_state *state;
11325                 struct bpf_reg_state *reg;
11326
11327                 if (rcu_lock) {
11328                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11329                         return -EINVAL;
11330                 } else if (rcu_unlock) {
11331                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11332                                 if (reg->type & MEM_RCU) {
11333                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11334                                         reg->type |= PTR_UNTRUSTED;
11335                                 }
11336                         }));
11337                         env->cur_state->active_rcu_lock = false;
11338                 } else if (sleepable) {
11339                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11340                         return -EACCES;
11341                 }
11342         } else if (rcu_lock) {
11343                 env->cur_state->active_rcu_lock = true;
11344         } else if (rcu_unlock) {
11345                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11346                 return -EINVAL;
11347         }
11348
11349         /* Check the arguments */
11350         err = check_kfunc_args(env, &meta, insn_idx);
11351         if (err < 0)
11352                 return err;
11353         /* In case of release function, we get register number of refcounted
11354          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11355          */
11356         if (meta.release_regno) {
11357                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11358                 if (err) {
11359                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11360                                 func_name, meta.func_id);
11361                         return err;
11362                 }
11363         }
11364
11365         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11366             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11367             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11368                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11369                 insn_aux->insert_off = regs[BPF_REG_2].off;
11370                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11371                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11372                 if (err) {
11373                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11374                                 func_name, meta.func_id);
11375                         return err;
11376                 }
11377
11378                 err = release_reference(env, release_ref_obj_id);
11379                 if (err) {
11380                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11381                                 func_name, meta.func_id);
11382                         return err;
11383                 }
11384         }
11385
11386         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11387                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11388                                         set_rbtree_add_callback_state);
11389                 if (err) {
11390                         verbose(env, "kfunc %s#%d failed callback verification\n",
11391                                 func_name, meta.func_id);
11392                         return err;
11393                 }
11394         }
11395
11396         for (i = 0; i < CALLER_SAVED_REGS; i++)
11397                 mark_reg_not_init(env, regs, caller_saved[i]);
11398
11399         /* Check return type */
11400         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11401
11402         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11403                 /* Only exception is bpf_obj_new_impl */
11404                 if (meta.btf != btf_vmlinux ||
11405                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11406                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11407                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11408                         return -EINVAL;
11409                 }
11410         }
11411
11412         if (btf_type_is_scalar(t)) {
11413                 mark_reg_unknown(env, regs, BPF_REG_0);
11414                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11415         } else if (btf_type_is_ptr(t)) {
11416                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11417
11418                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11419                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11420                                 struct btf *ret_btf;
11421                                 u32 ret_btf_id;
11422
11423                                 if (unlikely(!bpf_global_ma_set))
11424                                         return -ENOMEM;
11425
11426                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11427                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11428                                         return -EINVAL;
11429                                 }
11430
11431                                 ret_btf = env->prog->aux->btf;
11432                                 ret_btf_id = meta.arg_constant.value;
11433
11434                                 /* This may be NULL due to user not supplying a BTF */
11435                                 if (!ret_btf) {
11436                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11437                                         return -EINVAL;
11438                                 }
11439
11440                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11441                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11442                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11443                                         return -EINVAL;
11444                                 }
11445
11446                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11447                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11448                                 regs[BPF_REG_0].btf = ret_btf;
11449                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11450
11451                                 insn_aux->obj_new_size = ret_t->size;
11452                                 insn_aux->kptr_struct_meta =
11453                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11454                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11455                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11456                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11457                                 regs[BPF_REG_0].btf = meta.arg_btf;
11458                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11459
11460                                 insn_aux->kptr_struct_meta =
11461                                         btf_find_struct_meta(meta.arg_btf,
11462                                                              meta.arg_btf_id);
11463                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11464                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11465                                 struct btf_field *field = meta.arg_list_head.field;
11466
11467                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11468                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11469                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11470                                 struct btf_field *field = meta.arg_rbtree_root.field;
11471
11472                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11473                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11474                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11475                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11476                                 regs[BPF_REG_0].btf = desc_btf;
11477                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11478                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11479                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11480                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11481                                         verbose(env,
11482                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11483                                         return -EINVAL;
11484                                 }
11485
11486                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11487                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11488                                 regs[BPF_REG_0].btf = desc_btf;
11489                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11490                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11491                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11492                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11493
11494                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11495
11496                                 if (!meta.arg_constant.found) {
11497                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11498                                         return -EFAULT;
11499                                 }
11500
11501                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11502
11503                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11504                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11505
11506                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11507                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11508                                 } else {
11509                                         /* this will set env->seen_direct_write to true */
11510                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11511                                                 verbose(env, "the prog does not allow writes to packet data\n");
11512                                                 return -EINVAL;
11513                                         }
11514                                 }
11515
11516                                 if (!meta.initialized_dynptr.id) {
11517                                         verbose(env, "verifier internal error: no dynptr id\n");
11518                                         return -EFAULT;
11519                                 }
11520                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11521
11522                                 /* we don't need to set BPF_REG_0's ref obj id
11523                                  * because packet slices are not refcounted (see
11524                                  * dynptr_type_refcounted)
11525                                  */
11526                         } else {
11527                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11528                                         meta.func_name);
11529                                 return -EFAULT;
11530                         }
11531                 } else if (!__btf_type_is_struct(ptr_type)) {
11532                         if (!meta.r0_size) {
11533                                 __u32 sz;
11534
11535                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11536                                         meta.r0_size = sz;
11537                                         meta.r0_rdonly = true;
11538                                 }
11539                         }
11540                         if (!meta.r0_size) {
11541                                 ptr_type_name = btf_name_by_offset(desc_btf,
11542                                                                    ptr_type->name_off);
11543                                 verbose(env,
11544                                         "kernel function %s returns pointer type %s %s is not supported\n",
11545                                         func_name,
11546                                         btf_type_str(ptr_type),
11547                                         ptr_type_name);
11548                                 return -EINVAL;
11549                         }
11550
11551                         mark_reg_known_zero(env, regs, BPF_REG_0);
11552                         regs[BPF_REG_0].type = PTR_TO_MEM;
11553                         regs[BPF_REG_0].mem_size = meta.r0_size;
11554
11555                         if (meta.r0_rdonly)
11556                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11557
11558                         /* Ensures we don't access the memory after a release_reference() */
11559                         if (meta.ref_obj_id)
11560                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11561                 } else {
11562                         mark_reg_known_zero(env, regs, BPF_REG_0);
11563                         regs[BPF_REG_0].btf = desc_btf;
11564                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11565                         regs[BPF_REG_0].btf_id = ptr_type_id;
11566                 }
11567
11568                 if (is_kfunc_ret_null(&meta)) {
11569                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11570                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11571                         regs[BPF_REG_0].id = ++env->id_gen;
11572                 }
11573                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11574                 if (is_kfunc_acquire(&meta)) {
11575                         int id = acquire_reference_state(env, insn_idx);
11576
11577                         if (id < 0)
11578                                 return id;
11579                         if (is_kfunc_ret_null(&meta))
11580                                 regs[BPF_REG_0].id = id;
11581                         regs[BPF_REG_0].ref_obj_id = id;
11582                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11583                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11584                 }
11585
11586                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11587                         regs[BPF_REG_0].id = ++env->id_gen;
11588         } else if (btf_type_is_void(t)) {
11589                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11590                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11591                                 insn_aux->kptr_struct_meta =
11592                                         btf_find_struct_meta(meta.arg_btf,
11593                                                              meta.arg_btf_id);
11594                         }
11595                 }
11596         }
11597
11598         nargs = btf_type_vlen(meta.func_proto);
11599         args = (const struct btf_param *)(meta.func_proto + 1);
11600         for (i = 0; i < nargs; i++) {
11601                 u32 regno = i + 1;
11602
11603                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11604                 if (btf_type_is_ptr(t))
11605                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11606                 else
11607                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11608                         mark_btf_func_reg_size(env, regno, t->size);
11609         }
11610
11611         if (is_iter_next_kfunc(&meta)) {
11612                 err = process_iter_next_call(env, insn_idx, &meta);
11613                 if (err)
11614                         return err;
11615         }
11616
11617         return 0;
11618 }
11619
11620 static bool signed_add_overflows(s64 a, s64 b)
11621 {
11622         /* Do the add in u64, where overflow is well-defined */
11623         s64 res = (s64)((u64)a + (u64)b);
11624
11625         if (b < 0)
11626                 return res > a;
11627         return res < a;
11628 }
11629
11630 static bool signed_add32_overflows(s32 a, s32 b)
11631 {
11632         /* Do the add in u32, where overflow is well-defined */
11633         s32 res = (s32)((u32)a + (u32)b);
11634
11635         if (b < 0)
11636                 return res > a;
11637         return res < a;
11638 }
11639
11640 static bool signed_sub_overflows(s64 a, s64 b)
11641 {
11642         /* Do the sub in u64, where overflow is well-defined */
11643         s64 res = (s64)((u64)a - (u64)b);
11644
11645         if (b < 0)
11646                 return res < a;
11647         return res > a;
11648 }
11649
11650 static bool signed_sub32_overflows(s32 a, s32 b)
11651 {
11652         /* Do the sub in u32, where overflow is well-defined */
11653         s32 res = (s32)((u32)a - (u32)b);
11654
11655         if (b < 0)
11656                 return res < a;
11657         return res > a;
11658 }
11659
11660 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11661                                   const struct bpf_reg_state *reg,
11662                                   enum bpf_reg_type type)
11663 {
11664         bool known = tnum_is_const(reg->var_off);
11665         s64 val = reg->var_off.value;
11666         s64 smin = reg->smin_value;
11667
11668         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11669                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11670                         reg_type_str(env, type), val);
11671                 return false;
11672         }
11673
11674         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11675                 verbose(env, "%s pointer offset %d is not allowed\n",
11676                         reg_type_str(env, type), reg->off);
11677                 return false;
11678         }
11679
11680         if (smin == S64_MIN) {
11681                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11682                         reg_type_str(env, type));
11683                 return false;
11684         }
11685
11686         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11687                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11688                         smin, reg_type_str(env, type));
11689                 return false;
11690         }
11691
11692         return true;
11693 }
11694
11695 enum {
11696         REASON_BOUNDS   = -1,
11697         REASON_TYPE     = -2,
11698         REASON_PATHS    = -3,
11699         REASON_LIMIT    = -4,
11700         REASON_STACK    = -5,
11701 };
11702
11703 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11704                               u32 *alu_limit, bool mask_to_left)
11705 {
11706         u32 max = 0, ptr_limit = 0;
11707
11708         switch (ptr_reg->type) {
11709         case PTR_TO_STACK:
11710                 /* Offset 0 is out-of-bounds, but acceptable start for the
11711                  * left direction, see BPF_REG_FP. Also, unknown scalar
11712                  * offset where we would need to deal with min/max bounds is
11713                  * currently prohibited for unprivileged.
11714                  */
11715                 max = MAX_BPF_STACK + mask_to_left;
11716                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11717                 break;
11718         case PTR_TO_MAP_VALUE:
11719                 max = ptr_reg->map_ptr->value_size;
11720                 ptr_limit = (mask_to_left ?
11721                              ptr_reg->smin_value :
11722                              ptr_reg->umax_value) + ptr_reg->off;
11723                 break;
11724         default:
11725                 return REASON_TYPE;
11726         }
11727
11728         if (ptr_limit >= max)
11729                 return REASON_LIMIT;
11730         *alu_limit = ptr_limit;
11731         return 0;
11732 }
11733
11734 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11735                                     const struct bpf_insn *insn)
11736 {
11737         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11738 }
11739
11740 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11741                                        u32 alu_state, u32 alu_limit)
11742 {
11743         /* If we arrived here from different branches with different
11744          * state or limits to sanitize, then this won't work.
11745          */
11746         if (aux->alu_state &&
11747             (aux->alu_state != alu_state ||
11748              aux->alu_limit != alu_limit))
11749                 return REASON_PATHS;
11750
11751         /* Corresponding fixup done in do_misc_fixups(). */
11752         aux->alu_state = alu_state;
11753         aux->alu_limit = alu_limit;
11754         return 0;
11755 }
11756
11757 static int sanitize_val_alu(struct bpf_verifier_env *env,
11758                             struct bpf_insn *insn)
11759 {
11760         struct bpf_insn_aux_data *aux = cur_aux(env);
11761
11762         if (can_skip_alu_sanitation(env, insn))
11763                 return 0;
11764
11765         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11766 }
11767
11768 static bool sanitize_needed(u8 opcode)
11769 {
11770         return opcode == BPF_ADD || opcode == BPF_SUB;
11771 }
11772
11773 struct bpf_sanitize_info {
11774         struct bpf_insn_aux_data aux;
11775         bool mask_to_left;
11776 };
11777
11778 static struct bpf_verifier_state *
11779 sanitize_speculative_path(struct bpf_verifier_env *env,
11780                           const struct bpf_insn *insn,
11781                           u32 next_idx, u32 curr_idx)
11782 {
11783         struct bpf_verifier_state *branch;
11784         struct bpf_reg_state *regs;
11785
11786         branch = push_stack(env, next_idx, curr_idx, true);
11787         if (branch && insn) {
11788                 regs = branch->frame[branch->curframe]->regs;
11789                 if (BPF_SRC(insn->code) == BPF_K) {
11790                         mark_reg_unknown(env, regs, insn->dst_reg);
11791                 } else if (BPF_SRC(insn->code) == BPF_X) {
11792                         mark_reg_unknown(env, regs, insn->dst_reg);
11793                         mark_reg_unknown(env, regs, insn->src_reg);
11794                 }
11795         }
11796         return branch;
11797 }
11798
11799 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11800                             struct bpf_insn *insn,
11801                             const struct bpf_reg_state *ptr_reg,
11802                             const struct bpf_reg_state *off_reg,
11803                             struct bpf_reg_state *dst_reg,
11804                             struct bpf_sanitize_info *info,
11805                             const bool commit_window)
11806 {
11807         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11808         struct bpf_verifier_state *vstate = env->cur_state;
11809         bool off_is_imm = tnum_is_const(off_reg->var_off);
11810         bool off_is_neg = off_reg->smin_value < 0;
11811         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11812         u8 opcode = BPF_OP(insn->code);
11813         u32 alu_state, alu_limit;
11814         struct bpf_reg_state tmp;
11815         bool ret;
11816         int err;
11817
11818         if (can_skip_alu_sanitation(env, insn))
11819                 return 0;
11820
11821         /* We already marked aux for masking from non-speculative
11822          * paths, thus we got here in the first place. We only care
11823          * to explore bad access from here.
11824          */
11825         if (vstate->speculative)
11826                 goto do_sim;
11827
11828         if (!commit_window) {
11829                 if (!tnum_is_const(off_reg->var_off) &&
11830                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11831                         return REASON_BOUNDS;
11832
11833                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11834                                      (opcode == BPF_SUB && !off_is_neg);
11835         }
11836
11837         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11838         if (err < 0)
11839                 return err;
11840
11841         if (commit_window) {
11842                 /* In commit phase we narrow the masking window based on
11843                  * the observed pointer move after the simulated operation.
11844                  */
11845                 alu_state = info->aux.alu_state;
11846                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11847         } else {
11848                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11849                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11850                 alu_state |= ptr_is_dst_reg ?
11851                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11852
11853                 /* Limit pruning on unknown scalars to enable deep search for
11854                  * potential masking differences from other program paths.
11855                  */
11856                 if (!off_is_imm)
11857                         env->explore_alu_limits = true;
11858         }
11859
11860         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11861         if (err < 0)
11862                 return err;
11863 do_sim:
11864         /* If we're in commit phase, we're done here given we already
11865          * pushed the truncated dst_reg into the speculative verification
11866          * stack.
11867          *
11868          * Also, when register is a known constant, we rewrite register-based
11869          * operation to immediate-based, and thus do not need masking (and as
11870          * a consequence, do not need to simulate the zero-truncation either).
11871          */
11872         if (commit_window || off_is_imm)
11873                 return 0;
11874
11875         /* Simulate and find potential out-of-bounds access under
11876          * speculative execution from truncation as a result of
11877          * masking when off was not within expected range. If off
11878          * sits in dst, then we temporarily need to move ptr there
11879          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11880          * for cases where we use K-based arithmetic in one direction
11881          * and truncated reg-based in the other in order to explore
11882          * bad access.
11883          */
11884         if (!ptr_is_dst_reg) {
11885                 tmp = *dst_reg;
11886                 copy_register_state(dst_reg, ptr_reg);
11887         }
11888         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11889                                         env->insn_idx);
11890         if (!ptr_is_dst_reg && ret)
11891                 *dst_reg = tmp;
11892         return !ret ? REASON_STACK : 0;
11893 }
11894
11895 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11896 {
11897         struct bpf_verifier_state *vstate = env->cur_state;
11898
11899         /* If we simulate paths under speculation, we don't update the
11900          * insn as 'seen' such that when we verify unreachable paths in
11901          * the non-speculative domain, sanitize_dead_code() can still
11902          * rewrite/sanitize them.
11903          */
11904         if (!vstate->speculative)
11905                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11906 }
11907
11908 static int sanitize_err(struct bpf_verifier_env *env,
11909                         const struct bpf_insn *insn, int reason,
11910                         const struct bpf_reg_state *off_reg,
11911                         const struct bpf_reg_state *dst_reg)
11912 {
11913         static const char *err = "pointer arithmetic with it prohibited for !root";
11914         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11915         u32 dst = insn->dst_reg, src = insn->src_reg;
11916
11917         switch (reason) {
11918         case REASON_BOUNDS:
11919                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11920                         off_reg == dst_reg ? dst : src, err);
11921                 break;
11922         case REASON_TYPE:
11923                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11924                         off_reg == dst_reg ? src : dst, err);
11925                 break;
11926         case REASON_PATHS:
11927                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11928                         dst, op, err);
11929                 break;
11930         case REASON_LIMIT:
11931                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11932                         dst, op, err);
11933                 break;
11934         case REASON_STACK:
11935                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11936                         dst, err);
11937                 break;
11938         default:
11939                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11940                         reason);
11941                 break;
11942         }
11943
11944         return -EACCES;
11945 }
11946
11947 /* check that stack access falls within stack limits and that 'reg' doesn't
11948  * have a variable offset.
11949  *
11950  * Variable offset is prohibited for unprivileged mode for simplicity since it
11951  * requires corresponding support in Spectre masking for stack ALU.  See also
11952  * retrieve_ptr_limit().
11953  *
11954  *
11955  * 'off' includes 'reg->off'.
11956  */
11957 static int check_stack_access_for_ptr_arithmetic(
11958                                 struct bpf_verifier_env *env,
11959                                 int regno,
11960                                 const struct bpf_reg_state *reg,
11961                                 int off)
11962 {
11963         if (!tnum_is_const(reg->var_off)) {
11964                 char tn_buf[48];
11965
11966                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
11967                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
11968                         regno, tn_buf, off);
11969                 return -EACCES;
11970         }
11971
11972         if (off >= 0 || off < -MAX_BPF_STACK) {
11973                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
11974                         "prohibited for !root; off=%d\n", regno, off);
11975                 return -EACCES;
11976         }
11977
11978         return 0;
11979 }
11980
11981 static int sanitize_check_bounds(struct bpf_verifier_env *env,
11982                                  const struct bpf_insn *insn,
11983                                  const struct bpf_reg_state *dst_reg)
11984 {
11985         u32 dst = insn->dst_reg;
11986
11987         /* For unprivileged we require that resulting offset must be in bounds
11988          * in order to be able to sanitize access later on.
11989          */
11990         if (env->bypass_spec_v1)
11991                 return 0;
11992
11993         switch (dst_reg->type) {
11994         case PTR_TO_STACK:
11995                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
11996                                         dst_reg->off + dst_reg->var_off.value))
11997                         return -EACCES;
11998                 break;
11999         case PTR_TO_MAP_VALUE:
12000                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12001                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12002                                 "prohibited for !root\n", dst);
12003                         return -EACCES;
12004                 }
12005                 break;
12006         default:
12007                 break;
12008         }
12009
12010         return 0;
12011 }
12012
12013 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12014  * Caller should also handle BPF_MOV case separately.
12015  * If we return -EACCES, caller may want to try again treating pointer as a
12016  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12017  */
12018 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12019                                    struct bpf_insn *insn,
12020                                    const struct bpf_reg_state *ptr_reg,
12021                                    const struct bpf_reg_state *off_reg)
12022 {
12023         struct bpf_verifier_state *vstate = env->cur_state;
12024         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12025         struct bpf_reg_state *regs = state->regs, *dst_reg;
12026         bool known = tnum_is_const(off_reg->var_off);
12027         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12028             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12029         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12030             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12031         struct bpf_sanitize_info info = {};
12032         u8 opcode = BPF_OP(insn->code);
12033         u32 dst = insn->dst_reg;
12034         int ret;
12035
12036         dst_reg = &regs[dst];
12037
12038         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12039             smin_val > smax_val || umin_val > umax_val) {
12040                 /* Taint dst register if offset had invalid bounds derived from
12041                  * e.g. dead branches.
12042                  */
12043                 __mark_reg_unknown(env, dst_reg);
12044                 return 0;
12045         }
12046
12047         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12048                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12049                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12050                         __mark_reg_unknown(env, dst_reg);
12051                         return 0;
12052                 }
12053
12054                 verbose(env,
12055                         "R%d 32-bit pointer arithmetic prohibited\n",
12056                         dst);
12057                 return -EACCES;
12058         }
12059
12060         if (ptr_reg->type & PTR_MAYBE_NULL) {
12061                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12062                         dst, reg_type_str(env, ptr_reg->type));
12063                 return -EACCES;
12064         }
12065
12066         switch (base_type(ptr_reg->type)) {
12067         case CONST_PTR_TO_MAP:
12068                 /* smin_val represents the known value */
12069                 if (known && smin_val == 0 && opcode == BPF_ADD)
12070                         break;
12071                 fallthrough;
12072         case PTR_TO_PACKET_END:
12073         case PTR_TO_SOCKET:
12074         case PTR_TO_SOCK_COMMON:
12075         case PTR_TO_TCP_SOCK:
12076         case PTR_TO_XDP_SOCK:
12077                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12078                         dst, reg_type_str(env, ptr_reg->type));
12079                 return -EACCES;
12080         default:
12081                 break;
12082         }
12083
12084         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12085          * The id may be overwritten later if we create a new variable offset.
12086          */
12087         dst_reg->type = ptr_reg->type;
12088         dst_reg->id = ptr_reg->id;
12089
12090         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12091             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12092                 return -EINVAL;
12093
12094         /* pointer types do not carry 32-bit bounds at the moment. */
12095         __mark_reg32_unbounded(dst_reg);
12096
12097         if (sanitize_needed(opcode)) {
12098                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12099                                        &info, false);
12100                 if (ret < 0)
12101                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12102         }
12103
12104         switch (opcode) {
12105         case BPF_ADD:
12106                 /* We can take a fixed offset as long as it doesn't overflow
12107                  * the s32 'off' field
12108                  */
12109                 if (known && (ptr_reg->off + smin_val ==
12110                               (s64)(s32)(ptr_reg->off + smin_val))) {
12111                         /* pointer += K.  Accumulate it into fixed offset */
12112                         dst_reg->smin_value = smin_ptr;
12113                         dst_reg->smax_value = smax_ptr;
12114                         dst_reg->umin_value = umin_ptr;
12115                         dst_reg->umax_value = umax_ptr;
12116                         dst_reg->var_off = ptr_reg->var_off;
12117                         dst_reg->off = ptr_reg->off + smin_val;
12118                         dst_reg->raw = ptr_reg->raw;
12119                         break;
12120                 }
12121                 /* A new variable offset is created.  Note that off_reg->off
12122                  * == 0, since it's a scalar.
12123                  * dst_reg gets the pointer type and since some positive
12124                  * integer value was added to the pointer, give it a new 'id'
12125                  * if it's a PTR_TO_PACKET.
12126                  * this creates a new 'base' pointer, off_reg (variable) gets
12127                  * added into the variable offset, and we copy the fixed offset
12128                  * from ptr_reg.
12129                  */
12130                 if (signed_add_overflows(smin_ptr, smin_val) ||
12131                     signed_add_overflows(smax_ptr, smax_val)) {
12132                         dst_reg->smin_value = S64_MIN;
12133                         dst_reg->smax_value = S64_MAX;
12134                 } else {
12135                         dst_reg->smin_value = smin_ptr + smin_val;
12136                         dst_reg->smax_value = smax_ptr + smax_val;
12137                 }
12138                 if (umin_ptr + umin_val < umin_ptr ||
12139                     umax_ptr + umax_val < umax_ptr) {
12140                         dst_reg->umin_value = 0;
12141                         dst_reg->umax_value = U64_MAX;
12142                 } else {
12143                         dst_reg->umin_value = umin_ptr + umin_val;
12144                         dst_reg->umax_value = umax_ptr + umax_val;
12145                 }
12146                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12147                 dst_reg->off = ptr_reg->off;
12148                 dst_reg->raw = ptr_reg->raw;
12149                 if (reg_is_pkt_pointer(ptr_reg)) {
12150                         dst_reg->id = ++env->id_gen;
12151                         /* something was added to pkt_ptr, set range to zero */
12152                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12153                 }
12154                 break;
12155         case BPF_SUB:
12156                 if (dst_reg == off_reg) {
12157                         /* scalar -= pointer.  Creates an unknown scalar */
12158                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12159                                 dst);
12160                         return -EACCES;
12161                 }
12162                 /* We don't allow subtraction from FP, because (according to
12163                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12164                  * be able to deal with it.
12165                  */
12166                 if (ptr_reg->type == PTR_TO_STACK) {
12167                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12168                                 dst);
12169                         return -EACCES;
12170                 }
12171                 if (known && (ptr_reg->off - smin_val ==
12172                               (s64)(s32)(ptr_reg->off - smin_val))) {
12173                         /* pointer -= K.  Subtract it from fixed offset */
12174                         dst_reg->smin_value = smin_ptr;
12175                         dst_reg->smax_value = smax_ptr;
12176                         dst_reg->umin_value = umin_ptr;
12177                         dst_reg->umax_value = umax_ptr;
12178                         dst_reg->var_off = ptr_reg->var_off;
12179                         dst_reg->id = ptr_reg->id;
12180                         dst_reg->off = ptr_reg->off - smin_val;
12181                         dst_reg->raw = ptr_reg->raw;
12182                         break;
12183                 }
12184                 /* A new variable offset is created.  If the subtrahend is known
12185                  * nonnegative, then any reg->range we had before is still good.
12186                  */
12187                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12188                     signed_sub_overflows(smax_ptr, smin_val)) {
12189                         /* Overflow possible, we know nothing */
12190                         dst_reg->smin_value = S64_MIN;
12191                         dst_reg->smax_value = S64_MAX;
12192                 } else {
12193                         dst_reg->smin_value = smin_ptr - smax_val;
12194                         dst_reg->smax_value = smax_ptr - smin_val;
12195                 }
12196                 if (umin_ptr < umax_val) {
12197                         /* Overflow possible, we know nothing */
12198                         dst_reg->umin_value = 0;
12199                         dst_reg->umax_value = U64_MAX;
12200                 } else {
12201                         /* Cannot overflow (as long as bounds are consistent) */
12202                         dst_reg->umin_value = umin_ptr - umax_val;
12203                         dst_reg->umax_value = umax_ptr - umin_val;
12204                 }
12205                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12206                 dst_reg->off = ptr_reg->off;
12207                 dst_reg->raw = ptr_reg->raw;
12208                 if (reg_is_pkt_pointer(ptr_reg)) {
12209                         dst_reg->id = ++env->id_gen;
12210                         /* something was added to pkt_ptr, set range to zero */
12211                         if (smin_val < 0)
12212                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12213                 }
12214                 break;
12215         case BPF_AND:
12216         case BPF_OR:
12217         case BPF_XOR:
12218                 /* bitwise ops on pointers are troublesome, prohibit. */
12219                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12220                         dst, bpf_alu_string[opcode >> 4]);
12221                 return -EACCES;
12222         default:
12223                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12224                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12225                         dst, bpf_alu_string[opcode >> 4]);
12226                 return -EACCES;
12227         }
12228
12229         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12230                 return -EINVAL;
12231         reg_bounds_sync(dst_reg);
12232         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12233                 return -EACCES;
12234         if (sanitize_needed(opcode)) {
12235                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12236                                        &info, true);
12237                 if (ret < 0)
12238                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12239         }
12240
12241         return 0;
12242 }
12243
12244 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12245                                  struct bpf_reg_state *src_reg)
12246 {
12247         s32 smin_val = src_reg->s32_min_value;
12248         s32 smax_val = src_reg->s32_max_value;
12249         u32 umin_val = src_reg->u32_min_value;
12250         u32 umax_val = src_reg->u32_max_value;
12251
12252         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12253             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12254                 dst_reg->s32_min_value = S32_MIN;
12255                 dst_reg->s32_max_value = S32_MAX;
12256         } else {
12257                 dst_reg->s32_min_value += smin_val;
12258                 dst_reg->s32_max_value += smax_val;
12259         }
12260         if (dst_reg->u32_min_value + umin_val < umin_val ||
12261             dst_reg->u32_max_value + umax_val < umax_val) {
12262                 dst_reg->u32_min_value = 0;
12263                 dst_reg->u32_max_value = U32_MAX;
12264         } else {
12265                 dst_reg->u32_min_value += umin_val;
12266                 dst_reg->u32_max_value += umax_val;
12267         }
12268 }
12269
12270 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12271                                struct bpf_reg_state *src_reg)
12272 {
12273         s64 smin_val = src_reg->smin_value;
12274         s64 smax_val = src_reg->smax_value;
12275         u64 umin_val = src_reg->umin_value;
12276         u64 umax_val = src_reg->umax_value;
12277
12278         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12279             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12280                 dst_reg->smin_value = S64_MIN;
12281                 dst_reg->smax_value = S64_MAX;
12282         } else {
12283                 dst_reg->smin_value += smin_val;
12284                 dst_reg->smax_value += smax_val;
12285         }
12286         if (dst_reg->umin_value + umin_val < umin_val ||
12287             dst_reg->umax_value + umax_val < umax_val) {
12288                 dst_reg->umin_value = 0;
12289                 dst_reg->umax_value = U64_MAX;
12290         } else {
12291                 dst_reg->umin_value += umin_val;
12292                 dst_reg->umax_value += umax_val;
12293         }
12294 }
12295
12296 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12297                                  struct bpf_reg_state *src_reg)
12298 {
12299         s32 smin_val = src_reg->s32_min_value;
12300         s32 smax_val = src_reg->s32_max_value;
12301         u32 umin_val = src_reg->u32_min_value;
12302         u32 umax_val = src_reg->u32_max_value;
12303
12304         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12305             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12306                 /* Overflow possible, we know nothing */
12307                 dst_reg->s32_min_value = S32_MIN;
12308                 dst_reg->s32_max_value = S32_MAX;
12309         } else {
12310                 dst_reg->s32_min_value -= smax_val;
12311                 dst_reg->s32_max_value -= smin_val;
12312         }
12313         if (dst_reg->u32_min_value < umax_val) {
12314                 /* Overflow possible, we know nothing */
12315                 dst_reg->u32_min_value = 0;
12316                 dst_reg->u32_max_value = U32_MAX;
12317         } else {
12318                 /* Cannot overflow (as long as bounds are consistent) */
12319                 dst_reg->u32_min_value -= umax_val;
12320                 dst_reg->u32_max_value -= umin_val;
12321         }
12322 }
12323
12324 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12325                                struct bpf_reg_state *src_reg)
12326 {
12327         s64 smin_val = src_reg->smin_value;
12328         s64 smax_val = src_reg->smax_value;
12329         u64 umin_val = src_reg->umin_value;
12330         u64 umax_val = src_reg->umax_value;
12331
12332         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12333             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12334                 /* Overflow possible, we know nothing */
12335                 dst_reg->smin_value = S64_MIN;
12336                 dst_reg->smax_value = S64_MAX;
12337         } else {
12338                 dst_reg->smin_value -= smax_val;
12339                 dst_reg->smax_value -= smin_val;
12340         }
12341         if (dst_reg->umin_value < umax_val) {
12342                 /* Overflow possible, we know nothing */
12343                 dst_reg->umin_value = 0;
12344                 dst_reg->umax_value = U64_MAX;
12345         } else {
12346                 /* Cannot overflow (as long as bounds are consistent) */
12347                 dst_reg->umin_value -= umax_val;
12348                 dst_reg->umax_value -= umin_val;
12349         }
12350 }
12351
12352 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12353                                  struct bpf_reg_state *src_reg)
12354 {
12355         s32 smin_val = src_reg->s32_min_value;
12356         u32 umin_val = src_reg->u32_min_value;
12357         u32 umax_val = src_reg->u32_max_value;
12358
12359         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12360                 /* Ain't nobody got time to multiply that sign */
12361                 __mark_reg32_unbounded(dst_reg);
12362                 return;
12363         }
12364         /* Both values are positive, so we can work with unsigned and
12365          * copy the result to signed (unless it exceeds S32_MAX).
12366          */
12367         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12368                 /* Potential overflow, we know nothing */
12369                 __mark_reg32_unbounded(dst_reg);
12370                 return;
12371         }
12372         dst_reg->u32_min_value *= umin_val;
12373         dst_reg->u32_max_value *= umax_val;
12374         if (dst_reg->u32_max_value > S32_MAX) {
12375                 /* Overflow possible, we know nothing */
12376                 dst_reg->s32_min_value = S32_MIN;
12377                 dst_reg->s32_max_value = S32_MAX;
12378         } else {
12379                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12380                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12381         }
12382 }
12383
12384 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12385                                struct bpf_reg_state *src_reg)
12386 {
12387         s64 smin_val = src_reg->smin_value;
12388         u64 umin_val = src_reg->umin_value;
12389         u64 umax_val = src_reg->umax_value;
12390
12391         if (smin_val < 0 || dst_reg->smin_value < 0) {
12392                 /* Ain't nobody got time to multiply that sign */
12393                 __mark_reg64_unbounded(dst_reg);
12394                 return;
12395         }
12396         /* Both values are positive, so we can work with unsigned and
12397          * copy the result to signed (unless it exceeds S64_MAX).
12398          */
12399         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12400                 /* Potential overflow, we know nothing */
12401                 __mark_reg64_unbounded(dst_reg);
12402                 return;
12403         }
12404         dst_reg->umin_value *= umin_val;
12405         dst_reg->umax_value *= umax_val;
12406         if (dst_reg->umax_value > S64_MAX) {
12407                 /* Overflow possible, we know nothing */
12408                 dst_reg->smin_value = S64_MIN;
12409                 dst_reg->smax_value = S64_MAX;
12410         } else {
12411                 dst_reg->smin_value = dst_reg->umin_value;
12412                 dst_reg->smax_value = dst_reg->umax_value;
12413         }
12414 }
12415
12416 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12417                                  struct bpf_reg_state *src_reg)
12418 {
12419         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12420         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12421         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12422         s32 smin_val = src_reg->s32_min_value;
12423         u32 umax_val = src_reg->u32_max_value;
12424
12425         if (src_known && dst_known) {
12426                 __mark_reg32_known(dst_reg, var32_off.value);
12427                 return;
12428         }
12429
12430         /* We get our minimum from the var_off, since that's inherently
12431          * bitwise.  Our maximum is the minimum of the operands' maxima.
12432          */
12433         dst_reg->u32_min_value = var32_off.value;
12434         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12435         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12436                 /* Lose signed bounds when ANDing negative numbers,
12437                  * ain't nobody got time for that.
12438                  */
12439                 dst_reg->s32_min_value = S32_MIN;
12440                 dst_reg->s32_max_value = S32_MAX;
12441         } else {
12442                 /* ANDing two positives gives a positive, so safe to
12443                  * cast result into s64.
12444                  */
12445                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12446                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12447         }
12448 }
12449
12450 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12451                                struct bpf_reg_state *src_reg)
12452 {
12453         bool src_known = tnum_is_const(src_reg->var_off);
12454         bool dst_known = tnum_is_const(dst_reg->var_off);
12455         s64 smin_val = src_reg->smin_value;
12456         u64 umax_val = src_reg->umax_value;
12457
12458         if (src_known && dst_known) {
12459                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12460                 return;
12461         }
12462
12463         /* We get our minimum from the var_off, since that's inherently
12464          * bitwise.  Our maximum is the minimum of the operands' maxima.
12465          */
12466         dst_reg->umin_value = dst_reg->var_off.value;
12467         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12468         if (dst_reg->smin_value < 0 || smin_val < 0) {
12469                 /* Lose signed bounds when ANDing negative numbers,
12470                  * ain't nobody got time for that.
12471                  */
12472                 dst_reg->smin_value = S64_MIN;
12473                 dst_reg->smax_value = S64_MAX;
12474         } else {
12475                 /* ANDing two positives gives a positive, so safe to
12476                  * cast result into s64.
12477                  */
12478                 dst_reg->smin_value = dst_reg->umin_value;
12479                 dst_reg->smax_value = dst_reg->umax_value;
12480         }
12481         /* We may learn something more from the var_off */
12482         __update_reg_bounds(dst_reg);
12483 }
12484
12485 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12486                                 struct bpf_reg_state *src_reg)
12487 {
12488         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12489         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12490         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12491         s32 smin_val = src_reg->s32_min_value;
12492         u32 umin_val = src_reg->u32_min_value;
12493
12494         if (src_known && dst_known) {
12495                 __mark_reg32_known(dst_reg, var32_off.value);
12496                 return;
12497         }
12498
12499         /* We get our maximum from the var_off, and our minimum is the
12500          * maximum of the operands' minima
12501          */
12502         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12503         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12504         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12505                 /* Lose signed bounds when ORing negative numbers,
12506                  * ain't nobody got time for that.
12507                  */
12508                 dst_reg->s32_min_value = S32_MIN;
12509                 dst_reg->s32_max_value = S32_MAX;
12510         } else {
12511                 /* ORing two positives gives a positive, so safe to
12512                  * cast result into s64.
12513                  */
12514                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12515                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12516         }
12517 }
12518
12519 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12520                               struct bpf_reg_state *src_reg)
12521 {
12522         bool src_known = tnum_is_const(src_reg->var_off);
12523         bool dst_known = tnum_is_const(dst_reg->var_off);
12524         s64 smin_val = src_reg->smin_value;
12525         u64 umin_val = src_reg->umin_value;
12526
12527         if (src_known && dst_known) {
12528                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12529                 return;
12530         }
12531
12532         /* We get our maximum from the var_off, and our minimum is the
12533          * maximum of the operands' minima
12534          */
12535         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12536         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12537         if (dst_reg->smin_value < 0 || smin_val < 0) {
12538                 /* Lose signed bounds when ORing negative numbers,
12539                  * ain't nobody got time for that.
12540                  */
12541                 dst_reg->smin_value = S64_MIN;
12542                 dst_reg->smax_value = S64_MAX;
12543         } else {
12544                 /* ORing two positives gives a positive, so safe to
12545                  * cast result into s64.
12546                  */
12547                 dst_reg->smin_value = dst_reg->umin_value;
12548                 dst_reg->smax_value = dst_reg->umax_value;
12549         }
12550         /* We may learn something more from the var_off */
12551         __update_reg_bounds(dst_reg);
12552 }
12553
12554 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12555                                  struct bpf_reg_state *src_reg)
12556 {
12557         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12558         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12559         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12560         s32 smin_val = src_reg->s32_min_value;
12561
12562         if (src_known && dst_known) {
12563                 __mark_reg32_known(dst_reg, var32_off.value);
12564                 return;
12565         }
12566
12567         /* We get both minimum and maximum from the var32_off. */
12568         dst_reg->u32_min_value = var32_off.value;
12569         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12570
12571         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12572                 /* XORing two positive sign numbers gives a positive,
12573                  * so safe to cast u32 result into s32.
12574                  */
12575                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12576                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12577         } else {
12578                 dst_reg->s32_min_value = S32_MIN;
12579                 dst_reg->s32_max_value = S32_MAX;
12580         }
12581 }
12582
12583 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12584                                struct bpf_reg_state *src_reg)
12585 {
12586         bool src_known = tnum_is_const(src_reg->var_off);
12587         bool dst_known = tnum_is_const(dst_reg->var_off);
12588         s64 smin_val = src_reg->smin_value;
12589
12590         if (src_known && dst_known) {
12591                 /* dst_reg->var_off.value has been updated earlier */
12592                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12593                 return;
12594         }
12595
12596         /* We get both minimum and maximum from the var_off. */
12597         dst_reg->umin_value = dst_reg->var_off.value;
12598         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12599
12600         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12601                 /* XORing two positive sign numbers gives a positive,
12602                  * so safe to cast u64 result into s64.
12603                  */
12604                 dst_reg->smin_value = dst_reg->umin_value;
12605                 dst_reg->smax_value = dst_reg->umax_value;
12606         } else {
12607                 dst_reg->smin_value = S64_MIN;
12608                 dst_reg->smax_value = S64_MAX;
12609         }
12610
12611         __update_reg_bounds(dst_reg);
12612 }
12613
12614 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12615                                    u64 umin_val, u64 umax_val)
12616 {
12617         /* We lose all sign bit information (except what we can pick
12618          * up from var_off)
12619          */
12620         dst_reg->s32_min_value = S32_MIN;
12621         dst_reg->s32_max_value = S32_MAX;
12622         /* If we might shift our top bit out, then we know nothing */
12623         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12624                 dst_reg->u32_min_value = 0;
12625                 dst_reg->u32_max_value = U32_MAX;
12626         } else {
12627                 dst_reg->u32_min_value <<= umin_val;
12628                 dst_reg->u32_max_value <<= umax_val;
12629         }
12630 }
12631
12632 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12633                                  struct bpf_reg_state *src_reg)
12634 {
12635         u32 umax_val = src_reg->u32_max_value;
12636         u32 umin_val = src_reg->u32_min_value;
12637         /* u32 alu operation will zext upper bits */
12638         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12639
12640         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12641         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12642         /* Not required but being careful mark reg64 bounds as unknown so
12643          * that we are forced to pick them up from tnum and zext later and
12644          * if some path skips this step we are still safe.
12645          */
12646         __mark_reg64_unbounded(dst_reg);
12647         __update_reg32_bounds(dst_reg);
12648 }
12649
12650 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12651                                    u64 umin_val, u64 umax_val)
12652 {
12653         /* Special case <<32 because it is a common compiler pattern to sign
12654          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12655          * positive we know this shift will also be positive so we can track
12656          * bounds correctly. Otherwise we lose all sign bit information except
12657          * what we can pick up from var_off. Perhaps we can generalize this
12658          * later to shifts of any length.
12659          */
12660         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12661                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12662         else
12663                 dst_reg->smax_value = S64_MAX;
12664
12665         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12666                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12667         else
12668                 dst_reg->smin_value = S64_MIN;
12669
12670         /* If we might shift our top bit out, then we know nothing */
12671         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12672                 dst_reg->umin_value = 0;
12673                 dst_reg->umax_value = U64_MAX;
12674         } else {
12675                 dst_reg->umin_value <<= umin_val;
12676                 dst_reg->umax_value <<= umax_val;
12677         }
12678 }
12679
12680 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12681                                struct bpf_reg_state *src_reg)
12682 {
12683         u64 umax_val = src_reg->umax_value;
12684         u64 umin_val = src_reg->umin_value;
12685
12686         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12687         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12688         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12689
12690         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12691         /* We may learn something more from the var_off */
12692         __update_reg_bounds(dst_reg);
12693 }
12694
12695 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12696                                  struct bpf_reg_state *src_reg)
12697 {
12698         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12699         u32 umax_val = src_reg->u32_max_value;
12700         u32 umin_val = src_reg->u32_min_value;
12701
12702         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12703          * be negative, then either:
12704          * 1) src_reg might be zero, so the sign bit of the result is
12705          *    unknown, so we lose our signed bounds
12706          * 2) it's known negative, thus the unsigned bounds capture the
12707          *    signed bounds
12708          * 3) the signed bounds cross zero, so they tell us nothing
12709          *    about the result
12710          * If the value in dst_reg is known nonnegative, then again the
12711          * unsigned bounds capture the signed bounds.
12712          * Thus, in all cases it suffices to blow away our signed bounds
12713          * and rely on inferring new ones from the unsigned bounds and
12714          * var_off of the result.
12715          */
12716         dst_reg->s32_min_value = S32_MIN;
12717         dst_reg->s32_max_value = S32_MAX;
12718
12719         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12720         dst_reg->u32_min_value >>= umax_val;
12721         dst_reg->u32_max_value >>= umin_val;
12722
12723         __mark_reg64_unbounded(dst_reg);
12724         __update_reg32_bounds(dst_reg);
12725 }
12726
12727 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12728                                struct bpf_reg_state *src_reg)
12729 {
12730         u64 umax_val = src_reg->umax_value;
12731         u64 umin_val = src_reg->umin_value;
12732
12733         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12734          * be negative, then either:
12735          * 1) src_reg might be zero, so the sign bit of the result is
12736          *    unknown, so we lose our signed bounds
12737          * 2) it's known negative, thus the unsigned bounds capture the
12738          *    signed bounds
12739          * 3) the signed bounds cross zero, so they tell us nothing
12740          *    about the result
12741          * If the value in dst_reg is known nonnegative, then again the
12742          * unsigned bounds capture the signed bounds.
12743          * Thus, in all cases it suffices to blow away our signed bounds
12744          * and rely on inferring new ones from the unsigned bounds and
12745          * var_off of the result.
12746          */
12747         dst_reg->smin_value = S64_MIN;
12748         dst_reg->smax_value = S64_MAX;
12749         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12750         dst_reg->umin_value >>= umax_val;
12751         dst_reg->umax_value >>= umin_val;
12752
12753         /* Its not easy to operate on alu32 bounds here because it depends
12754          * on bits being shifted in. Take easy way out and mark unbounded
12755          * so we can recalculate later from tnum.
12756          */
12757         __mark_reg32_unbounded(dst_reg);
12758         __update_reg_bounds(dst_reg);
12759 }
12760
12761 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12762                                   struct bpf_reg_state *src_reg)
12763 {
12764         u64 umin_val = src_reg->u32_min_value;
12765
12766         /* Upon reaching here, src_known is true and
12767          * umax_val is equal to umin_val.
12768          */
12769         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12770         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12771
12772         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12773
12774         /* blow away the dst_reg umin_value/umax_value and rely on
12775          * dst_reg var_off to refine the result.
12776          */
12777         dst_reg->u32_min_value = 0;
12778         dst_reg->u32_max_value = U32_MAX;
12779
12780         __mark_reg64_unbounded(dst_reg);
12781         __update_reg32_bounds(dst_reg);
12782 }
12783
12784 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12785                                 struct bpf_reg_state *src_reg)
12786 {
12787         u64 umin_val = src_reg->umin_value;
12788
12789         /* Upon reaching here, src_known is true and umax_val is equal
12790          * to umin_val.
12791          */
12792         dst_reg->smin_value >>= umin_val;
12793         dst_reg->smax_value >>= umin_val;
12794
12795         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12796
12797         /* blow away the dst_reg umin_value/umax_value and rely on
12798          * dst_reg var_off to refine the result.
12799          */
12800         dst_reg->umin_value = 0;
12801         dst_reg->umax_value = U64_MAX;
12802
12803         /* Its not easy to operate on alu32 bounds here because it depends
12804          * on bits being shifted in from upper 32-bits. Take easy way out
12805          * and mark unbounded so we can recalculate later from tnum.
12806          */
12807         __mark_reg32_unbounded(dst_reg);
12808         __update_reg_bounds(dst_reg);
12809 }
12810
12811 /* WARNING: This function does calculations on 64-bit values, but the actual
12812  * execution may occur on 32-bit values. Therefore, things like bitshifts
12813  * need extra checks in the 32-bit case.
12814  */
12815 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12816                                       struct bpf_insn *insn,
12817                                       struct bpf_reg_state *dst_reg,
12818                                       struct bpf_reg_state src_reg)
12819 {
12820         struct bpf_reg_state *regs = cur_regs(env);
12821         u8 opcode = BPF_OP(insn->code);
12822         bool src_known;
12823         s64 smin_val, smax_val;
12824         u64 umin_val, umax_val;
12825         s32 s32_min_val, s32_max_val;
12826         u32 u32_min_val, u32_max_val;
12827         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12828         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12829         int ret;
12830
12831         smin_val = src_reg.smin_value;
12832         smax_val = src_reg.smax_value;
12833         umin_val = src_reg.umin_value;
12834         umax_val = src_reg.umax_value;
12835
12836         s32_min_val = src_reg.s32_min_value;
12837         s32_max_val = src_reg.s32_max_value;
12838         u32_min_val = src_reg.u32_min_value;
12839         u32_max_val = src_reg.u32_max_value;
12840
12841         if (alu32) {
12842                 src_known = tnum_subreg_is_const(src_reg.var_off);
12843                 if ((src_known &&
12844                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12845                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12846                         /* Taint dst register if offset had invalid bounds
12847                          * derived from e.g. dead branches.
12848                          */
12849                         __mark_reg_unknown(env, dst_reg);
12850                         return 0;
12851                 }
12852         } else {
12853                 src_known = tnum_is_const(src_reg.var_off);
12854                 if ((src_known &&
12855                      (smin_val != smax_val || umin_val != umax_val)) ||
12856                     smin_val > smax_val || umin_val > umax_val) {
12857                         /* Taint dst register if offset had invalid bounds
12858                          * derived from e.g. dead branches.
12859                          */
12860                         __mark_reg_unknown(env, dst_reg);
12861                         return 0;
12862                 }
12863         }
12864
12865         if (!src_known &&
12866             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12867                 __mark_reg_unknown(env, dst_reg);
12868                 return 0;
12869         }
12870
12871         if (sanitize_needed(opcode)) {
12872                 ret = sanitize_val_alu(env, insn);
12873                 if (ret < 0)
12874                         return sanitize_err(env, insn, ret, NULL, NULL);
12875         }
12876
12877         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12878          * There are two classes of instructions: The first class we track both
12879          * alu32 and alu64 sign/unsigned bounds independently this provides the
12880          * greatest amount of precision when alu operations are mixed with jmp32
12881          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12882          * and BPF_OR. This is possible because these ops have fairly easy to
12883          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12884          * See alu32 verifier tests for examples. The second class of
12885          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12886          * with regards to tracking sign/unsigned bounds because the bits may
12887          * cross subreg boundaries in the alu64 case. When this happens we mark
12888          * the reg unbounded in the subreg bound space and use the resulting
12889          * tnum to calculate an approximation of the sign/unsigned bounds.
12890          */
12891         switch (opcode) {
12892         case BPF_ADD:
12893                 scalar32_min_max_add(dst_reg, &src_reg);
12894                 scalar_min_max_add(dst_reg, &src_reg);
12895                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12896                 break;
12897         case BPF_SUB:
12898                 scalar32_min_max_sub(dst_reg, &src_reg);
12899                 scalar_min_max_sub(dst_reg, &src_reg);
12900                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12901                 break;
12902         case BPF_MUL:
12903                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12904                 scalar32_min_max_mul(dst_reg, &src_reg);
12905                 scalar_min_max_mul(dst_reg, &src_reg);
12906                 break;
12907         case BPF_AND:
12908                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12909                 scalar32_min_max_and(dst_reg, &src_reg);
12910                 scalar_min_max_and(dst_reg, &src_reg);
12911                 break;
12912         case BPF_OR:
12913                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12914                 scalar32_min_max_or(dst_reg, &src_reg);
12915                 scalar_min_max_or(dst_reg, &src_reg);
12916                 break;
12917         case BPF_XOR:
12918                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12919                 scalar32_min_max_xor(dst_reg, &src_reg);
12920                 scalar_min_max_xor(dst_reg, &src_reg);
12921                 break;
12922         case BPF_LSH:
12923                 if (umax_val >= insn_bitness) {
12924                         /* Shifts greater than 31 or 63 are undefined.
12925                          * This includes shifts by a negative number.
12926                          */
12927                         mark_reg_unknown(env, regs, insn->dst_reg);
12928                         break;
12929                 }
12930                 if (alu32)
12931                         scalar32_min_max_lsh(dst_reg, &src_reg);
12932                 else
12933                         scalar_min_max_lsh(dst_reg, &src_reg);
12934                 break;
12935         case BPF_RSH:
12936                 if (umax_val >= insn_bitness) {
12937                         /* Shifts greater than 31 or 63 are undefined.
12938                          * This includes shifts by a negative number.
12939                          */
12940                         mark_reg_unknown(env, regs, insn->dst_reg);
12941                         break;
12942                 }
12943                 if (alu32)
12944                         scalar32_min_max_rsh(dst_reg, &src_reg);
12945                 else
12946                         scalar_min_max_rsh(dst_reg, &src_reg);
12947                 break;
12948         case BPF_ARSH:
12949                 if (umax_val >= insn_bitness) {
12950                         /* Shifts greater than 31 or 63 are undefined.
12951                          * This includes shifts by a negative number.
12952                          */
12953                         mark_reg_unknown(env, regs, insn->dst_reg);
12954                         break;
12955                 }
12956                 if (alu32)
12957                         scalar32_min_max_arsh(dst_reg, &src_reg);
12958                 else
12959                         scalar_min_max_arsh(dst_reg, &src_reg);
12960                 break;
12961         default:
12962                 mark_reg_unknown(env, regs, insn->dst_reg);
12963                 break;
12964         }
12965
12966         /* ALU32 ops are zero extended into 64bit register */
12967         if (alu32)
12968                 zext_32_to_64(dst_reg);
12969         reg_bounds_sync(dst_reg);
12970         return 0;
12971 }
12972
12973 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
12974  * and var_off.
12975  */
12976 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
12977                                    struct bpf_insn *insn)
12978 {
12979         struct bpf_verifier_state *vstate = env->cur_state;
12980         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12981         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
12982         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
12983         u8 opcode = BPF_OP(insn->code);
12984         int err;
12985
12986         dst_reg = &regs[insn->dst_reg];
12987         src_reg = NULL;
12988         if (dst_reg->type != SCALAR_VALUE)
12989                 ptr_reg = dst_reg;
12990         else
12991                 /* Make sure ID is cleared otherwise dst_reg min/max could be
12992                  * incorrectly propagated into other registers by find_equal_scalars()
12993                  */
12994                 dst_reg->id = 0;
12995         if (BPF_SRC(insn->code) == BPF_X) {
12996                 src_reg = &regs[insn->src_reg];
12997                 if (src_reg->type != SCALAR_VALUE) {
12998                         if (dst_reg->type != SCALAR_VALUE) {
12999                                 /* Combining two pointers by any ALU op yields
13000                                  * an arbitrary scalar. Disallow all math except
13001                                  * pointer subtraction
13002                                  */
13003                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13004                                         mark_reg_unknown(env, regs, insn->dst_reg);
13005                                         return 0;
13006                                 }
13007                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13008                                         insn->dst_reg,
13009                                         bpf_alu_string[opcode >> 4]);
13010                                 return -EACCES;
13011                         } else {
13012                                 /* scalar += pointer
13013                                  * This is legal, but we have to reverse our
13014                                  * src/dest handling in computing the range
13015                                  */
13016                                 err = mark_chain_precision(env, insn->dst_reg);
13017                                 if (err)
13018                                         return err;
13019                                 return adjust_ptr_min_max_vals(env, insn,
13020                                                                src_reg, dst_reg);
13021                         }
13022                 } else if (ptr_reg) {
13023                         /* pointer += scalar */
13024                         err = mark_chain_precision(env, insn->src_reg);
13025                         if (err)
13026                                 return err;
13027                         return adjust_ptr_min_max_vals(env, insn,
13028                                                        dst_reg, src_reg);
13029                 } else if (dst_reg->precise) {
13030                         /* if dst_reg is precise, src_reg should be precise as well */
13031                         err = mark_chain_precision(env, insn->src_reg);
13032                         if (err)
13033                                 return err;
13034                 }
13035         } else {
13036                 /* Pretend the src is a reg with a known value, since we only
13037                  * need to be able to read from this state.
13038                  */
13039                 off_reg.type = SCALAR_VALUE;
13040                 __mark_reg_known(&off_reg, insn->imm);
13041                 src_reg = &off_reg;
13042                 if (ptr_reg) /* pointer += K */
13043                         return adjust_ptr_min_max_vals(env, insn,
13044                                                        ptr_reg, src_reg);
13045         }
13046
13047         /* Got here implies adding two SCALAR_VALUEs */
13048         if (WARN_ON_ONCE(ptr_reg)) {
13049                 print_verifier_state(env, state, true);
13050                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13051                 return -EINVAL;
13052         }
13053         if (WARN_ON(!src_reg)) {
13054                 print_verifier_state(env, state, true);
13055                 verbose(env, "verifier internal error: no src_reg\n");
13056                 return -EINVAL;
13057         }
13058         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13059 }
13060
13061 /* check validity of 32-bit and 64-bit arithmetic operations */
13062 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13063 {
13064         struct bpf_reg_state *regs = cur_regs(env);
13065         u8 opcode = BPF_OP(insn->code);
13066         int err;
13067
13068         if (opcode == BPF_END || opcode == BPF_NEG) {
13069                 if (opcode == BPF_NEG) {
13070                         if (BPF_SRC(insn->code) != BPF_K ||
13071                             insn->src_reg != BPF_REG_0 ||
13072                             insn->off != 0 || insn->imm != 0) {
13073                                 verbose(env, "BPF_NEG uses reserved fields\n");
13074                                 return -EINVAL;
13075                         }
13076                 } else {
13077                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13078                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13079                             BPF_CLASS(insn->code) == BPF_ALU64) {
13080                                 verbose(env, "BPF_END uses reserved fields\n");
13081                                 return -EINVAL;
13082                         }
13083                 }
13084
13085                 /* check src operand */
13086                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13087                 if (err)
13088                         return err;
13089
13090                 if (is_pointer_value(env, insn->dst_reg)) {
13091                         verbose(env, "R%d pointer arithmetic prohibited\n",
13092                                 insn->dst_reg);
13093                         return -EACCES;
13094                 }
13095
13096                 /* check dest operand */
13097                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13098                 if (err)
13099                         return err;
13100
13101         } else if (opcode == BPF_MOV) {
13102
13103                 if (BPF_SRC(insn->code) == BPF_X) {
13104                         if (insn->imm != 0) {
13105                                 verbose(env, "BPF_MOV uses reserved fields\n");
13106                                 return -EINVAL;
13107                         }
13108
13109                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13110                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13111                                         verbose(env, "BPF_MOV uses reserved fields\n");
13112                                         return -EINVAL;
13113                                 }
13114                         } else {
13115                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13116                                     insn->off != 32) {
13117                                         verbose(env, "BPF_MOV uses reserved fields\n");
13118                                         return -EINVAL;
13119                                 }
13120                         }
13121
13122                         /* check src operand */
13123                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13124                         if (err)
13125                                 return err;
13126                 } else {
13127                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13128                                 verbose(env, "BPF_MOV uses reserved fields\n");
13129                                 return -EINVAL;
13130                         }
13131                 }
13132
13133                 /* check dest operand, mark as required later */
13134                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13135                 if (err)
13136                         return err;
13137
13138                 if (BPF_SRC(insn->code) == BPF_X) {
13139                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13140                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13141                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13142                                        !tnum_is_const(src_reg->var_off);
13143
13144                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13145                                 if (insn->off == 0) {
13146                                         /* case: R1 = R2
13147                                          * copy register state to dest reg
13148                                          */
13149                                         if (need_id)
13150                                                 /* Assign src and dst registers the same ID
13151                                                  * that will be used by find_equal_scalars()
13152                                                  * to propagate min/max range.
13153                                                  */
13154                                                 src_reg->id = ++env->id_gen;
13155                                         copy_register_state(dst_reg, src_reg);
13156                                         dst_reg->live |= REG_LIVE_WRITTEN;
13157                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13158                                 } else {
13159                                         /* case: R1 = (s8, s16 s32)R2 */
13160                                         bool no_sext;
13161
13162                                         no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13163                                         if (no_sext && need_id)
13164                                                 src_reg->id = ++env->id_gen;
13165                                         copy_register_state(dst_reg, src_reg);
13166                                         if (!no_sext)
13167                                                 dst_reg->id = 0;
13168                                         coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13169                                         dst_reg->live |= REG_LIVE_WRITTEN;
13170                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13171                                 }
13172                         } else {
13173                                 /* R1 = (u32) R2 */
13174                                 if (is_pointer_value(env, insn->src_reg)) {
13175                                         verbose(env,
13176                                                 "R%d partial copy of pointer\n",
13177                                                 insn->src_reg);
13178                                         return -EACCES;
13179                                 } else if (src_reg->type == SCALAR_VALUE) {
13180                                         if (insn->off == 0) {
13181                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13182
13183                                                 if (is_src_reg_u32 && need_id)
13184                                                         src_reg->id = ++env->id_gen;
13185                                                 copy_register_state(dst_reg, src_reg);
13186                                                 /* Make sure ID is cleared if src_reg is not in u32
13187                                                  * range otherwise dst_reg min/max could be incorrectly
13188                                                  * propagated into src_reg by find_equal_scalars()
13189                                                  */
13190                                                 if (!is_src_reg_u32)
13191                                                         dst_reg->id = 0;
13192                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13193                                                 dst_reg->subreg_def = env->insn_idx + 1;
13194                                         } else {
13195                                                 /* case: W1 = (s8, s16)W2 */
13196                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13197
13198                                                 if (no_sext && need_id)
13199                                                         src_reg->id = ++env->id_gen;
13200                                                 copy_register_state(dst_reg, src_reg);
13201                                                 if (!no_sext)
13202                                                         dst_reg->id = 0;
13203                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13204                                                 dst_reg->subreg_def = env->insn_idx + 1;
13205                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13206                                         }
13207                                 } else {
13208                                         mark_reg_unknown(env, regs,
13209                                                          insn->dst_reg);
13210                                 }
13211                                 zext_32_to_64(dst_reg);
13212                                 reg_bounds_sync(dst_reg);
13213                         }
13214                 } else {
13215                         /* case: R = imm
13216                          * remember the value we stored into this reg
13217                          */
13218                         /* clear any state __mark_reg_known doesn't set */
13219                         mark_reg_unknown(env, regs, insn->dst_reg);
13220                         regs[insn->dst_reg].type = SCALAR_VALUE;
13221                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13222                                 __mark_reg_known(regs + insn->dst_reg,
13223                                                  insn->imm);
13224                         } else {
13225                                 __mark_reg_known(regs + insn->dst_reg,
13226                                                  (u32)insn->imm);
13227                         }
13228                 }
13229
13230         } else if (opcode > BPF_END) {
13231                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13232                 return -EINVAL;
13233
13234         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13235
13236                 if (BPF_SRC(insn->code) == BPF_X) {
13237                         if (insn->imm != 0 || insn->off != 0) {
13238                                 verbose(env, "BPF_ALU uses reserved fields\n");
13239                                 return -EINVAL;
13240                         }
13241                         /* check src1 operand */
13242                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13243                         if (err)
13244                                 return err;
13245                 } else {
13246                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13247                                 verbose(env, "BPF_ALU uses reserved fields\n");
13248                                 return -EINVAL;
13249                         }
13250                 }
13251
13252                 /* check src2 operand */
13253                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13254                 if (err)
13255                         return err;
13256
13257                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13258                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13259                         verbose(env, "div by zero\n");
13260                         return -EINVAL;
13261                 }
13262
13263                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13264                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13265                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13266
13267                         if (insn->imm < 0 || insn->imm >= size) {
13268                                 verbose(env, "invalid shift %d\n", insn->imm);
13269                                 return -EINVAL;
13270                         }
13271                 }
13272
13273                 /* check dest operand */
13274                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13275                 if (err)
13276                         return err;
13277
13278                 return adjust_reg_min_max_vals(env, insn);
13279         }
13280
13281         return 0;
13282 }
13283
13284 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13285                                    struct bpf_reg_state *dst_reg,
13286                                    enum bpf_reg_type type,
13287                                    bool range_right_open)
13288 {
13289         struct bpf_func_state *state;
13290         struct bpf_reg_state *reg;
13291         int new_range;
13292
13293         if (dst_reg->off < 0 ||
13294             (dst_reg->off == 0 && range_right_open))
13295                 /* This doesn't give us any range */
13296                 return;
13297
13298         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13299             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13300                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13301                  * than pkt_end, but that's because it's also less than pkt.
13302                  */
13303                 return;
13304
13305         new_range = dst_reg->off;
13306         if (range_right_open)
13307                 new_range++;
13308
13309         /* Examples for register markings:
13310          *
13311          * pkt_data in dst register:
13312          *
13313          *   r2 = r3;
13314          *   r2 += 8;
13315          *   if (r2 > pkt_end) goto <handle exception>
13316          *   <access okay>
13317          *
13318          *   r2 = r3;
13319          *   r2 += 8;
13320          *   if (r2 < pkt_end) goto <access okay>
13321          *   <handle exception>
13322          *
13323          *   Where:
13324          *     r2 == dst_reg, pkt_end == src_reg
13325          *     r2=pkt(id=n,off=8,r=0)
13326          *     r3=pkt(id=n,off=0,r=0)
13327          *
13328          * pkt_data in src register:
13329          *
13330          *   r2 = r3;
13331          *   r2 += 8;
13332          *   if (pkt_end >= r2) goto <access okay>
13333          *   <handle exception>
13334          *
13335          *   r2 = r3;
13336          *   r2 += 8;
13337          *   if (pkt_end <= r2) goto <handle exception>
13338          *   <access okay>
13339          *
13340          *   Where:
13341          *     pkt_end == dst_reg, r2 == src_reg
13342          *     r2=pkt(id=n,off=8,r=0)
13343          *     r3=pkt(id=n,off=0,r=0)
13344          *
13345          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13346          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13347          * and [r3, r3 + 8-1) respectively is safe to access depending on
13348          * the check.
13349          */
13350
13351         /* If our ids match, then we must have the same max_value.  And we
13352          * don't care about the other reg's fixed offset, since if it's too big
13353          * the range won't allow anything.
13354          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13355          */
13356         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13357                 if (reg->type == type && reg->id == dst_reg->id)
13358                         /* keep the maximum range already checked */
13359                         reg->range = max(reg->range, new_range);
13360         }));
13361 }
13362
13363 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13364 {
13365         struct tnum subreg = tnum_subreg(reg->var_off);
13366         s32 sval = (s32)val;
13367
13368         switch (opcode) {
13369         case BPF_JEQ:
13370                 if (tnum_is_const(subreg))
13371                         return !!tnum_equals_const(subreg, val);
13372                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13373                         return 0;
13374                 break;
13375         case BPF_JNE:
13376                 if (tnum_is_const(subreg))
13377                         return !tnum_equals_const(subreg, val);
13378                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13379                         return 1;
13380                 break;
13381         case BPF_JSET:
13382                 if ((~subreg.mask & subreg.value) & val)
13383                         return 1;
13384                 if (!((subreg.mask | subreg.value) & val))
13385                         return 0;
13386                 break;
13387         case BPF_JGT:
13388                 if (reg->u32_min_value > val)
13389                         return 1;
13390                 else if (reg->u32_max_value <= val)
13391                         return 0;
13392                 break;
13393         case BPF_JSGT:
13394                 if (reg->s32_min_value > sval)
13395                         return 1;
13396                 else if (reg->s32_max_value <= sval)
13397                         return 0;
13398                 break;
13399         case BPF_JLT:
13400                 if (reg->u32_max_value < val)
13401                         return 1;
13402                 else if (reg->u32_min_value >= val)
13403                         return 0;
13404                 break;
13405         case BPF_JSLT:
13406                 if (reg->s32_max_value < sval)
13407                         return 1;
13408                 else if (reg->s32_min_value >= sval)
13409                         return 0;
13410                 break;
13411         case BPF_JGE:
13412                 if (reg->u32_min_value >= val)
13413                         return 1;
13414                 else if (reg->u32_max_value < val)
13415                         return 0;
13416                 break;
13417         case BPF_JSGE:
13418                 if (reg->s32_min_value >= sval)
13419                         return 1;
13420                 else if (reg->s32_max_value < sval)
13421                         return 0;
13422                 break;
13423         case BPF_JLE:
13424                 if (reg->u32_max_value <= val)
13425                         return 1;
13426                 else if (reg->u32_min_value > val)
13427                         return 0;
13428                 break;
13429         case BPF_JSLE:
13430                 if (reg->s32_max_value <= sval)
13431                         return 1;
13432                 else if (reg->s32_min_value > sval)
13433                         return 0;
13434                 break;
13435         }
13436
13437         return -1;
13438 }
13439
13440
13441 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13442 {
13443         s64 sval = (s64)val;
13444
13445         switch (opcode) {
13446         case BPF_JEQ:
13447                 if (tnum_is_const(reg->var_off))
13448                         return !!tnum_equals_const(reg->var_off, val);
13449                 else if (val < reg->umin_value || val > reg->umax_value)
13450                         return 0;
13451                 break;
13452         case BPF_JNE:
13453                 if (tnum_is_const(reg->var_off))
13454                         return !tnum_equals_const(reg->var_off, val);
13455                 else if (val < reg->umin_value || val > reg->umax_value)
13456                         return 1;
13457                 break;
13458         case BPF_JSET:
13459                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13460                         return 1;
13461                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13462                         return 0;
13463                 break;
13464         case BPF_JGT:
13465                 if (reg->umin_value > val)
13466                         return 1;
13467                 else if (reg->umax_value <= val)
13468                         return 0;
13469                 break;
13470         case BPF_JSGT:
13471                 if (reg->smin_value > sval)
13472                         return 1;
13473                 else if (reg->smax_value <= sval)
13474                         return 0;
13475                 break;
13476         case BPF_JLT:
13477                 if (reg->umax_value < val)
13478                         return 1;
13479                 else if (reg->umin_value >= val)
13480                         return 0;
13481                 break;
13482         case BPF_JSLT:
13483                 if (reg->smax_value < sval)
13484                         return 1;
13485                 else if (reg->smin_value >= sval)
13486                         return 0;
13487                 break;
13488         case BPF_JGE:
13489                 if (reg->umin_value >= val)
13490                         return 1;
13491                 else if (reg->umax_value < val)
13492                         return 0;
13493                 break;
13494         case BPF_JSGE:
13495                 if (reg->smin_value >= sval)
13496                         return 1;
13497                 else if (reg->smax_value < sval)
13498                         return 0;
13499                 break;
13500         case BPF_JLE:
13501                 if (reg->umax_value <= val)
13502                         return 1;
13503                 else if (reg->umin_value > val)
13504                         return 0;
13505                 break;
13506         case BPF_JSLE:
13507                 if (reg->smax_value <= sval)
13508                         return 1;
13509                 else if (reg->smin_value > sval)
13510                         return 0;
13511                 break;
13512         }
13513
13514         return -1;
13515 }
13516
13517 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13518  * and return:
13519  *  1 - branch will be taken and "goto target" will be executed
13520  *  0 - branch will not be taken and fall-through to next insn
13521  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13522  *      range [0,10]
13523  */
13524 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13525                            bool is_jmp32)
13526 {
13527         if (__is_pointer_value(false, reg)) {
13528                 if (!reg_not_null(reg))
13529                         return -1;
13530
13531                 /* If pointer is valid tests against zero will fail so we can
13532                  * use this to direct branch taken.
13533                  */
13534                 if (val != 0)
13535                         return -1;
13536
13537                 switch (opcode) {
13538                 case BPF_JEQ:
13539                         return 0;
13540                 case BPF_JNE:
13541                         return 1;
13542                 default:
13543                         return -1;
13544                 }
13545         }
13546
13547         if (is_jmp32)
13548                 return is_branch32_taken(reg, val, opcode);
13549         return is_branch64_taken(reg, val, opcode);
13550 }
13551
13552 static int flip_opcode(u32 opcode)
13553 {
13554         /* How can we transform "a <op> b" into "b <op> a"? */
13555         static const u8 opcode_flip[16] = {
13556                 /* these stay the same */
13557                 [BPF_JEQ  >> 4] = BPF_JEQ,
13558                 [BPF_JNE  >> 4] = BPF_JNE,
13559                 [BPF_JSET >> 4] = BPF_JSET,
13560                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13561                 [BPF_JGE  >> 4] = BPF_JLE,
13562                 [BPF_JGT  >> 4] = BPF_JLT,
13563                 [BPF_JLE  >> 4] = BPF_JGE,
13564                 [BPF_JLT  >> 4] = BPF_JGT,
13565                 [BPF_JSGE >> 4] = BPF_JSLE,
13566                 [BPF_JSGT >> 4] = BPF_JSLT,
13567                 [BPF_JSLE >> 4] = BPF_JSGE,
13568                 [BPF_JSLT >> 4] = BPF_JSGT
13569         };
13570         return opcode_flip[opcode >> 4];
13571 }
13572
13573 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13574                                    struct bpf_reg_state *src_reg,
13575                                    u8 opcode)
13576 {
13577         struct bpf_reg_state *pkt;
13578
13579         if (src_reg->type == PTR_TO_PACKET_END) {
13580                 pkt = dst_reg;
13581         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13582                 pkt = src_reg;
13583                 opcode = flip_opcode(opcode);
13584         } else {
13585                 return -1;
13586         }
13587
13588         if (pkt->range >= 0)
13589                 return -1;
13590
13591         switch (opcode) {
13592         case BPF_JLE:
13593                 /* pkt <= pkt_end */
13594                 fallthrough;
13595         case BPF_JGT:
13596                 /* pkt > pkt_end */
13597                 if (pkt->range == BEYOND_PKT_END)
13598                         /* pkt has at last one extra byte beyond pkt_end */
13599                         return opcode == BPF_JGT;
13600                 break;
13601         case BPF_JLT:
13602                 /* pkt < pkt_end */
13603                 fallthrough;
13604         case BPF_JGE:
13605                 /* pkt >= pkt_end */
13606                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13607                         return opcode == BPF_JGE;
13608                 break;
13609         }
13610         return -1;
13611 }
13612
13613 /* Adjusts the register min/max values in the case that the dst_reg is the
13614  * variable register that we are working on, and src_reg is a constant or we're
13615  * simply doing a BPF_K check.
13616  * In JEQ/JNE cases we also adjust the var_off values.
13617  */
13618 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13619                             struct bpf_reg_state *false_reg,
13620                             u64 val, u32 val32,
13621                             u8 opcode, bool is_jmp32)
13622 {
13623         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13624         struct tnum false_64off = false_reg->var_off;
13625         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13626         struct tnum true_64off = true_reg->var_off;
13627         s64 sval = (s64)val;
13628         s32 sval32 = (s32)val32;
13629
13630         /* If the dst_reg is a pointer, we can't learn anything about its
13631          * variable offset from the compare (unless src_reg were a pointer into
13632          * the same object, but we don't bother with that.
13633          * Since false_reg and true_reg have the same type by construction, we
13634          * only need to check one of them for pointerness.
13635          */
13636         if (__is_pointer_value(false, false_reg))
13637                 return;
13638
13639         switch (opcode) {
13640         /* JEQ/JNE comparison doesn't change the register equivalence.
13641          *
13642          * r1 = r2;
13643          * if (r1 == 42) goto label;
13644          * ...
13645          * label: // here both r1 and r2 are known to be 42.
13646          *
13647          * Hence when marking register as known preserve it's ID.
13648          */
13649         case BPF_JEQ:
13650                 if (is_jmp32) {
13651                         __mark_reg32_known(true_reg, val32);
13652                         true_32off = tnum_subreg(true_reg->var_off);
13653                 } else {
13654                         ___mark_reg_known(true_reg, val);
13655                         true_64off = true_reg->var_off;
13656                 }
13657                 break;
13658         case BPF_JNE:
13659                 if (is_jmp32) {
13660                         __mark_reg32_known(false_reg, val32);
13661                         false_32off = tnum_subreg(false_reg->var_off);
13662                 } else {
13663                         ___mark_reg_known(false_reg, val);
13664                         false_64off = false_reg->var_off;
13665                 }
13666                 break;
13667         case BPF_JSET:
13668                 if (is_jmp32) {
13669                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13670                         if (is_power_of_2(val32))
13671                                 true_32off = tnum_or(true_32off,
13672                                                      tnum_const(val32));
13673                 } else {
13674                         false_64off = tnum_and(false_64off, tnum_const(~val));
13675                         if (is_power_of_2(val))
13676                                 true_64off = tnum_or(true_64off,
13677                                                      tnum_const(val));
13678                 }
13679                 break;
13680         case BPF_JGE:
13681         case BPF_JGT:
13682         {
13683                 if (is_jmp32) {
13684                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13685                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13686
13687                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13688                                                        false_umax);
13689                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13690                                                       true_umin);
13691                 } else {
13692                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13693                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13694
13695                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13696                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13697                 }
13698                 break;
13699         }
13700         case BPF_JSGE:
13701         case BPF_JSGT:
13702         {
13703                 if (is_jmp32) {
13704                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13705                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13706
13707                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13708                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13709                 } else {
13710                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13711                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13712
13713                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13714                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13715                 }
13716                 break;
13717         }
13718         case BPF_JLE:
13719         case BPF_JLT:
13720         {
13721                 if (is_jmp32) {
13722                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13723                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13724
13725                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13726                                                        false_umin);
13727                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13728                                                       true_umax);
13729                 } else {
13730                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13731                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13732
13733                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13734                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13735                 }
13736                 break;
13737         }
13738         case BPF_JSLE:
13739         case BPF_JSLT:
13740         {
13741                 if (is_jmp32) {
13742                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13743                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13744
13745                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13746                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13747                 } else {
13748                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13749                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13750
13751                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13752                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13753                 }
13754                 break;
13755         }
13756         default:
13757                 return;
13758         }
13759
13760         if (is_jmp32) {
13761                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13762                                              tnum_subreg(false_32off));
13763                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13764                                             tnum_subreg(true_32off));
13765                 __reg_combine_32_into_64(false_reg);
13766                 __reg_combine_32_into_64(true_reg);
13767         } else {
13768                 false_reg->var_off = false_64off;
13769                 true_reg->var_off = true_64off;
13770                 __reg_combine_64_into_32(false_reg);
13771                 __reg_combine_64_into_32(true_reg);
13772         }
13773 }
13774
13775 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13776  * the variable reg.
13777  */
13778 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13779                                 struct bpf_reg_state *false_reg,
13780                                 u64 val, u32 val32,
13781                                 u8 opcode, bool is_jmp32)
13782 {
13783         opcode = flip_opcode(opcode);
13784         /* This uses zero as "not present in table"; luckily the zero opcode,
13785          * BPF_JA, can't get here.
13786          */
13787         if (opcode)
13788                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13789 }
13790
13791 /* Regs are known to be equal, so intersect their min/max/var_off */
13792 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13793                                   struct bpf_reg_state *dst_reg)
13794 {
13795         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13796                                                         dst_reg->umin_value);
13797         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13798                                                         dst_reg->umax_value);
13799         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13800                                                         dst_reg->smin_value);
13801         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13802                                                         dst_reg->smax_value);
13803         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13804                                                              dst_reg->var_off);
13805         reg_bounds_sync(src_reg);
13806         reg_bounds_sync(dst_reg);
13807 }
13808
13809 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13810                                 struct bpf_reg_state *true_dst,
13811                                 struct bpf_reg_state *false_src,
13812                                 struct bpf_reg_state *false_dst,
13813                                 u8 opcode)
13814 {
13815         switch (opcode) {
13816         case BPF_JEQ:
13817                 __reg_combine_min_max(true_src, true_dst);
13818                 break;
13819         case BPF_JNE:
13820                 __reg_combine_min_max(false_src, false_dst);
13821                 break;
13822         }
13823 }
13824
13825 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13826                                  struct bpf_reg_state *reg, u32 id,
13827                                  bool is_null)
13828 {
13829         if (type_may_be_null(reg->type) && reg->id == id &&
13830             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13831                 /* Old offset (both fixed and variable parts) should have been
13832                  * known-zero, because we don't allow pointer arithmetic on
13833                  * pointers that might be NULL. If we see this happening, don't
13834                  * convert the register.
13835                  *
13836                  * But in some cases, some helpers that return local kptrs
13837                  * advance offset for the returned pointer. In those cases, it
13838                  * is fine to expect to see reg->off.
13839                  */
13840                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13841                         return;
13842                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13843                     WARN_ON_ONCE(reg->off))
13844                         return;
13845
13846                 if (is_null) {
13847                         reg->type = SCALAR_VALUE;
13848                         /* We don't need id and ref_obj_id from this point
13849                          * onwards anymore, thus we should better reset it,
13850                          * so that state pruning has chances to take effect.
13851                          */
13852                         reg->id = 0;
13853                         reg->ref_obj_id = 0;
13854
13855                         return;
13856                 }
13857
13858                 mark_ptr_not_null_reg(reg);
13859
13860                 if (!reg_may_point_to_spin_lock(reg)) {
13861                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13862                          * in release_reference().
13863                          *
13864                          * reg->id is still used by spin_lock ptr. Other
13865                          * than spin_lock ptr type, reg->id can be reset.
13866                          */
13867                         reg->id = 0;
13868                 }
13869         }
13870 }
13871
13872 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13873  * be folded together at some point.
13874  */
13875 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13876                                   bool is_null)
13877 {
13878         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13879         struct bpf_reg_state *regs = state->regs, *reg;
13880         u32 ref_obj_id = regs[regno].ref_obj_id;
13881         u32 id = regs[regno].id;
13882
13883         if (ref_obj_id && ref_obj_id == id && is_null)
13884                 /* regs[regno] is in the " == NULL" branch.
13885                  * No one could have freed the reference state before
13886                  * doing the NULL check.
13887                  */
13888                 WARN_ON_ONCE(release_reference_state(state, id));
13889
13890         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13891                 mark_ptr_or_null_reg(state, reg, id, is_null);
13892         }));
13893 }
13894
13895 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13896                                    struct bpf_reg_state *dst_reg,
13897                                    struct bpf_reg_state *src_reg,
13898                                    struct bpf_verifier_state *this_branch,
13899                                    struct bpf_verifier_state *other_branch)
13900 {
13901         if (BPF_SRC(insn->code) != BPF_X)
13902                 return false;
13903
13904         /* Pointers are always 64-bit. */
13905         if (BPF_CLASS(insn->code) == BPF_JMP32)
13906                 return false;
13907
13908         switch (BPF_OP(insn->code)) {
13909         case BPF_JGT:
13910                 if ((dst_reg->type == PTR_TO_PACKET &&
13911                      src_reg->type == PTR_TO_PACKET_END) ||
13912                     (dst_reg->type == PTR_TO_PACKET_META &&
13913                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13914                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13915                         find_good_pkt_pointers(this_branch, dst_reg,
13916                                                dst_reg->type, false);
13917                         mark_pkt_end(other_branch, insn->dst_reg, true);
13918                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13919                             src_reg->type == PTR_TO_PACKET) ||
13920                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13921                             src_reg->type == PTR_TO_PACKET_META)) {
13922                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13923                         find_good_pkt_pointers(other_branch, src_reg,
13924                                                src_reg->type, true);
13925                         mark_pkt_end(this_branch, insn->src_reg, false);
13926                 } else {
13927                         return false;
13928                 }
13929                 break;
13930         case BPF_JLT:
13931                 if ((dst_reg->type == PTR_TO_PACKET &&
13932                      src_reg->type == PTR_TO_PACKET_END) ||
13933                     (dst_reg->type == PTR_TO_PACKET_META &&
13934                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13935                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13936                         find_good_pkt_pointers(other_branch, dst_reg,
13937                                                dst_reg->type, true);
13938                         mark_pkt_end(this_branch, insn->dst_reg, false);
13939                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13940                             src_reg->type == PTR_TO_PACKET) ||
13941                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13942                             src_reg->type == PTR_TO_PACKET_META)) {
13943                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13944                         find_good_pkt_pointers(this_branch, src_reg,
13945                                                src_reg->type, false);
13946                         mark_pkt_end(other_branch, insn->src_reg, true);
13947                 } else {
13948                         return false;
13949                 }
13950                 break;
13951         case BPF_JGE:
13952                 if ((dst_reg->type == PTR_TO_PACKET &&
13953                      src_reg->type == PTR_TO_PACKET_END) ||
13954                     (dst_reg->type == PTR_TO_PACKET_META &&
13955                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13956                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
13957                         find_good_pkt_pointers(this_branch, dst_reg,
13958                                                dst_reg->type, true);
13959                         mark_pkt_end(other_branch, insn->dst_reg, false);
13960                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13961                             src_reg->type == PTR_TO_PACKET) ||
13962                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13963                             src_reg->type == PTR_TO_PACKET_META)) {
13964                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
13965                         find_good_pkt_pointers(other_branch, src_reg,
13966                                                src_reg->type, false);
13967                         mark_pkt_end(this_branch, insn->src_reg, true);
13968                 } else {
13969                         return false;
13970                 }
13971                 break;
13972         case BPF_JLE:
13973                 if ((dst_reg->type == PTR_TO_PACKET &&
13974                      src_reg->type == PTR_TO_PACKET_END) ||
13975                     (dst_reg->type == PTR_TO_PACKET_META &&
13976                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13977                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
13978                         find_good_pkt_pointers(other_branch, dst_reg,
13979                                                dst_reg->type, false);
13980                         mark_pkt_end(this_branch, insn->dst_reg, true);
13981                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13982                             src_reg->type == PTR_TO_PACKET) ||
13983                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13984                             src_reg->type == PTR_TO_PACKET_META)) {
13985                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
13986                         find_good_pkt_pointers(this_branch, src_reg,
13987                                                src_reg->type, true);
13988                         mark_pkt_end(other_branch, insn->src_reg, false);
13989                 } else {
13990                         return false;
13991                 }
13992                 break;
13993         default:
13994                 return false;
13995         }
13996
13997         return true;
13998 }
13999
14000 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14001                                struct bpf_reg_state *known_reg)
14002 {
14003         struct bpf_func_state *state;
14004         struct bpf_reg_state *reg;
14005
14006         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14007                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14008                         copy_register_state(reg, known_reg);
14009         }));
14010 }
14011
14012 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14013                              struct bpf_insn *insn, int *insn_idx)
14014 {
14015         struct bpf_verifier_state *this_branch = env->cur_state;
14016         struct bpf_verifier_state *other_branch;
14017         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14018         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14019         struct bpf_reg_state *eq_branch_regs;
14020         u8 opcode = BPF_OP(insn->code);
14021         bool is_jmp32;
14022         int pred = -1;
14023         int err;
14024
14025         /* Only conditional jumps are expected to reach here. */
14026         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14027                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14028                 return -EINVAL;
14029         }
14030
14031         if (BPF_SRC(insn->code) == BPF_X) {
14032                 if (insn->imm != 0) {
14033                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14034                         return -EINVAL;
14035                 }
14036
14037                 /* check src1 operand */
14038                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14039                 if (err)
14040                         return err;
14041
14042                 if (is_pointer_value(env, insn->src_reg)) {
14043                         verbose(env, "R%d pointer comparison prohibited\n",
14044                                 insn->src_reg);
14045                         return -EACCES;
14046                 }
14047                 src_reg = &regs[insn->src_reg];
14048         } else {
14049                 if (insn->src_reg != BPF_REG_0) {
14050                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14051                         return -EINVAL;
14052                 }
14053         }
14054
14055         /* check src2 operand */
14056         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14057         if (err)
14058                 return err;
14059
14060         dst_reg = &regs[insn->dst_reg];
14061         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14062
14063         if (BPF_SRC(insn->code) == BPF_K) {
14064                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14065         } else if (src_reg->type == SCALAR_VALUE &&
14066                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14067                 pred = is_branch_taken(dst_reg,
14068                                        tnum_subreg(src_reg->var_off).value,
14069                                        opcode,
14070                                        is_jmp32);
14071         } else if (src_reg->type == SCALAR_VALUE &&
14072                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14073                 pred = is_branch_taken(dst_reg,
14074                                        src_reg->var_off.value,
14075                                        opcode,
14076                                        is_jmp32);
14077         } else if (dst_reg->type == SCALAR_VALUE &&
14078                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14079                 pred = is_branch_taken(src_reg,
14080                                        tnum_subreg(dst_reg->var_off).value,
14081                                        flip_opcode(opcode),
14082                                        is_jmp32);
14083         } else if (dst_reg->type == SCALAR_VALUE &&
14084                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14085                 pred = is_branch_taken(src_reg,
14086                                        dst_reg->var_off.value,
14087                                        flip_opcode(opcode),
14088                                        is_jmp32);
14089         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14090                    reg_is_pkt_pointer_any(src_reg) &&
14091                    !is_jmp32) {
14092                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14093         }
14094
14095         if (pred >= 0) {
14096                 /* If we get here with a dst_reg pointer type it is because
14097                  * above is_branch_taken() special cased the 0 comparison.
14098                  */
14099                 if (!__is_pointer_value(false, dst_reg))
14100                         err = mark_chain_precision(env, insn->dst_reg);
14101                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14102                     !__is_pointer_value(false, src_reg))
14103                         err = mark_chain_precision(env, insn->src_reg);
14104                 if (err)
14105                         return err;
14106         }
14107
14108         if (pred == 1) {
14109                 /* Only follow the goto, ignore fall-through. If needed, push
14110                  * the fall-through branch for simulation under speculative
14111                  * execution.
14112                  */
14113                 if (!env->bypass_spec_v1 &&
14114                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14115                                                *insn_idx))
14116                         return -EFAULT;
14117                 *insn_idx += insn->off;
14118                 return 0;
14119         } else if (pred == 0) {
14120                 /* Only follow the fall-through branch, since that's where the
14121                  * program will go. If needed, push the goto branch for
14122                  * simulation under speculative execution.
14123                  */
14124                 if (!env->bypass_spec_v1 &&
14125                     !sanitize_speculative_path(env, insn,
14126                                                *insn_idx + insn->off + 1,
14127                                                *insn_idx))
14128                         return -EFAULT;
14129                 return 0;
14130         }
14131
14132         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14133                                   false);
14134         if (!other_branch)
14135                 return -EFAULT;
14136         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14137
14138         /* detect if we are comparing against a constant value so we can adjust
14139          * our min/max values for our dst register.
14140          * this is only legit if both are scalars (or pointers to the same
14141          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14142          * because otherwise the different base pointers mean the offsets aren't
14143          * comparable.
14144          */
14145         if (BPF_SRC(insn->code) == BPF_X) {
14146                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14147
14148                 if (dst_reg->type == SCALAR_VALUE &&
14149                     src_reg->type == SCALAR_VALUE) {
14150                         if (tnum_is_const(src_reg->var_off) ||
14151                             (is_jmp32 &&
14152                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14153                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14154                                                 dst_reg,
14155                                                 src_reg->var_off.value,
14156                                                 tnum_subreg(src_reg->var_off).value,
14157                                                 opcode, is_jmp32);
14158                         else if (tnum_is_const(dst_reg->var_off) ||
14159                                  (is_jmp32 &&
14160                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14161                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14162                                                     src_reg,
14163                                                     dst_reg->var_off.value,
14164                                                     tnum_subreg(dst_reg->var_off).value,
14165                                                     opcode, is_jmp32);
14166                         else if (!is_jmp32 &&
14167                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14168                                 /* Comparing for equality, we can combine knowledge */
14169                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14170                                                     &other_branch_regs[insn->dst_reg],
14171                                                     src_reg, dst_reg, opcode);
14172                         if (src_reg->id &&
14173                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14174                                 find_equal_scalars(this_branch, src_reg);
14175                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14176                         }
14177
14178                 }
14179         } else if (dst_reg->type == SCALAR_VALUE) {
14180                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14181                                         dst_reg, insn->imm, (u32)insn->imm,
14182                                         opcode, is_jmp32);
14183         }
14184
14185         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14186             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14187                 find_equal_scalars(this_branch, dst_reg);
14188                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14189         }
14190
14191         /* if one pointer register is compared to another pointer
14192          * register check if PTR_MAYBE_NULL could be lifted.
14193          * E.g. register A - maybe null
14194          *      register B - not null
14195          * for JNE A, B, ... - A is not null in the false branch;
14196          * for JEQ A, B, ... - A is not null in the true branch.
14197          *
14198          * Since PTR_TO_BTF_ID points to a kernel struct that does
14199          * not need to be null checked by the BPF program, i.e.,
14200          * could be null even without PTR_MAYBE_NULL marking, so
14201          * only propagate nullness when neither reg is that type.
14202          */
14203         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14204             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14205             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14206             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14207             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14208                 eq_branch_regs = NULL;
14209                 switch (opcode) {
14210                 case BPF_JEQ:
14211                         eq_branch_regs = other_branch_regs;
14212                         break;
14213                 case BPF_JNE:
14214                         eq_branch_regs = regs;
14215                         break;
14216                 default:
14217                         /* do nothing */
14218                         break;
14219                 }
14220                 if (eq_branch_regs) {
14221                         if (type_may_be_null(src_reg->type))
14222                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14223                         else
14224                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14225                 }
14226         }
14227
14228         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14229          * NOTE: these optimizations below are related with pointer comparison
14230          *       which will never be JMP32.
14231          */
14232         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14233             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14234             type_may_be_null(dst_reg->type)) {
14235                 /* Mark all identical registers in each branch as either
14236                  * safe or unknown depending R == 0 or R != 0 conditional.
14237                  */
14238                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14239                                       opcode == BPF_JNE);
14240                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14241                                       opcode == BPF_JEQ);
14242         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14243                                            this_branch, other_branch) &&
14244                    is_pointer_value(env, insn->dst_reg)) {
14245                 verbose(env, "R%d pointer comparison prohibited\n",
14246                         insn->dst_reg);
14247                 return -EACCES;
14248         }
14249         if (env->log.level & BPF_LOG_LEVEL)
14250                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14251         return 0;
14252 }
14253
14254 /* verify BPF_LD_IMM64 instruction */
14255 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14256 {
14257         struct bpf_insn_aux_data *aux = cur_aux(env);
14258         struct bpf_reg_state *regs = cur_regs(env);
14259         struct bpf_reg_state *dst_reg;
14260         struct bpf_map *map;
14261         int err;
14262
14263         if (BPF_SIZE(insn->code) != BPF_DW) {
14264                 verbose(env, "invalid BPF_LD_IMM insn\n");
14265                 return -EINVAL;
14266         }
14267         if (insn->off != 0) {
14268                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14269                 return -EINVAL;
14270         }
14271
14272         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14273         if (err)
14274                 return err;
14275
14276         dst_reg = &regs[insn->dst_reg];
14277         if (insn->src_reg == 0) {
14278                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14279
14280                 dst_reg->type = SCALAR_VALUE;
14281                 __mark_reg_known(&regs[insn->dst_reg], imm);
14282                 return 0;
14283         }
14284
14285         /* All special src_reg cases are listed below. From this point onwards
14286          * we either succeed and assign a corresponding dst_reg->type after
14287          * zeroing the offset, or fail and reject the program.
14288          */
14289         mark_reg_known_zero(env, regs, insn->dst_reg);
14290
14291         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14292                 dst_reg->type = aux->btf_var.reg_type;
14293                 switch (base_type(dst_reg->type)) {
14294                 case PTR_TO_MEM:
14295                         dst_reg->mem_size = aux->btf_var.mem_size;
14296                         break;
14297                 case PTR_TO_BTF_ID:
14298                         dst_reg->btf = aux->btf_var.btf;
14299                         dst_reg->btf_id = aux->btf_var.btf_id;
14300                         break;
14301                 default:
14302                         verbose(env, "bpf verifier is misconfigured\n");
14303                         return -EFAULT;
14304                 }
14305                 return 0;
14306         }
14307
14308         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14309                 struct bpf_prog_aux *aux = env->prog->aux;
14310                 u32 subprogno = find_subprog(env,
14311                                              env->insn_idx + insn->imm + 1);
14312
14313                 if (!aux->func_info) {
14314                         verbose(env, "missing btf func_info\n");
14315                         return -EINVAL;
14316                 }
14317                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14318                         verbose(env, "callback function not static\n");
14319                         return -EINVAL;
14320                 }
14321
14322                 dst_reg->type = PTR_TO_FUNC;
14323                 dst_reg->subprogno = subprogno;
14324                 return 0;
14325         }
14326
14327         map = env->used_maps[aux->map_index];
14328         dst_reg->map_ptr = map;
14329
14330         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14331             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14332                 dst_reg->type = PTR_TO_MAP_VALUE;
14333                 dst_reg->off = aux->map_off;
14334                 WARN_ON_ONCE(map->max_entries != 1);
14335                 /* We want reg->id to be same (0) as map_value is not distinct */
14336         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14337                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14338                 dst_reg->type = CONST_PTR_TO_MAP;
14339         } else {
14340                 verbose(env, "bpf verifier is misconfigured\n");
14341                 return -EINVAL;
14342         }
14343
14344         return 0;
14345 }
14346
14347 static bool may_access_skb(enum bpf_prog_type type)
14348 {
14349         switch (type) {
14350         case BPF_PROG_TYPE_SOCKET_FILTER:
14351         case BPF_PROG_TYPE_SCHED_CLS:
14352         case BPF_PROG_TYPE_SCHED_ACT:
14353                 return true;
14354         default:
14355                 return false;
14356         }
14357 }
14358
14359 /* verify safety of LD_ABS|LD_IND instructions:
14360  * - they can only appear in the programs where ctx == skb
14361  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14362  *   preserve R6-R9, and store return value into R0
14363  *
14364  * Implicit input:
14365  *   ctx == skb == R6 == CTX
14366  *
14367  * Explicit input:
14368  *   SRC == any register
14369  *   IMM == 32-bit immediate
14370  *
14371  * Output:
14372  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14373  */
14374 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14375 {
14376         struct bpf_reg_state *regs = cur_regs(env);
14377         static const int ctx_reg = BPF_REG_6;
14378         u8 mode = BPF_MODE(insn->code);
14379         int i, err;
14380
14381         if (!may_access_skb(resolve_prog_type(env->prog))) {
14382                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14383                 return -EINVAL;
14384         }
14385
14386         if (!env->ops->gen_ld_abs) {
14387                 verbose(env, "bpf verifier is misconfigured\n");
14388                 return -EINVAL;
14389         }
14390
14391         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14392             BPF_SIZE(insn->code) == BPF_DW ||
14393             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14394                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14395                 return -EINVAL;
14396         }
14397
14398         /* check whether implicit source operand (register R6) is readable */
14399         err = check_reg_arg(env, ctx_reg, SRC_OP);
14400         if (err)
14401                 return err;
14402
14403         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14404          * gen_ld_abs() may terminate the program at runtime, leading to
14405          * reference leak.
14406          */
14407         err = check_reference_leak(env);
14408         if (err) {
14409                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14410                 return err;
14411         }
14412
14413         if (env->cur_state->active_lock.ptr) {
14414                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14415                 return -EINVAL;
14416         }
14417
14418         if (env->cur_state->active_rcu_lock) {
14419                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14420                 return -EINVAL;
14421         }
14422
14423         if (regs[ctx_reg].type != PTR_TO_CTX) {
14424                 verbose(env,
14425                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14426                 return -EINVAL;
14427         }
14428
14429         if (mode == BPF_IND) {
14430                 /* check explicit source operand */
14431                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14432                 if (err)
14433                         return err;
14434         }
14435
14436         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14437         if (err < 0)
14438                 return err;
14439
14440         /* reset caller saved regs to unreadable */
14441         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14442                 mark_reg_not_init(env, regs, caller_saved[i]);
14443                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14444         }
14445
14446         /* mark destination R0 register as readable, since it contains
14447          * the value fetched from the packet.
14448          * Already marked as written above.
14449          */
14450         mark_reg_unknown(env, regs, BPF_REG_0);
14451         /* ld_abs load up to 32-bit skb data. */
14452         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14453         return 0;
14454 }
14455
14456 static int check_return_code(struct bpf_verifier_env *env)
14457 {
14458         struct tnum enforce_attach_type_range = tnum_unknown;
14459         const struct bpf_prog *prog = env->prog;
14460         struct bpf_reg_state *reg;
14461         struct tnum range = tnum_range(0, 1);
14462         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14463         int err;
14464         struct bpf_func_state *frame = env->cur_state->frame[0];
14465         const bool is_subprog = frame->subprogno;
14466
14467         /* LSM and struct_ops func-ptr's return type could be "void" */
14468         if (!is_subprog) {
14469                 switch (prog_type) {
14470                 case BPF_PROG_TYPE_LSM:
14471                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14472                                 /* See below, can be 0 or 0-1 depending on hook. */
14473                                 break;
14474                         fallthrough;
14475                 case BPF_PROG_TYPE_STRUCT_OPS:
14476                         if (!prog->aux->attach_func_proto->type)
14477                                 return 0;
14478                         break;
14479                 default:
14480                         break;
14481                 }
14482         }
14483
14484         /* eBPF calling convention is such that R0 is used
14485          * to return the value from eBPF program.
14486          * Make sure that it's readable at this time
14487          * of bpf_exit, which means that program wrote
14488          * something into it earlier
14489          */
14490         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14491         if (err)
14492                 return err;
14493
14494         if (is_pointer_value(env, BPF_REG_0)) {
14495                 verbose(env, "R0 leaks addr as return value\n");
14496                 return -EACCES;
14497         }
14498
14499         reg = cur_regs(env) + BPF_REG_0;
14500
14501         if (frame->in_async_callback_fn) {
14502                 /* enforce return zero from async callbacks like timer */
14503                 if (reg->type != SCALAR_VALUE) {
14504                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14505                                 reg_type_str(env, reg->type));
14506                         return -EINVAL;
14507                 }
14508
14509                 if (!tnum_in(tnum_const(0), reg->var_off)) {
14510                         verbose_invalid_scalar(env, reg, &range, "async callback", "R0");
14511                         return -EINVAL;
14512                 }
14513                 return 0;
14514         }
14515
14516         if (is_subprog) {
14517                 if (reg->type != SCALAR_VALUE) {
14518                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14519                                 reg_type_str(env, reg->type));
14520                         return -EINVAL;
14521                 }
14522                 return 0;
14523         }
14524
14525         switch (prog_type) {
14526         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14527                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14528                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14529                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14530                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14531                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14532                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14533                         range = tnum_range(1, 1);
14534                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14535                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14536                         range = tnum_range(0, 3);
14537                 break;
14538         case BPF_PROG_TYPE_CGROUP_SKB:
14539                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14540                         range = tnum_range(0, 3);
14541                         enforce_attach_type_range = tnum_range(2, 3);
14542                 }
14543                 break;
14544         case BPF_PROG_TYPE_CGROUP_SOCK:
14545         case BPF_PROG_TYPE_SOCK_OPS:
14546         case BPF_PROG_TYPE_CGROUP_DEVICE:
14547         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14548         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14549                 break;
14550         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14551                 if (!env->prog->aux->attach_btf_id)
14552                         return 0;
14553                 range = tnum_const(0);
14554                 break;
14555         case BPF_PROG_TYPE_TRACING:
14556                 switch (env->prog->expected_attach_type) {
14557                 case BPF_TRACE_FENTRY:
14558                 case BPF_TRACE_FEXIT:
14559                         range = tnum_const(0);
14560                         break;
14561                 case BPF_TRACE_RAW_TP:
14562                 case BPF_MODIFY_RETURN:
14563                         return 0;
14564                 case BPF_TRACE_ITER:
14565                         break;
14566                 default:
14567                         return -ENOTSUPP;
14568                 }
14569                 break;
14570         case BPF_PROG_TYPE_SK_LOOKUP:
14571                 range = tnum_range(SK_DROP, SK_PASS);
14572                 break;
14573
14574         case BPF_PROG_TYPE_LSM:
14575                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14576                         /* Regular BPF_PROG_TYPE_LSM programs can return
14577                          * any value.
14578                          */
14579                         return 0;
14580                 }
14581                 if (!env->prog->aux->attach_func_proto->type) {
14582                         /* Make sure programs that attach to void
14583                          * hooks don't try to modify return value.
14584                          */
14585                         range = tnum_range(1, 1);
14586                 }
14587                 break;
14588
14589         case BPF_PROG_TYPE_NETFILTER:
14590                 range = tnum_range(NF_DROP, NF_ACCEPT);
14591                 break;
14592         case BPF_PROG_TYPE_EXT:
14593                 /* freplace program can return anything as its return value
14594                  * depends on the to-be-replaced kernel func or bpf program.
14595                  */
14596         default:
14597                 return 0;
14598         }
14599
14600         if (reg->type != SCALAR_VALUE) {
14601                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14602                         reg_type_str(env, reg->type));
14603                 return -EINVAL;
14604         }
14605
14606         if (!tnum_in(range, reg->var_off)) {
14607                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14608                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14609                     prog_type == BPF_PROG_TYPE_LSM &&
14610                     !prog->aux->attach_func_proto->type)
14611                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14612                 return -EINVAL;
14613         }
14614
14615         if (!tnum_is_unknown(enforce_attach_type_range) &&
14616             tnum_in(enforce_attach_type_range, reg->var_off))
14617                 env->prog->enforce_expected_attach_type = 1;
14618         return 0;
14619 }
14620
14621 /* non-recursive DFS pseudo code
14622  * 1  procedure DFS-iterative(G,v):
14623  * 2      label v as discovered
14624  * 3      let S be a stack
14625  * 4      S.push(v)
14626  * 5      while S is not empty
14627  * 6            t <- S.peek()
14628  * 7            if t is what we're looking for:
14629  * 8                return t
14630  * 9            for all edges e in G.adjacentEdges(t) do
14631  * 10               if edge e is already labelled
14632  * 11                   continue with the next edge
14633  * 12               w <- G.adjacentVertex(t,e)
14634  * 13               if vertex w is not discovered and not explored
14635  * 14                   label e as tree-edge
14636  * 15                   label w as discovered
14637  * 16                   S.push(w)
14638  * 17                   continue at 5
14639  * 18               else if vertex w is discovered
14640  * 19                   label e as back-edge
14641  * 20               else
14642  * 21                   // vertex w is explored
14643  * 22                   label e as forward- or cross-edge
14644  * 23           label t as explored
14645  * 24           S.pop()
14646  *
14647  * convention:
14648  * 0x10 - discovered
14649  * 0x11 - discovered and fall-through edge labelled
14650  * 0x12 - discovered and fall-through and branch edges labelled
14651  * 0x20 - explored
14652  */
14653
14654 enum {
14655         DISCOVERED = 0x10,
14656         EXPLORED = 0x20,
14657         FALLTHROUGH = 1,
14658         BRANCH = 2,
14659 };
14660
14661 static u32 state_htab_size(struct bpf_verifier_env *env)
14662 {
14663         return env->prog->len;
14664 }
14665
14666 static struct bpf_verifier_state_list **explored_state(
14667                                         struct bpf_verifier_env *env,
14668                                         int idx)
14669 {
14670         struct bpf_verifier_state *cur = env->cur_state;
14671         struct bpf_func_state *state = cur->frame[cur->curframe];
14672
14673         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14674 }
14675
14676 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14677 {
14678         env->insn_aux_data[idx].prune_point = true;
14679 }
14680
14681 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14682 {
14683         return env->insn_aux_data[insn_idx].prune_point;
14684 }
14685
14686 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14687 {
14688         env->insn_aux_data[idx].force_checkpoint = true;
14689 }
14690
14691 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14692 {
14693         return env->insn_aux_data[insn_idx].force_checkpoint;
14694 }
14695
14696
14697 enum {
14698         DONE_EXPLORING = 0,
14699         KEEP_EXPLORING = 1,
14700 };
14701
14702 /* t, w, e - match pseudo-code above:
14703  * t - index of current instruction
14704  * w - next instruction
14705  * e - edge
14706  */
14707 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env,
14708                      bool loop_ok)
14709 {
14710         int *insn_stack = env->cfg.insn_stack;
14711         int *insn_state = env->cfg.insn_state;
14712
14713         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14714                 return DONE_EXPLORING;
14715
14716         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14717                 return DONE_EXPLORING;
14718
14719         if (w < 0 || w >= env->prog->len) {
14720                 verbose_linfo(env, t, "%d: ", t);
14721                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14722                 return -EINVAL;
14723         }
14724
14725         if (e == BRANCH) {
14726                 /* mark branch target for state pruning */
14727                 mark_prune_point(env, w);
14728                 mark_jmp_point(env, w);
14729         }
14730
14731         if (insn_state[w] == 0) {
14732                 /* tree-edge */
14733                 insn_state[t] = DISCOVERED | e;
14734                 insn_state[w] = DISCOVERED;
14735                 if (env->cfg.cur_stack >= env->prog->len)
14736                         return -E2BIG;
14737                 insn_stack[env->cfg.cur_stack++] = w;
14738                 return KEEP_EXPLORING;
14739         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14740                 if (loop_ok && env->bpf_capable)
14741                         return DONE_EXPLORING;
14742                 verbose_linfo(env, t, "%d: ", t);
14743                 verbose_linfo(env, w, "%d: ", w);
14744                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14745                 return -EINVAL;
14746         } else if (insn_state[w] == EXPLORED) {
14747                 /* forward- or cross-edge */
14748                 insn_state[t] = DISCOVERED | e;
14749         } else {
14750                 verbose(env, "insn state internal bug\n");
14751                 return -EFAULT;
14752         }
14753         return DONE_EXPLORING;
14754 }
14755
14756 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14757                                 struct bpf_verifier_env *env,
14758                                 bool visit_callee)
14759 {
14760         int ret;
14761
14762         ret = push_insn(t, t + 1, FALLTHROUGH, env, false);
14763         if (ret)
14764                 return ret;
14765
14766         mark_prune_point(env, t + 1);
14767         /* when we exit from subprog, we need to record non-linear history */
14768         mark_jmp_point(env, t + 1);
14769
14770         if (visit_callee) {
14771                 mark_prune_point(env, t);
14772                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env,
14773                                 /* It's ok to allow recursion from CFG point of
14774                                  * view. __check_func_call() will do the actual
14775                                  * check.
14776                                  */
14777                                 bpf_pseudo_func(insns + t));
14778         }
14779         return ret;
14780 }
14781
14782 /* Visits the instruction at index t and returns one of the following:
14783  *  < 0 - an error occurred
14784  *  DONE_EXPLORING - the instruction was fully explored
14785  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14786  */
14787 static int visit_insn(int t, struct bpf_verifier_env *env)
14788 {
14789         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14790         int ret;
14791
14792         if (bpf_pseudo_func(insn))
14793                 return visit_func_call_insn(t, insns, env, true);
14794
14795         /* All non-branch instructions have a single fall-through edge. */
14796         if (BPF_CLASS(insn->code) != BPF_JMP &&
14797             BPF_CLASS(insn->code) != BPF_JMP32)
14798                 return push_insn(t, t + 1, FALLTHROUGH, env, false);
14799
14800         switch (BPF_OP(insn->code)) {
14801         case BPF_EXIT:
14802                 return DONE_EXPLORING;
14803
14804         case BPF_CALL:
14805                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14806                         /* Mark this call insn as a prune point to trigger
14807                          * is_state_visited() check before call itself is
14808                          * processed by __check_func_call(). Otherwise new
14809                          * async state will be pushed for further exploration.
14810                          */
14811                         mark_prune_point(env, t);
14812                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14813                         struct bpf_kfunc_call_arg_meta meta;
14814
14815                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14816                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14817                                 mark_prune_point(env, t);
14818                                 /* Checking and saving state checkpoints at iter_next() call
14819                                  * is crucial for fast convergence of open-coded iterator loop
14820                                  * logic, so we need to force it. If we don't do that,
14821                                  * is_state_visited() might skip saving a checkpoint, causing
14822                                  * unnecessarily long sequence of not checkpointed
14823                                  * instructions and jumps, leading to exhaustion of jump
14824                                  * history buffer, and potentially other undesired outcomes.
14825                                  * It is expected that with correct open-coded iterators
14826                                  * convergence will happen quickly, so we don't run a risk of
14827                                  * exhausting memory.
14828                                  */
14829                                 mark_force_checkpoint(env, t);
14830                         }
14831                 }
14832                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14833
14834         case BPF_JA:
14835                 if (BPF_SRC(insn->code) != BPF_K)
14836                         return -EINVAL;
14837
14838                 /* unconditional jump with single edge */
14839                 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env,
14840                                 true);
14841                 if (ret)
14842                         return ret;
14843
14844                 mark_prune_point(env, t + insn->off + 1);
14845                 mark_jmp_point(env, t + insn->off + 1);
14846
14847                 return ret;
14848
14849         default:
14850                 /* conditional jump with two edges */
14851                 mark_prune_point(env, t);
14852
14853                 ret = push_insn(t, t + 1, FALLTHROUGH, env, true);
14854                 if (ret)
14855                         return ret;
14856
14857                 return push_insn(t, t + insn->off + 1, BRANCH, env, true);
14858         }
14859 }
14860
14861 /* non-recursive depth-first-search to detect loops in BPF program
14862  * loop == back-edge in directed graph
14863  */
14864 static int check_cfg(struct bpf_verifier_env *env)
14865 {
14866         int insn_cnt = env->prog->len;
14867         int *insn_stack, *insn_state;
14868         int ret = 0;
14869         int i;
14870
14871         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14872         if (!insn_state)
14873                 return -ENOMEM;
14874
14875         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14876         if (!insn_stack) {
14877                 kvfree(insn_state);
14878                 return -ENOMEM;
14879         }
14880
14881         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14882         insn_stack[0] = 0; /* 0 is the first instruction */
14883         env->cfg.cur_stack = 1;
14884
14885         while (env->cfg.cur_stack > 0) {
14886                 int t = insn_stack[env->cfg.cur_stack - 1];
14887
14888                 ret = visit_insn(t, env);
14889                 switch (ret) {
14890                 case DONE_EXPLORING:
14891                         insn_state[t] = EXPLORED;
14892                         env->cfg.cur_stack--;
14893                         break;
14894                 case KEEP_EXPLORING:
14895                         break;
14896                 default:
14897                         if (ret > 0) {
14898                                 verbose(env, "visit_insn internal bug\n");
14899                                 ret = -EFAULT;
14900                         }
14901                         goto err_free;
14902                 }
14903         }
14904
14905         if (env->cfg.cur_stack < 0) {
14906                 verbose(env, "pop stack internal bug\n");
14907                 ret = -EFAULT;
14908                 goto err_free;
14909         }
14910
14911         for (i = 0; i < insn_cnt; i++) {
14912                 if (insn_state[i] != EXPLORED) {
14913                         verbose(env, "unreachable insn %d\n", i);
14914                         ret = -EINVAL;
14915                         goto err_free;
14916                 }
14917         }
14918         ret = 0; /* cfg looks good */
14919
14920 err_free:
14921         kvfree(insn_state);
14922         kvfree(insn_stack);
14923         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14924         return ret;
14925 }
14926
14927 static int check_abnormal_return(struct bpf_verifier_env *env)
14928 {
14929         int i;
14930
14931         for (i = 1; i < env->subprog_cnt; i++) {
14932                 if (env->subprog_info[i].has_ld_abs) {
14933                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
14934                         return -EINVAL;
14935                 }
14936                 if (env->subprog_info[i].has_tail_call) {
14937                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
14938                         return -EINVAL;
14939                 }
14940         }
14941         return 0;
14942 }
14943
14944 /* The minimum supported BTF func info size */
14945 #define MIN_BPF_FUNCINFO_SIZE   8
14946 #define MAX_FUNCINFO_REC_SIZE   252
14947
14948 static int check_btf_func(struct bpf_verifier_env *env,
14949                           const union bpf_attr *attr,
14950                           bpfptr_t uattr)
14951 {
14952         const struct btf_type *type, *func_proto, *ret_type;
14953         u32 i, nfuncs, urec_size, min_size;
14954         u32 krec_size = sizeof(struct bpf_func_info);
14955         struct bpf_func_info *krecord;
14956         struct bpf_func_info_aux *info_aux = NULL;
14957         struct bpf_prog *prog;
14958         const struct btf *btf;
14959         bpfptr_t urecord;
14960         u32 prev_offset = 0;
14961         bool scalar_return;
14962         int ret = -ENOMEM;
14963
14964         nfuncs = attr->func_info_cnt;
14965         if (!nfuncs) {
14966                 if (check_abnormal_return(env))
14967                         return -EINVAL;
14968                 return 0;
14969         }
14970
14971         if (nfuncs != env->subprog_cnt) {
14972                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
14973                 return -EINVAL;
14974         }
14975
14976         urec_size = attr->func_info_rec_size;
14977         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
14978             urec_size > MAX_FUNCINFO_REC_SIZE ||
14979             urec_size % sizeof(u32)) {
14980                 verbose(env, "invalid func info rec size %u\n", urec_size);
14981                 return -EINVAL;
14982         }
14983
14984         prog = env->prog;
14985         btf = prog->aux->btf;
14986
14987         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
14988         min_size = min_t(u32, krec_size, urec_size);
14989
14990         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
14991         if (!krecord)
14992                 return -ENOMEM;
14993         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
14994         if (!info_aux)
14995                 goto err_free;
14996
14997         for (i = 0; i < nfuncs; i++) {
14998                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
14999                 if (ret) {
15000                         if (ret == -E2BIG) {
15001                                 verbose(env, "nonzero tailing record in func info");
15002                                 /* set the size kernel expects so loader can zero
15003                                  * out the rest of the record.
15004                                  */
15005                                 if (copy_to_bpfptr_offset(uattr,
15006                                                           offsetof(union bpf_attr, func_info_rec_size),
15007                                                           &min_size, sizeof(min_size)))
15008                                         ret = -EFAULT;
15009                         }
15010                         goto err_free;
15011                 }
15012
15013                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15014                         ret = -EFAULT;
15015                         goto err_free;
15016                 }
15017
15018                 /* check insn_off */
15019                 ret = -EINVAL;
15020                 if (i == 0) {
15021                         if (krecord[i].insn_off) {
15022                                 verbose(env,
15023                                         "nonzero insn_off %u for the first func info record",
15024                                         krecord[i].insn_off);
15025                                 goto err_free;
15026                         }
15027                 } else if (krecord[i].insn_off <= prev_offset) {
15028                         verbose(env,
15029                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15030                                 krecord[i].insn_off, prev_offset);
15031                         goto err_free;
15032                 }
15033
15034                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15035                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15036                         goto err_free;
15037                 }
15038
15039                 /* check type_id */
15040                 type = btf_type_by_id(btf, krecord[i].type_id);
15041                 if (!type || !btf_type_is_func(type)) {
15042                         verbose(env, "invalid type id %d in func info",
15043                                 krecord[i].type_id);
15044                         goto err_free;
15045                 }
15046                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15047
15048                 func_proto = btf_type_by_id(btf, type->type);
15049                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15050                         /* btf_func_check() already verified it during BTF load */
15051                         goto err_free;
15052                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15053                 scalar_return =
15054                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15055                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15056                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15057                         goto err_free;
15058                 }
15059                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15060                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15061                         goto err_free;
15062                 }
15063
15064                 prev_offset = krecord[i].insn_off;
15065                 bpfptr_add(&urecord, urec_size);
15066         }
15067
15068         prog->aux->func_info = krecord;
15069         prog->aux->func_info_cnt = nfuncs;
15070         prog->aux->func_info_aux = info_aux;
15071         return 0;
15072
15073 err_free:
15074         kvfree(krecord);
15075         kfree(info_aux);
15076         return ret;
15077 }
15078
15079 static void adjust_btf_func(struct bpf_verifier_env *env)
15080 {
15081         struct bpf_prog_aux *aux = env->prog->aux;
15082         int i;
15083
15084         if (!aux->func_info)
15085                 return;
15086
15087         for (i = 0; i < env->subprog_cnt; i++)
15088                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15089 }
15090
15091 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15092 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15093
15094 static int check_btf_line(struct bpf_verifier_env *env,
15095                           const union bpf_attr *attr,
15096                           bpfptr_t uattr)
15097 {
15098         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15099         struct bpf_subprog_info *sub;
15100         struct bpf_line_info *linfo;
15101         struct bpf_prog *prog;
15102         const struct btf *btf;
15103         bpfptr_t ulinfo;
15104         int err;
15105
15106         nr_linfo = attr->line_info_cnt;
15107         if (!nr_linfo)
15108                 return 0;
15109         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15110                 return -EINVAL;
15111
15112         rec_size = attr->line_info_rec_size;
15113         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15114             rec_size > MAX_LINEINFO_REC_SIZE ||
15115             rec_size & (sizeof(u32) - 1))
15116                 return -EINVAL;
15117
15118         /* Need to zero it in case the userspace may
15119          * pass in a smaller bpf_line_info object.
15120          */
15121         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15122                          GFP_KERNEL | __GFP_NOWARN);
15123         if (!linfo)
15124                 return -ENOMEM;
15125
15126         prog = env->prog;
15127         btf = prog->aux->btf;
15128
15129         s = 0;
15130         sub = env->subprog_info;
15131         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15132         expected_size = sizeof(struct bpf_line_info);
15133         ncopy = min_t(u32, expected_size, rec_size);
15134         for (i = 0; i < nr_linfo; i++) {
15135                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15136                 if (err) {
15137                         if (err == -E2BIG) {
15138                                 verbose(env, "nonzero tailing record in line_info");
15139                                 if (copy_to_bpfptr_offset(uattr,
15140                                                           offsetof(union bpf_attr, line_info_rec_size),
15141                                                           &expected_size, sizeof(expected_size)))
15142                                         err = -EFAULT;
15143                         }
15144                         goto err_free;
15145                 }
15146
15147                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15148                         err = -EFAULT;
15149                         goto err_free;
15150                 }
15151
15152                 /*
15153                  * Check insn_off to ensure
15154                  * 1) strictly increasing AND
15155                  * 2) bounded by prog->len
15156                  *
15157                  * The linfo[0].insn_off == 0 check logically falls into
15158                  * the later "missing bpf_line_info for func..." case
15159                  * because the first linfo[0].insn_off must be the
15160                  * first sub also and the first sub must have
15161                  * subprog_info[0].start == 0.
15162                  */
15163                 if ((i && linfo[i].insn_off <= prev_offset) ||
15164                     linfo[i].insn_off >= prog->len) {
15165                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15166                                 i, linfo[i].insn_off, prev_offset,
15167                                 prog->len);
15168                         err = -EINVAL;
15169                         goto err_free;
15170                 }
15171
15172                 if (!prog->insnsi[linfo[i].insn_off].code) {
15173                         verbose(env,
15174                                 "Invalid insn code at line_info[%u].insn_off\n",
15175                                 i);
15176                         err = -EINVAL;
15177                         goto err_free;
15178                 }
15179
15180                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15181                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15182                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15183                         err = -EINVAL;
15184                         goto err_free;
15185                 }
15186
15187                 if (s != env->subprog_cnt) {
15188                         if (linfo[i].insn_off == sub[s].start) {
15189                                 sub[s].linfo_idx = i;
15190                                 s++;
15191                         } else if (sub[s].start < linfo[i].insn_off) {
15192                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15193                                 err = -EINVAL;
15194                                 goto err_free;
15195                         }
15196                 }
15197
15198                 prev_offset = linfo[i].insn_off;
15199                 bpfptr_add(&ulinfo, rec_size);
15200         }
15201
15202         if (s != env->subprog_cnt) {
15203                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15204                         env->subprog_cnt - s, s);
15205                 err = -EINVAL;
15206                 goto err_free;
15207         }
15208
15209         prog->aux->linfo = linfo;
15210         prog->aux->nr_linfo = nr_linfo;
15211
15212         return 0;
15213
15214 err_free:
15215         kvfree(linfo);
15216         return err;
15217 }
15218
15219 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15220 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15221
15222 static int check_core_relo(struct bpf_verifier_env *env,
15223                            const union bpf_attr *attr,
15224                            bpfptr_t uattr)
15225 {
15226         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15227         struct bpf_core_relo core_relo = {};
15228         struct bpf_prog *prog = env->prog;
15229         const struct btf *btf = prog->aux->btf;
15230         struct bpf_core_ctx ctx = {
15231                 .log = &env->log,
15232                 .btf = btf,
15233         };
15234         bpfptr_t u_core_relo;
15235         int err;
15236
15237         nr_core_relo = attr->core_relo_cnt;
15238         if (!nr_core_relo)
15239                 return 0;
15240         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15241                 return -EINVAL;
15242
15243         rec_size = attr->core_relo_rec_size;
15244         if (rec_size < MIN_CORE_RELO_SIZE ||
15245             rec_size > MAX_CORE_RELO_SIZE ||
15246             rec_size % sizeof(u32))
15247                 return -EINVAL;
15248
15249         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15250         expected_size = sizeof(struct bpf_core_relo);
15251         ncopy = min_t(u32, expected_size, rec_size);
15252
15253         /* Unlike func_info and line_info, copy and apply each CO-RE
15254          * relocation record one at a time.
15255          */
15256         for (i = 0; i < nr_core_relo; i++) {
15257                 /* future proofing when sizeof(bpf_core_relo) changes */
15258                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15259                 if (err) {
15260                         if (err == -E2BIG) {
15261                                 verbose(env, "nonzero tailing record in core_relo");
15262                                 if (copy_to_bpfptr_offset(uattr,
15263                                                           offsetof(union bpf_attr, core_relo_rec_size),
15264                                                           &expected_size, sizeof(expected_size)))
15265                                         err = -EFAULT;
15266                         }
15267                         break;
15268                 }
15269
15270                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15271                         err = -EFAULT;
15272                         break;
15273                 }
15274
15275                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15276                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15277                                 i, core_relo.insn_off, prog->len);
15278                         err = -EINVAL;
15279                         break;
15280                 }
15281
15282                 err = bpf_core_apply(&ctx, &core_relo, i,
15283                                      &prog->insnsi[core_relo.insn_off / 8]);
15284                 if (err)
15285                         break;
15286                 bpfptr_add(&u_core_relo, rec_size);
15287         }
15288         return err;
15289 }
15290
15291 static int check_btf_info(struct bpf_verifier_env *env,
15292                           const union bpf_attr *attr,
15293                           bpfptr_t uattr)
15294 {
15295         struct btf *btf;
15296         int err;
15297
15298         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15299                 if (check_abnormal_return(env))
15300                         return -EINVAL;
15301                 return 0;
15302         }
15303
15304         btf = btf_get_by_fd(attr->prog_btf_fd);
15305         if (IS_ERR(btf))
15306                 return PTR_ERR(btf);
15307         if (btf_is_kernel(btf)) {
15308                 btf_put(btf);
15309                 return -EACCES;
15310         }
15311         env->prog->aux->btf = btf;
15312
15313         err = check_btf_func(env, attr, uattr);
15314         if (err)
15315                 return err;
15316
15317         err = check_btf_line(env, attr, uattr);
15318         if (err)
15319                 return err;
15320
15321         err = check_core_relo(env, attr, uattr);
15322         if (err)
15323                 return err;
15324
15325         return 0;
15326 }
15327
15328 /* check %cur's range satisfies %old's */
15329 static bool range_within(struct bpf_reg_state *old,
15330                          struct bpf_reg_state *cur)
15331 {
15332         return old->umin_value <= cur->umin_value &&
15333                old->umax_value >= cur->umax_value &&
15334                old->smin_value <= cur->smin_value &&
15335                old->smax_value >= cur->smax_value &&
15336                old->u32_min_value <= cur->u32_min_value &&
15337                old->u32_max_value >= cur->u32_max_value &&
15338                old->s32_min_value <= cur->s32_min_value &&
15339                old->s32_max_value >= cur->s32_max_value;
15340 }
15341
15342 /* If in the old state two registers had the same id, then they need to have
15343  * the same id in the new state as well.  But that id could be different from
15344  * the old state, so we need to track the mapping from old to new ids.
15345  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15346  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15347  * regs with a different old id could still have new id 9, we don't care about
15348  * that.
15349  * So we look through our idmap to see if this old id has been seen before.  If
15350  * so, we require the new id to match; otherwise, we add the id pair to the map.
15351  */
15352 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15353 {
15354         struct bpf_id_pair *map = idmap->map;
15355         unsigned int i;
15356
15357         /* either both IDs should be set or both should be zero */
15358         if (!!old_id != !!cur_id)
15359                 return false;
15360
15361         if (old_id == 0) /* cur_id == 0 as well */
15362                 return true;
15363
15364         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15365                 if (!map[i].old) {
15366                         /* Reached an empty slot; haven't seen this id before */
15367                         map[i].old = old_id;
15368                         map[i].cur = cur_id;
15369                         return true;
15370                 }
15371                 if (map[i].old == old_id)
15372                         return map[i].cur == cur_id;
15373                 if (map[i].cur == cur_id)
15374                         return false;
15375         }
15376         /* We ran out of idmap slots, which should be impossible */
15377         WARN_ON_ONCE(1);
15378         return false;
15379 }
15380
15381 /* Similar to check_ids(), but allocate a unique temporary ID
15382  * for 'old_id' or 'cur_id' of zero.
15383  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15384  */
15385 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15386 {
15387         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15388         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15389
15390         return check_ids(old_id, cur_id, idmap);
15391 }
15392
15393 static void clean_func_state(struct bpf_verifier_env *env,
15394                              struct bpf_func_state *st)
15395 {
15396         enum bpf_reg_liveness live;
15397         int i, j;
15398
15399         for (i = 0; i < BPF_REG_FP; i++) {
15400                 live = st->regs[i].live;
15401                 /* liveness must not touch this register anymore */
15402                 st->regs[i].live |= REG_LIVE_DONE;
15403                 if (!(live & REG_LIVE_READ))
15404                         /* since the register is unused, clear its state
15405                          * to make further comparison simpler
15406                          */
15407                         __mark_reg_not_init(env, &st->regs[i]);
15408         }
15409
15410         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15411                 live = st->stack[i].spilled_ptr.live;
15412                 /* liveness must not touch this stack slot anymore */
15413                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15414                 if (!(live & REG_LIVE_READ)) {
15415                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15416                         for (j = 0; j < BPF_REG_SIZE; j++)
15417                                 st->stack[i].slot_type[j] = STACK_INVALID;
15418                 }
15419         }
15420 }
15421
15422 static void clean_verifier_state(struct bpf_verifier_env *env,
15423                                  struct bpf_verifier_state *st)
15424 {
15425         int i;
15426
15427         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15428                 /* all regs in this state in all frames were already marked */
15429                 return;
15430
15431         for (i = 0; i <= st->curframe; i++)
15432                 clean_func_state(env, st->frame[i]);
15433 }
15434
15435 /* the parentage chains form a tree.
15436  * the verifier states are added to state lists at given insn and
15437  * pushed into state stack for future exploration.
15438  * when the verifier reaches bpf_exit insn some of the verifer states
15439  * stored in the state lists have their final liveness state already,
15440  * but a lot of states will get revised from liveness point of view when
15441  * the verifier explores other branches.
15442  * Example:
15443  * 1: r0 = 1
15444  * 2: if r1 == 100 goto pc+1
15445  * 3: r0 = 2
15446  * 4: exit
15447  * when the verifier reaches exit insn the register r0 in the state list of
15448  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15449  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15450  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15451  *
15452  * Since the verifier pushes the branch states as it sees them while exploring
15453  * the program the condition of walking the branch instruction for the second
15454  * time means that all states below this branch were already explored and
15455  * their final liveness marks are already propagated.
15456  * Hence when the verifier completes the search of state list in is_state_visited()
15457  * we can call this clean_live_states() function to mark all liveness states
15458  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15459  * will not be used.
15460  * This function also clears the registers and stack for states that !READ
15461  * to simplify state merging.
15462  *
15463  * Important note here that walking the same branch instruction in the callee
15464  * doesn't meant that the states are DONE. The verifier has to compare
15465  * the callsites
15466  */
15467 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15468                               struct bpf_verifier_state *cur)
15469 {
15470         struct bpf_verifier_state_list *sl;
15471         int i;
15472
15473         sl = *explored_state(env, insn);
15474         while (sl) {
15475                 if (sl->state.branches)
15476                         goto next;
15477                 if (sl->state.insn_idx != insn ||
15478                     sl->state.curframe != cur->curframe)
15479                         goto next;
15480                 for (i = 0; i <= cur->curframe; i++)
15481                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15482                                 goto next;
15483                 clean_verifier_state(env, &sl->state);
15484 next:
15485                 sl = sl->next;
15486         }
15487 }
15488
15489 static bool regs_exact(const struct bpf_reg_state *rold,
15490                        const struct bpf_reg_state *rcur,
15491                        struct bpf_idmap *idmap)
15492 {
15493         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15494                check_ids(rold->id, rcur->id, idmap) &&
15495                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15496 }
15497
15498 /* Returns true if (rold safe implies rcur safe) */
15499 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15500                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15501 {
15502         if (!(rold->live & REG_LIVE_READ))
15503                 /* explored state didn't use this */
15504                 return true;
15505         if (rold->type == NOT_INIT)
15506                 /* explored state can't have used this */
15507                 return true;
15508         if (rcur->type == NOT_INIT)
15509                 return false;
15510
15511         /* Enforce that register types have to match exactly, including their
15512          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15513          * rule.
15514          *
15515          * One can make a point that using a pointer register as unbounded
15516          * SCALAR would be technically acceptable, but this could lead to
15517          * pointer leaks because scalars are allowed to leak while pointers
15518          * are not. We could make this safe in special cases if root is
15519          * calling us, but it's probably not worth the hassle.
15520          *
15521          * Also, register types that are *not* MAYBE_NULL could technically be
15522          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15523          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15524          * to the same map).
15525          * However, if the old MAYBE_NULL register then got NULL checked,
15526          * doing so could have affected others with the same id, and we can't
15527          * check for that because we lost the id when we converted to
15528          * a non-MAYBE_NULL variant.
15529          * So, as a general rule we don't allow mixing MAYBE_NULL and
15530          * non-MAYBE_NULL registers as well.
15531          */
15532         if (rold->type != rcur->type)
15533                 return false;
15534
15535         switch (base_type(rold->type)) {
15536         case SCALAR_VALUE:
15537                 if (env->explore_alu_limits) {
15538                         /* explore_alu_limits disables tnum_in() and range_within()
15539                          * logic and requires everything to be strict
15540                          */
15541                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15542                                check_scalar_ids(rold->id, rcur->id, idmap);
15543                 }
15544                 if (!rold->precise)
15545                         return true;
15546                 /* Why check_ids() for scalar registers?
15547                  *
15548                  * Consider the following BPF code:
15549                  *   1: r6 = ... unbound scalar, ID=a ...
15550                  *   2: r7 = ... unbound scalar, ID=b ...
15551                  *   3: if (r6 > r7) goto +1
15552                  *   4: r6 = r7
15553                  *   5: if (r6 > X) goto ...
15554                  *   6: ... memory operation using r7 ...
15555                  *
15556                  * First verification path is [1-6]:
15557                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15558                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15559                  *   r7 <= X, because r6 and r7 share same id.
15560                  * Next verification path is [1-4, 6].
15561                  *
15562                  * Instruction (6) would be reached in two states:
15563                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15564                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15565                  *
15566                  * Use check_ids() to distinguish these states.
15567                  * ---
15568                  * Also verify that new value satisfies old value range knowledge.
15569                  */
15570                 return range_within(rold, rcur) &&
15571                        tnum_in(rold->var_off, rcur->var_off) &&
15572                        check_scalar_ids(rold->id, rcur->id, idmap);
15573         case PTR_TO_MAP_KEY:
15574         case PTR_TO_MAP_VALUE:
15575         case PTR_TO_MEM:
15576         case PTR_TO_BUF:
15577         case PTR_TO_TP_BUFFER:
15578                 /* If the new min/max/var_off satisfy the old ones and
15579                  * everything else matches, we are OK.
15580                  */
15581                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15582                        range_within(rold, rcur) &&
15583                        tnum_in(rold->var_off, rcur->var_off) &&
15584                        check_ids(rold->id, rcur->id, idmap) &&
15585                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15586         case PTR_TO_PACKET_META:
15587         case PTR_TO_PACKET:
15588                 /* We must have at least as much range as the old ptr
15589                  * did, so that any accesses which were safe before are
15590                  * still safe.  This is true even if old range < old off,
15591                  * since someone could have accessed through (ptr - k), or
15592                  * even done ptr -= k in a register, to get a safe access.
15593                  */
15594                 if (rold->range > rcur->range)
15595                         return false;
15596                 /* If the offsets don't match, we can't trust our alignment;
15597                  * nor can we be sure that we won't fall out of range.
15598                  */
15599                 if (rold->off != rcur->off)
15600                         return false;
15601                 /* id relations must be preserved */
15602                 if (!check_ids(rold->id, rcur->id, idmap))
15603                         return false;
15604                 /* new val must satisfy old val knowledge */
15605                 return range_within(rold, rcur) &&
15606                        tnum_in(rold->var_off, rcur->var_off);
15607         case PTR_TO_STACK:
15608                 /* two stack pointers are equal only if they're pointing to
15609                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15610                  */
15611                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15612         default:
15613                 return regs_exact(rold, rcur, idmap);
15614         }
15615 }
15616
15617 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15618                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15619 {
15620         int i, spi;
15621
15622         /* walk slots of the explored stack and ignore any additional
15623          * slots in the current stack, since explored(safe) state
15624          * didn't use them
15625          */
15626         for (i = 0; i < old->allocated_stack; i++) {
15627                 struct bpf_reg_state *old_reg, *cur_reg;
15628
15629                 spi = i / BPF_REG_SIZE;
15630
15631                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15632                         i += BPF_REG_SIZE - 1;
15633                         /* explored state didn't use this */
15634                         continue;
15635                 }
15636
15637                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15638                         continue;
15639
15640                 if (env->allow_uninit_stack &&
15641                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15642                         continue;
15643
15644                 /* explored stack has more populated slots than current stack
15645                  * and these slots were used
15646                  */
15647                 if (i >= cur->allocated_stack)
15648                         return false;
15649
15650                 /* if old state was safe with misc data in the stack
15651                  * it will be safe with zero-initialized stack.
15652                  * The opposite is not true
15653                  */
15654                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15655                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15656                         continue;
15657                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15658                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15659                         /* Ex: old explored (safe) state has STACK_SPILL in
15660                          * this stack slot, but current has STACK_MISC ->
15661                          * this verifier states are not equivalent,
15662                          * return false to continue verification of this path
15663                          */
15664                         return false;
15665                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15666                         continue;
15667                 /* Both old and cur are having same slot_type */
15668                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15669                 case STACK_SPILL:
15670                         /* when explored and current stack slot are both storing
15671                          * spilled registers, check that stored pointers types
15672                          * are the same as well.
15673                          * Ex: explored safe path could have stored
15674                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15675                          * but current path has stored:
15676                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15677                          * such verifier states are not equivalent.
15678                          * return false to continue verification of this path
15679                          */
15680                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15681                                      &cur->stack[spi].spilled_ptr, idmap))
15682                                 return false;
15683                         break;
15684                 case STACK_DYNPTR:
15685                         old_reg = &old->stack[spi].spilled_ptr;
15686                         cur_reg = &cur->stack[spi].spilled_ptr;
15687                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15688                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15689                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15690                                 return false;
15691                         break;
15692                 case STACK_ITER:
15693                         old_reg = &old->stack[spi].spilled_ptr;
15694                         cur_reg = &cur->stack[spi].spilled_ptr;
15695                         /* iter.depth is not compared between states as it
15696                          * doesn't matter for correctness and would otherwise
15697                          * prevent convergence; we maintain it only to prevent
15698                          * infinite loop check triggering, see
15699                          * iter_active_depths_differ()
15700                          */
15701                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15702                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15703                             old_reg->iter.state != cur_reg->iter.state ||
15704                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15705                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15706                                 return false;
15707                         break;
15708                 case STACK_MISC:
15709                 case STACK_ZERO:
15710                 case STACK_INVALID:
15711                         continue;
15712                 /* Ensure that new unhandled slot types return false by default */
15713                 default:
15714                         return false;
15715                 }
15716         }
15717         return true;
15718 }
15719
15720 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15721                     struct bpf_idmap *idmap)
15722 {
15723         int i;
15724
15725         if (old->acquired_refs != cur->acquired_refs)
15726                 return false;
15727
15728         for (i = 0; i < old->acquired_refs; i++) {
15729                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15730                         return false;
15731         }
15732
15733         return true;
15734 }
15735
15736 /* compare two verifier states
15737  *
15738  * all states stored in state_list are known to be valid, since
15739  * verifier reached 'bpf_exit' instruction through them
15740  *
15741  * this function is called when verifier exploring different branches of
15742  * execution popped from the state stack. If it sees an old state that has
15743  * more strict register state and more strict stack state then this execution
15744  * branch doesn't need to be explored further, since verifier already
15745  * concluded that more strict state leads to valid finish.
15746  *
15747  * Therefore two states are equivalent if register state is more conservative
15748  * and explored stack state is more conservative than the current one.
15749  * Example:
15750  *       explored                   current
15751  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15752  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15753  *
15754  * In other words if current stack state (one being explored) has more
15755  * valid slots than old one that already passed validation, it means
15756  * the verifier can stop exploring and conclude that current state is valid too
15757  *
15758  * Similarly with registers. If explored state has register type as invalid
15759  * whereas register type in current state is meaningful, it means that
15760  * the current state will reach 'bpf_exit' instruction safely
15761  */
15762 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15763                               struct bpf_func_state *cur)
15764 {
15765         int i;
15766
15767         for (i = 0; i < MAX_BPF_REG; i++)
15768                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15769                              &env->idmap_scratch))
15770                         return false;
15771
15772         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15773                 return false;
15774
15775         if (!refsafe(old, cur, &env->idmap_scratch))
15776                 return false;
15777
15778         return true;
15779 }
15780
15781 static bool states_equal(struct bpf_verifier_env *env,
15782                          struct bpf_verifier_state *old,
15783                          struct bpf_verifier_state *cur)
15784 {
15785         int i;
15786
15787         if (old->curframe != cur->curframe)
15788                 return false;
15789
15790         env->idmap_scratch.tmp_id_gen = env->id_gen;
15791         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15792
15793         /* Verification state from speculative execution simulation
15794          * must never prune a non-speculative execution one.
15795          */
15796         if (old->speculative && !cur->speculative)
15797                 return false;
15798
15799         if (old->active_lock.ptr != cur->active_lock.ptr)
15800                 return false;
15801
15802         /* Old and cur active_lock's have to be either both present
15803          * or both absent.
15804          */
15805         if (!!old->active_lock.id != !!cur->active_lock.id)
15806                 return false;
15807
15808         if (old->active_lock.id &&
15809             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15810                 return false;
15811
15812         if (old->active_rcu_lock != cur->active_rcu_lock)
15813                 return false;
15814
15815         /* for states to be equal callsites have to be the same
15816          * and all frame states need to be equivalent
15817          */
15818         for (i = 0; i <= old->curframe; i++) {
15819                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15820                         return false;
15821                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15822                         return false;
15823         }
15824         return true;
15825 }
15826
15827 /* Return 0 if no propagation happened. Return negative error code if error
15828  * happened. Otherwise, return the propagated bit.
15829  */
15830 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15831                                   struct bpf_reg_state *reg,
15832                                   struct bpf_reg_state *parent_reg)
15833 {
15834         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15835         u8 flag = reg->live & REG_LIVE_READ;
15836         int err;
15837
15838         /* When comes here, read flags of PARENT_REG or REG could be any of
15839          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15840          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15841          */
15842         if (parent_flag == REG_LIVE_READ64 ||
15843             /* Or if there is no read flag from REG. */
15844             !flag ||
15845             /* Or if the read flag from REG is the same as PARENT_REG. */
15846             parent_flag == flag)
15847                 return 0;
15848
15849         err = mark_reg_read(env, reg, parent_reg, flag);
15850         if (err)
15851                 return err;
15852
15853         return flag;
15854 }
15855
15856 /* A write screens off any subsequent reads; but write marks come from the
15857  * straight-line code between a state and its parent.  When we arrive at an
15858  * equivalent state (jump target or such) we didn't arrive by the straight-line
15859  * code, so read marks in the state must propagate to the parent regardless
15860  * of the state's write marks. That's what 'parent == state->parent' comparison
15861  * in mark_reg_read() is for.
15862  */
15863 static int propagate_liveness(struct bpf_verifier_env *env,
15864                               const struct bpf_verifier_state *vstate,
15865                               struct bpf_verifier_state *vparent)
15866 {
15867         struct bpf_reg_state *state_reg, *parent_reg;
15868         struct bpf_func_state *state, *parent;
15869         int i, frame, err = 0;
15870
15871         if (vparent->curframe != vstate->curframe) {
15872                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15873                      vparent->curframe, vstate->curframe);
15874                 return -EFAULT;
15875         }
15876         /* Propagate read liveness of registers... */
15877         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15878         for (frame = 0; frame <= vstate->curframe; frame++) {
15879                 parent = vparent->frame[frame];
15880                 state = vstate->frame[frame];
15881                 parent_reg = parent->regs;
15882                 state_reg = state->regs;
15883                 /* We don't need to worry about FP liveness, it's read-only */
15884                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15885                         err = propagate_liveness_reg(env, &state_reg[i],
15886                                                      &parent_reg[i]);
15887                         if (err < 0)
15888                                 return err;
15889                         if (err == REG_LIVE_READ64)
15890                                 mark_insn_zext(env, &parent_reg[i]);
15891                 }
15892
15893                 /* Propagate stack slots. */
15894                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15895                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15896                         parent_reg = &parent->stack[i].spilled_ptr;
15897                         state_reg = &state->stack[i].spilled_ptr;
15898                         err = propagate_liveness_reg(env, state_reg,
15899                                                      parent_reg);
15900                         if (err < 0)
15901                                 return err;
15902                 }
15903         }
15904         return 0;
15905 }
15906
15907 /* find precise scalars in the previous equivalent state and
15908  * propagate them into the current state
15909  */
15910 static int propagate_precision(struct bpf_verifier_env *env,
15911                                const struct bpf_verifier_state *old)
15912 {
15913         struct bpf_reg_state *state_reg;
15914         struct bpf_func_state *state;
15915         int i, err = 0, fr;
15916         bool first;
15917
15918         for (fr = old->curframe; fr >= 0; fr--) {
15919                 state = old->frame[fr];
15920                 state_reg = state->regs;
15921                 first = true;
15922                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15923                         if (state_reg->type != SCALAR_VALUE ||
15924                             !state_reg->precise ||
15925                             !(state_reg->live & REG_LIVE_READ))
15926                                 continue;
15927                         if (env->log.level & BPF_LOG_LEVEL2) {
15928                                 if (first)
15929                                         verbose(env, "frame %d: propagating r%d", fr, i);
15930                                 else
15931                                         verbose(env, ",r%d", i);
15932                         }
15933                         bt_set_frame_reg(&env->bt, fr, i);
15934                         first = false;
15935                 }
15936
15937                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
15938                         if (!is_spilled_reg(&state->stack[i]))
15939                                 continue;
15940                         state_reg = &state->stack[i].spilled_ptr;
15941                         if (state_reg->type != SCALAR_VALUE ||
15942                             !state_reg->precise ||
15943                             !(state_reg->live & REG_LIVE_READ))
15944                                 continue;
15945                         if (env->log.level & BPF_LOG_LEVEL2) {
15946                                 if (first)
15947                                         verbose(env, "frame %d: propagating fp%d",
15948                                                 fr, (-i - 1) * BPF_REG_SIZE);
15949                                 else
15950                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
15951                         }
15952                         bt_set_frame_slot(&env->bt, fr, i);
15953                         first = false;
15954                 }
15955                 if (!first)
15956                         verbose(env, "\n");
15957         }
15958
15959         err = mark_chain_precision_batch(env);
15960         if (err < 0)
15961                 return err;
15962
15963         return 0;
15964 }
15965
15966 static bool states_maybe_looping(struct bpf_verifier_state *old,
15967                                  struct bpf_verifier_state *cur)
15968 {
15969         struct bpf_func_state *fold, *fcur;
15970         int i, fr = cur->curframe;
15971
15972         if (old->curframe != fr)
15973                 return false;
15974
15975         fold = old->frame[fr];
15976         fcur = cur->frame[fr];
15977         for (i = 0; i < MAX_BPF_REG; i++)
15978                 if (memcmp(&fold->regs[i], &fcur->regs[i],
15979                            offsetof(struct bpf_reg_state, parent)))
15980                         return false;
15981         return true;
15982 }
15983
15984 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
15985 {
15986         return env->insn_aux_data[insn_idx].is_iter_next;
15987 }
15988
15989 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
15990  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
15991  * states to match, which otherwise would look like an infinite loop. So while
15992  * iter_next() calls are taken care of, we still need to be careful and
15993  * prevent erroneous and too eager declaration of "ininite loop", when
15994  * iterators are involved.
15995  *
15996  * Here's a situation in pseudo-BPF assembly form:
15997  *
15998  *   0: again:                          ; set up iter_next() call args
15999  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16000  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16001  *   3:   if r0 == 0 goto done
16002  *   4:   ... something useful here ...
16003  *   5:   goto again                    ; another iteration
16004  *   6: done:
16005  *   7:   r1 = &it
16006  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16007  *   9:   exit
16008  *
16009  * This is a typical loop. Let's assume that we have a prune point at 1:,
16010  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16011  * again`, assuming other heuristics don't get in a way).
16012  *
16013  * When we first time come to 1:, let's say we have some state X. We proceed
16014  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16015  * Now we come back to validate that forked ACTIVE state. We proceed through
16016  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16017  * are converging. But the problem is that we don't know that yet, as this
16018  * convergence has to happen at iter_next() call site only. So if nothing is
16019  * done, at 1: verifier will use bounded loop logic and declare infinite
16020  * looping (and would be *technically* correct, if not for iterator's
16021  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16022  * don't want that. So what we do in process_iter_next_call() when we go on
16023  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16024  * a different iteration. So when we suspect an infinite loop, we additionally
16025  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16026  * pretend we are not looping and wait for next iter_next() call.
16027  *
16028  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16029  * loop, because that would actually mean infinite loop, as DRAINED state is
16030  * "sticky", and so we'll keep returning into the same instruction with the
16031  * same state (at least in one of possible code paths).
16032  *
16033  * This approach allows to keep infinite loop heuristic even in the face of
16034  * active iterator. E.g., C snippet below is and will be detected as
16035  * inifintely looping:
16036  *
16037  *   struct bpf_iter_num it;
16038  *   int *p, x;
16039  *
16040  *   bpf_iter_num_new(&it, 0, 10);
16041  *   while ((p = bpf_iter_num_next(&t))) {
16042  *       x = p;
16043  *       while (x--) {} // <<-- infinite loop here
16044  *   }
16045  *
16046  */
16047 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16048 {
16049         struct bpf_reg_state *slot, *cur_slot;
16050         struct bpf_func_state *state;
16051         int i, fr;
16052
16053         for (fr = old->curframe; fr >= 0; fr--) {
16054                 state = old->frame[fr];
16055                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16056                         if (state->stack[i].slot_type[0] != STACK_ITER)
16057                                 continue;
16058
16059                         slot = &state->stack[i].spilled_ptr;
16060                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16061                                 continue;
16062
16063                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16064                         if (cur_slot->iter.depth != slot->iter.depth)
16065                                 return true;
16066                 }
16067         }
16068         return false;
16069 }
16070
16071 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16072 {
16073         struct bpf_verifier_state_list *new_sl;
16074         struct bpf_verifier_state_list *sl, **pprev;
16075         struct bpf_verifier_state *cur = env->cur_state, *new;
16076         int i, j, err, states_cnt = 0;
16077         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16078         bool add_new_state = force_new_state;
16079
16080         /* bpf progs typically have pruning point every 4 instructions
16081          * http://vger.kernel.org/bpfconf2019.html#session-1
16082          * Do not add new state for future pruning if the verifier hasn't seen
16083          * at least 2 jumps and at least 8 instructions.
16084          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16085          * In tests that amounts to up to 50% reduction into total verifier
16086          * memory consumption and 20% verifier time speedup.
16087          */
16088         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16089             env->insn_processed - env->prev_insn_processed >= 8)
16090                 add_new_state = true;
16091
16092         pprev = explored_state(env, insn_idx);
16093         sl = *pprev;
16094
16095         clean_live_states(env, insn_idx, cur);
16096
16097         while (sl) {
16098                 states_cnt++;
16099                 if (sl->state.insn_idx != insn_idx)
16100                         goto next;
16101
16102                 if (sl->state.branches) {
16103                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16104
16105                         if (frame->in_async_callback_fn &&
16106                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16107                                 /* Different async_entry_cnt means that the verifier is
16108                                  * processing another entry into async callback.
16109                                  * Seeing the same state is not an indication of infinite
16110                                  * loop or infinite recursion.
16111                                  * But finding the same state doesn't mean that it's safe
16112                                  * to stop processing the current state. The previous state
16113                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16114                                  * Checking in_async_callback_fn alone is not enough either.
16115                                  * Since the verifier still needs to catch infinite loops
16116                                  * inside async callbacks.
16117                                  */
16118                                 goto skip_inf_loop_check;
16119                         }
16120                         /* BPF open-coded iterators loop detection is special.
16121                          * states_maybe_looping() logic is too simplistic in detecting
16122                          * states that *might* be equivalent, because it doesn't know
16123                          * about ID remapping, so don't even perform it.
16124                          * See process_iter_next_call() and iter_active_depths_differ()
16125                          * for overview of the logic. When current and one of parent
16126                          * states are detected as equivalent, it's a good thing: we prove
16127                          * convergence and can stop simulating further iterations.
16128                          * It's safe to assume that iterator loop will finish, taking into
16129                          * account iter_next() contract of eventually returning
16130                          * sticky NULL result.
16131                          */
16132                         if (is_iter_next_insn(env, insn_idx)) {
16133                                 if (states_equal(env, &sl->state, cur)) {
16134                                         struct bpf_func_state *cur_frame;
16135                                         struct bpf_reg_state *iter_state, *iter_reg;
16136                                         int spi;
16137
16138                                         cur_frame = cur->frame[cur->curframe];
16139                                         /* btf_check_iter_kfuncs() enforces that
16140                                          * iter state pointer is always the first arg
16141                                          */
16142                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16143                                         /* current state is valid due to states_equal(),
16144                                          * so we can assume valid iter and reg state,
16145                                          * no need for extra (re-)validations
16146                                          */
16147                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16148                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16149                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16150                                                 goto hit;
16151                                 }
16152                                 goto skip_inf_loop_check;
16153                         }
16154                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16155                         if (states_maybe_looping(&sl->state, cur) &&
16156                             states_equal(env, &sl->state, cur) &&
16157                             !iter_active_depths_differ(&sl->state, cur)) {
16158                                 verbose_linfo(env, insn_idx, "; ");
16159                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16160                                 return -EINVAL;
16161                         }
16162                         /* if the verifier is processing a loop, avoid adding new state
16163                          * too often, since different loop iterations have distinct
16164                          * states and may not help future pruning.
16165                          * This threshold shouldn't be too low to make sure that
16166                          * a loop with large bound will be rejected quickly.
16167                          * The most abusive loop will be:
16168                          * r1 += 1
16169                          * if r1 < 1000000 goto pc-2
16170                          * 1M insn_procssed limit / 100 == 10k peak states.
16171                          * This threshold shouldn't be too high either, since states
16172                          * at the end of the loop are likely to be useful in pruning.
16173                          */
16174 skip_inf_loop_check:
16175                         if (!force_new_state &&
16176                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16177                             env->insn_processed - env->prev_insn_processed < 100)
16178                                 add_new_state = false;
16179                         goto miss;
16180                 }
16181                 if (states_equal(env, &sl->state, cur)) {
16182 hit:
16183                         sl->hit_cnt++;
16184                         /* reached equivalent register/stack state,
16185                          * prune the search.
16186                          * Registers read by the continuation are read by us.
16187                          * If we have any write marks in env->cur_state, they
16188                          * will prevent corresponding reads in the continuation
16189                          * from reaching our parent (an explored_state).  Our
16190                          * own state will get the read marks recorded, but
16191                          * they'll be immediately forgotten as we're pruning
16192                          * this state and will pop a new one.
16193                          */
16194                         err = propagate_liveness(env, &sl->state, cur);
16195
16196                         /* if previous state reached the exit with precision and
16197                          * current state is equivalent to it (except precsion marks)
16198                          * the precision needs to be propagated back in
16199                          * the current state.
16200                          */
16201                         err = err ? : push_jmp_history(env, cur);
16202                         err = err ? : propagate_precision(env, &sl->state);
16203                         if (err)
16204                                 return err;
16205                         return 1;
16206                 }
16207 miss:
16208                 /* when new state is not going to be added do not increase miss count.
16209                  * Otherwise several loop iterations will remove the state
16210                  * recorded earlier. The goal of these heuristics is to have
16211                  * states from some iterations of the loop (some in the beginning
16212                  * and some at the end) to help pruning.
16213                  */
16214                 if (add_new_state)
16215                         sl->miss_cnt++;
16216                 /* heuristic to determine whether this state is beneficial
16217                  * to keep checking from state equivalence point of view.
16218                  * Higher numbers increase max_states_per_insn and verification time,
16219                  * but do not meaningfully decrease insn_processed.
16220                  */
16221                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16222                         /* the state is unlikely to be useful. Remove it to
16223                          * speed up verification
16224                          */
16225                         *pprev = sl->next;
16226                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16227                                 u32 br = sl->state.branches;
16228
16229                                 WARN_ONCE(br,
16230                                           "BUG live_done but branches_to_explore %d\n",
16231                                           br);
16232                                 free_verifier_state(&sl->state, false);
16233                                 kfree(sl);
16234                                 env->peak_states--;
16235                         } else {
16236                                 /* cannot free this state, since parentage chain may
16237                                  * walk it later. Add it for free_list instead to
16238                                  * be freed at the end of verification
16239                                  */
16240                                 sl->next = env->free_list;
16241                                 env->free_list = sl;
16242                         }
16243                         sl = *pprev;
16244                         continue;
16245                 }
16246 next:
16247                 pprev = &sl->next;
16248                 sl = *pprev;
16249         }
16250
16251         if (env->max_states_per_insn < states_cnt)
16252                 env->max_states_per_insn = states_cnt;
16253
16254         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16255                 return 0;
16256
16257         if (!add_new_state)
16258                 return 0;
16259
16260         /* There were no equivalent states, remember the current one.
16261          * Technically the current state is not proven to be safe yet,
16262          * but it will either reach outer most bpf_exit (which means it's safe)
16263          * or it will be rejected. When there are no loops the verifier won't be
16264          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16265          * again on the way to bpf_exit.
16266          * When looping the sl->state.branches will be > 0 and this state
16267          * will not be considered for equivalence until branches == 0.
16268          */
16269         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16270         if (!new_sl)
16271                 return -ENOMEM;
16272         env->total_states++;
16273         env->peak_states++;
16274         env->prev_jmps_processed = env->jmps_processed;
16275         env->prev_insn_processed = env->insn_processed;
16276
16277         /* forget precise markings we inherited, see __mark_chain_precision */
16278         if (env->bpf_capable)
16279                 mark_all_scalars_imprecise(env, cur);
16280
16281         /* add new state to the head of linked list */
16282         new = &new_sl->state;
16283         err = copy_verifier_state(new, cur);
16284         if (err) {
16285                 free_verifier_state(new, false);
16286                 kfree(new_sl);
16287                 return err;
16288         }
16289         new->insn_idx = insn_idx;
16290         WARN_ONCE(new->branches != 1,
16291                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16292
16293         cur->parent = new;
16294         cur->first_insn_idx = insn_idx;
16295         clear_jmp_history(cur);
16296         new_sl->next = *explored_state(env, insn_idx);
16297         *explored_state(env, insn_idx) = new_sl;
16298         /* connect new state to parentage chain. Current frame needs all
16299          * registers connected. Only r6 - r9 of the callers are alive (pushed
16300          * to the stack implicitly by JITs) so in callers' frames connect just
16301          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16302          * the state of the call instruction (with WRITTEN set), and r0 comes
16303          * from callee with its full parentage chain, anyway.
16304          */
16305         /* clear write marks in current state: the writes we did are not writes
16306          * our child did, so they don't screen off its reads from us.
16307          * (There are no read marks in current state, because reads always mark
16308          * their parent and current state never has children yet.  Only
16309          * explored_states can get read marks.)
16310          */
16311         for (j = 0; j <= cur->curframe; j++) {
16312                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16313                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16314                 for (i = 0; i < BPF_REG_FP; i++)
16315                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16316         }
16317
16318         /* all stack frames are accessible from callee, clear them all */
16319         for (j = 0; j <= cur->curframe; j++) {
16320                 struct bpf_func_state *frame = cur->frame[j];
16321                 struct bpf_func_state *newframe = new->frame[j];
16322
16323                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16324                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16325                         frame->stack[i].spilled_ptr.parent =
16326                                                 &newframe->stack[i].spilled_ptr;
16327                 }
16328         }
16329         return 0;
16330 }
16331
16332 /* Return true if it's OK to have the same insn return a different type. */
16333 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16334 {
16335         switch (base_type(type)) {
16336         case PTR_TO_CTX:
16337         case PTR_TO_SOCKET:
16338         case PTR_TO_SOCK_COMMON:
16339         case PTR_TO_TCP_SOCK:
16340         case PTR_TO_XDP_SOCK:
16341         case PTR_TO_BTF_ID:
16342                 return false;
16343         default:
16344                 return true;
16345         }
16346 }
16347
16348 /* If an instruction was previously used with particular pointer types, then we
16349  * need to be careful to avoid cases such as the below, where it may be ok
16350  * for one branch accessing the pointer, but not ok for the other branch:
16351  *
16352  * R1 = sock_ptr
16353  * goto X;
16354  * ...
16355  * R1 = some_other_valid_ptr;
16356  * goto X;
16357  * ...
16358  * R2 = *(u32 *)(R1 + 0);
16359  */
16360 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16361 {
16362         return src != prev && (!reg_type_mismatch_ok(src) ||
16363                                !reg_type_mismatch_ok(prev));
16364 }
16365
16366 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16367                              bool allow_trust_missmatch)
16368 {
16369         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16370
16371         if (*prev_type == NOT_INIT) {
16372                 /* Saw a valid insn
16373                  * dst_reg = *(u32 *)(src_reg + off)
16374                  * save type to validate intersecting paths
16375                  */
16376                 *prev_type = type;
16377         } else if (reg_type_mismatch(type, *prev_type)) {
16378                 /* Abuser program is trying to use the same insn
16379                  * dst_reg = *(u32*) (src_reg + off)
16380                  * with different pointer types:
16381                  * src_reg == ctx in one branch and
16382                  * src_reg == stack|map in some other branch.
16383                  * Reject it.
16384                  */
16385                 if (allow_trust_missmatch &&
16386                     base_type(type) == PTR_TO_BTF_ID &&
16387                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16388                         /*
16389                          * Have to support a use case when one path through
16390                          * the program yields TRUSTED pointer while another
16391                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16392                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16393                          */
16394                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16395                 } else {
16396                         verbose(env, "same insn cannot be used with different pointers\n");
16397                         return -EINVAL;
16398                 }
16399         }
16400
16401         return 0;
16402 }
16403
16404 static int do_check(struct bpf_verifier_env *env)
16405 {
16406         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16407         struct bpf_verifier_state *state = env->cur_state;
16408         struct bpf_insn *insns = env->prog->insnsi;
16409         struct bpf_reg_state *regs;
16410         int insn_cnt = env->prog->len;
16411         bool do_print_state = false;
16412         int prev_insn_idx = -1;
16413
16414         for (;;) {
16415                 struct bpf_insn *insn;
16416                 u8 class;
16417                 int err;
16418
16419                 env->prev_insn_idx = prev_insn_idx;
16420                 if (env->insn_idx >= insn_cnt) {
16421                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16422                                 env->insn_idx, insn_cnt);
16423                         return -EFAULT;
16424                 }
16425
16426                 insn = &insns[env->insn_idx];
16427                 class = BPF_CLASS(insn->code);
16428
16429                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16430                         verbose(env,
16431                                 "BPF program is too large. Processed %d insn\n",
16432                                 env->insn_processed);
16433                         return -E2BIG;
16434                 }
16435
16436                 state->last_insn_idx = env->prev_insn_idx;
16437
16438                 if (is_prune_point(env, env->insn_idx)) {
16439                         err = is_state_visited(env, env->insn_idx);
16440                         if (err < 0)
16441                                 return err;
16442                         if (err == 1) {
16443                                 /* found equivalent state, can prune the search */
16444                                 if (env->log.level & BPF_LOG_LEVEL) {
16445                                         if (do_print_state)
16446                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16447                                                         env->prev_insn_idx, env->insn_idx,
16448                                                         env->cur_state->speculative ?
16449                                                         " (speculative execution)" : "");
16450                                         else
16451                                                 verbose(env, "%d: safe\n", env->insn_idx);
16452                                 }
16453                                 goto process_bpf_exit;
16454                         }
16455                 }
16456
16457                 if (is_jmp_point(env, env->insn_idx)) {
16458                         err = push_jmp_history(env, state);
16459                         if (err)
16460                                 return err;
16461                 }
16462
16463                 if (signal_pending(current))
16464                         return -EAGAIN;
16465
16466                 if (need_resched())
16467                         cond_resched();
16468
16469                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16470                         verbose(env, "\nfrom %d to %d%s:",
16471                                 env->prev_insn_idx, env->insn_idx,
16472                                 env->cur_state->speculative ?
16473                                 " (speculative execution)" : "");
16474                         print_verifier_state(env, state->frame[state->curframe], true);
16475                         do_print_state = false;
16476                 }
16477
16478                 if (env->log.level & BPF_LOG_LEVEL) {
16479                         const struct bpf_insn_cbs cbs = {
16480                                 .cb_call        = disasm_kfunc_name,
16481                                 .cb_print       = verbose,
16482                                 .private_data   = env,
16483                         };
16484
16485                         if (verifier_state_scratched(env))
16486                                 print_insn_state(env, state->frame[state->curframe]);
16487
16488                         verbose_linfo(env, env->insn_idx, "; ");
16489                         env->prev_log_pos = env->log.end_pos;
16490                         verbose(env, "%d: ", env->insn_idx);
16491                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16492                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16493                         env->prev_log_pos = env->log.end_pos;
16494                 }
16495
16496                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16497                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16498                                                            env->prev_insn_idx);
16499                         if (err)
16500                                 return err;
16501                 }
16502
16503                 regs = cur_regs(env);
16504                 sanitize_mark_insn_seen(env);
16505                 prev_insn_idx = env->insn_idx;
16506
16507                 if (class == BPF_ALU || class == BPF_ALU64) {
16508                         err = check_alu_op(env, insn);
16509                         if (err)
16510                                 return err;
16511
16512                 } else if (class == BPF_LDX) {
16513                         enum bpf_reg_type src_reg_type;
16514
16515                         /* check for reserved fields is already done */
16516
16517                         /* check src operand */
16518                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16519                         if (err)
16520                                 return err;
16521
16522                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16523                         if (err)
16524                                 return err;
16525
16526                         src_reg_type = regs[insn->src_reg].type;
16527
16528                         /* check that memory (src_reg + off) is readable,
16529                          * the state of dst_reg will be updated by this func
16530                          */
16531                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16532                                                insn->off, BPF_SIZE(insn->code),
16533                                                BPF_READ, insn->dst_reg, false,
16534                                                BPF_MODE(insn->code) == BPF_MEMSX);
16535                         if (err)
16536                                 return err;
16537
16538                         err = save_aux_ptr_type(env, src_reg_type, true);
16539                         if (err)
16540                                 return err;
16541                 } else if (class == BPF_STX) {
16542                         enum bpf_reg_type dst_reg_type;
16543
16544                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16545                                 err = check_atomic(env, env->insn_idx, insn);
16546                                 if (err)
16547                                         return err;
16548                                 env->insn_idx++;
16549                                 continue;
16550                         }
16551
16552                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16553                                 verbose(env, "BPF_STX uses reserved fields\n");
16554                                 return -EINVAL;
16555                         }
16556
16557                         /* check src1 operand */
16558                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16559                         if (err)
16560                                 return err;
16561                         /* check src2 operand */
16562                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16563                         if (err)
16564                                 return err;
16565
16566                         dst_reg_type = regs[insn->dst_reg].type;
16567
16568                         /* check that memory (dst_reg + off) is writeable */
16569                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16570                                                insn->off, BPF_SIZE(insn->code),
16571                                                BPF_WRITE, insn->src_reg, false, false);
16572                         if (err)
16573                                 return err;
16574
16575                         err = save_aux_ptr_type(env, dst_reg_type, false);
16576                         if (err)
16577                                 return err;
16578                 } else if (class == BPF_ST) {
16579                         enum bpf_reg_type dst_reg_type;
16580
16581                         if (BPF_MODE(insn->code) != BPF_MEM ||
16582                             insn->src_reg != BPF_REG_0) {
16583                                 verbose(env, "BPF_ST uses reserved fields\n");
16584                                 return -EINVAL;
16585                         }
16586                         /* check src operand */
16587                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16588                         if (err)
16589                                 return err;
16590
16591                         dst_reg_type = regs[insn->dst_reg].type;
16592
16593                         /* check that memory (dst_reg + off) is writeable */
16594                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16595                                                insn->off, BPF_SIZE(insn->code),
16596                                                BPF_WRITE, -1, false, false);
16597                         if (err)
16598                                 return err;
16599
16600                         err = save_aux_ptr_type(env, dst_reg_type, false);
16601                         if (err)
16602                                 return err;
16603                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16604                         u8 opcode = BPF_OP(insn->code);
16605
16606                         env->jmps_processed++;
16607                         if (opcode == BPF_CALL) {
16608                                 if (BPF_SRC(insn->code) != BPF_K ||
16609                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16610                                      && insn->off != 0) ||
16611                                     (insn->src_reg != BPF_REG_0 &&
16612                                      insn->src_reg != BPF_PSEUDO_CALL &&
16613                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16614                                     insn->dst_reg != BPF_REG_0 ||
16615                                     class == BPF_JMP32) {
16616                                         verbose(env, "BPF_CALL uses reserved fields\n");
16617                                         return -EINVAL;
16618                                 }
16619
16620                                 if (env->cur_state->active_lock.ptr) {
16621                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16622                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16623                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16624                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16625                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16626                                                 return -EINVAL;
16627                                         }
16628                                 }
16629                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16630                                         err = check_func_call(env, insn, &env->insn_idx);
16631                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16632                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16633                                 else
16634                                         err = check_helper_call(env, insn, &env->insn_idx);
16635                                 if (err)
16636                                         return err;
16637
16638                                 mark_reg_scratched(env, BPF_REG_0);
16639                         } else if (opcode == BPF_JA) {
16640                                 if (BPF_SRC(insn->code) != BPF_K ||
16641                                     insn->imm != 0 ||
16642                                     insn->src_reg != BPF_REG_0 ||
16643                                     insn->dst_reg != BPF_REG_0 ||
16644                                     class == BPF_JMP32) {
16645                                         verbose(env, "BPF_JA uses reserved fields\n");
16646                                         return -EINVAL;
16647                                 }
16648
16649                                 env->insn_idx += insn->off + 1;
16650                                 continue;
16651
16652                         } else if (opcode == BPF_EXIT) {
16653                                 if (BPF_SRC(insn->code) != BPF_K ||
16654                                     insn->imm != 0 ||
16655                                     insn->src_reg != BPF_REG_0 ||
16656                                     insn->dst_reg != BPF_REG_0 ||
16657                                     class == BPF_JMP32) {
16658                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16659                                         return -EINVAL;
16660                                 }
16661
16662                                 if (env->cur_state->active_lock.ptr &&
16663                                     !in_rbtree_lock_required_cb(env)) {
16664                                         verbose(env, "bpf_spin_unlock is missing\n");
16665                                         return -EINVAL;
16666                                 }
16667
16668                                 if (env->cur_state->active_rcu_lock) {
16669                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16670                                         return -EINVAL;
16671                                 }
16672
16673                                 /* We must do check_reference_leak here before
16674                                  * prepare_func_exit to handle the case when
16675                                  * state->curframe > 0, it may be a callback
16676                                  * function, for which reference_state must
16677                                  * match caller reference state when it exits.
16678                                  */
16679                                 err = check_reference_leak(env);
16680                                 if (err)
16681                                         return err;
16682
16683                                 if (state->curframe) {
16684                                         /* exit from nested function */
16685                                         err = prepare_func_exit(env, &env->insn_idx);
16686                                         if (err)
16687                                                 return err;
16688                                         do_print_state = true;
16689                                         continue;
16690                                 }
16691
16692                                 err = check_return_code(env);
16693                                 if (err)
16694                                         return err;
16695 process_bpf_exit:
16696                                 mark_verifier_state_scratched(env);
16697                                 update_branch_counts(env, env->cur_state);
16698                                 err = pop_stack(env, &prev_insn_idx,
16699                                                 &env->insn_idx, pop_log);
16700                                 if (err < 0) {
16701                                         if (err != -ENOENT)
16702                                                 return err;
16703                                         break;
16704                                 } else {
16705                                         do_print_state = true;
16706                                         continue;
16707                                 }
16708                         } else {
16709                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16710                                 if (err)
16711                                         return err;
16712                         }
16713                 } else if (class == BPF_LD) {
16714                         u8 mode = BPF_MODE(insn->code);
16715
16716                         if (mode == BPF_ABS || mode == BPF_IND) {
16717                                 err = check_ld_abs(env, insn);
16718                                 if (err)
16719                                         return err;
16720
16721                         } else if (mode == BPF_IMM) {
16722                                 err = check_ld_imm(env, insn);
16723                                 if (err)
16724                                         return err;
16725
16726                                 env->insn_idx++;
16727                                 sanitize_mark_insn_seen(env);
16728                         } else {
16729                                 verbose(env, "invalid BPF_LD mode\n");
16730                                 return -EINVAL;
16731                         }
16732                 } else {
16733                         verbose(env, "unknown insn class %d\n", class);
16734                         return -EINVAL;
16735                 }
16736
16737                 env->insn_idx++;
16738         }
16739
16740         return 0;
16741 }
16742
16743 static int find_btf_percpu_datasec(struct btf *btf)
16744 {
16745         const struct btf_type *t;
16746         const char *tname;
16747         int i, n;
16748
16749         /*
16750          * Both vmlinux and module each have their own ".data..percpu"
16751          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16752          * types to look at only module's own BTF types.
16753          */
16754         n = btf_nr_types(btf);
16755         if (btf_is_module(btf))
16756                 i = btf_nr_types(btf_vmlinux);
16757         else
16758                 i = 1;
16759
16760         for(; i < n; i++) {
16761                 t = btf_type_by_id(btf, i);
16762                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16763                         continue;
16764
16765                 tname = btf_name_by_offset(btf, t->name_off);
16766                 if (!strcmp(tname, ".data..percpu"))
16767                         return i;
16768         }
16769
16770         return -ENOENT;
16771 }
16772
16773 /* replace pseudo btf_id with kernel symbol address */
16774 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16775                                struct bpf_insn *insn,
16776                                struct bpf_insn_aux_data *aux)
16777 {
16778         const struct btf_var_secinfo *vsi;
16779         const struct btf_type *datasec;
16780         struct btf_mod_pair *btf_mod;
16781         const struct btf_type *t;
16782         const char *sym_name;
16783         bool percpu = false;
16784         u32 type, id = insn->imm;
16785         struct btf *btf;
16786         s32 datasec_id;
16787         u64 addr;
16788         int i, btf_fd, err;
16789
16790         btf_fd = insn[1].imm;
16791         if (btf_fd) {
16792                 btf = btf_get_by_fd(btf_fd);
16793                 if (IS_ERR(btf)) {
16794                         verbose(env, "invalid module BTF object FD specified.\n");
16795                         return -EINVAL;
16796                 }
16797         } else {
16798                 if (!btf_vmlinux) {
16799                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16800                         return -EINVAL;
16801                 }
16802                 btf = btf_vmlinux;
16803                 btf_get(btf);
16804         }
16805
16806         t = btf_type_by_id(btf, id);
16807         if (!t) {
16808                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16809                 err = -ENOENT;
16810                 goto err_put;
16811         }
16812
16813         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16814                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16815                 err = -EINVAL;
16816                 goto err_put;
16817         }
16818
16819         sym_name = btf_name_by_offset(btf, t->name_off);
16820         addr = kallsyms_lookup_name(sym_name);
16821         if (!addr) {
16822                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16823                         sym_name);
16824                 err = -ENOENT;
16825                 goto err_put;
16826         }
16827         insn[0].imm = (u32)addr;
16828         insn[1].imm = addr >> 32;
16829
16830         if (btf_type_is_func(t)) {
16831                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16832                 aux->btf_var.mem_size = 0;
16833                 goto check_btf;
16834         }
16835
16836         datasec_id = find_btf_percpu_datasec(btf);
16837         if (datasec_id > 0) {
16838                 datasec = btf_type_by_id(btf, datasec_id);
16839                 for_each_vsi(i, datasec, vsi) {
16840                         if (vsi->type == id) {
16841                                 percpu = true;
16842                                 break;
16843                         }
16844                 }
16845         }
16846
16847         type = t->type;
16848         t = btf_type_skip_modifiers(btf, type, NULL);
16849         if (percpu) {
16850                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16851                 aux->btf_var.btf = btf;
16852                 aux->btf_var.btf_id = type;
16853         } else if (!btf_type_is_struct(t)) {
16854                 const struct btf_type *ret;
16855                 const char *tname;
16856                 u32 tsize;
16857
16858                 /* resolve the type size of ksym. */
16859                 ret = btf_resolve_size(btf, t, &tsize);
16860                 if (IS_ERR(ret)) {
16861                         tname = btf_name_by_offset(btf, t->name_off);
16862                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16863                                 tname, PTR_ERR(ret));
16864                         err = -EINVAL;
16865                         goto err_put;
16866                 }
16867                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16868                 aux->btf_var.mem_size = tsize;
16869         } else {
16870                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16871                 aux->btf_var.btf = btf;
16872                 aux->btf_var.btf_id = type;
16873         }
16874 check_btf:
16875         /* check whether we recorded this BTF (and maybe module) already */
16876         for (i = 0; i < env->used_btf_cnt; i++) {
16877                 if (env->used_btfs[i].btf == btf) {
16878                         btf_put(btf);
16879                         return 0;
16880                 }
16881         }
16882
16883         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16884                 err = -E2BIG;
16885                 goto err_put;
16886         }
16887
16888         btf_mod = &env->used_btfs[env->used_btf_cnt];
16889         btf_mod->btf = btf;
16890         btf_mod->module = NULL;
16891
16892         /* if we reference variables from kernel module, bump its refcount */
16893         if (btf_is_module(btf)) {
16894                 btf_mod->module = btf_try_get_module(btf);
16895                 if (!btf_mod->module) {
16896                         err = -ENXIO;
16897                         goto err_put;
16898                 }
16899         }
16900
16901         env->used_btf_cnt++;
16902
16903         return 0;
16904 err_put:
16905         btf_put(btf);
16906         return err;
16907 }
16908
16909 static bool is_tracing_prog_type(enum bpf_prog_type type)
16910 {
16911         switch (type) {
16912         case BPF_PROG_TYPE_KPROBE:
16913         case BPF_PROG_TYPE_TRACEPOINT:
16914         case BPF_PROG_TYPE_PERF_EVENT:
16915         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16916         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16917                 return true;
16918         default:
16919                 return false;
16920         }
16921 }
16922
16923 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16924                                         struct bpf_map *map,
16925                                         struct bpf_prog *prog)
16926
16927 {
16928         enum bpf_prog_type prog_type = resolve_prog_type(prog);
16929
16930         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
16931             btf_record_has_field(map->record, BPF_RB_ROOT)) {
16932                 if (is_tracing_prog_type(prog_type)) {
16933                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
16934                         return -EINVAL;
16935                 }
16936         }
16937
16938         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
16939                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
16940                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
16941                         return -EINVAL;
16942                 }
16943
16944                 if (is_tracing_prog_type(prog_type)) {
16945                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
16946                         return -EINVAL;
16947                 }
16948
16949                 if (prog->aux->sleepable) {
16950                         verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n");
16951                         return -EINVAL;
16952                 }
16953         }
16954
16955         if (btf_record_has_field(map->record, BPF_TIMER)) {
16956                 if (is_tracing_prog_type(prog_type)) {
16957                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
16958                         return -EINVAL;
16959                 }
16960         }
16961
16962         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
16963             !bpf_offload_prog_map_match(prog, map)) {
16964                 verbose(env, "offload device mismatch between prog and map\n");
16965                 return -EINVAL;
16966         }
16967
16968         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
16969                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
16970                 return -EINVAL;
16971         }
16972
16973         if (prog->aux->sleepable)
16974                 switch (map->map_type) {
16975                 case BPF_MAP_TYPE_HASH:
16976                 case BPF_MAP_TYPE_LRU_HASH:
16977                 case BPF_MAP_TYPE_ARRAY:
16978                 case BPF_MAP_TYPE_PERCPU_HASH:
16979                 case BPF_MAP_TYPE_PERCPU_ARRAY:
16980                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
16981                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
16982                 case BPF_MAP_TYPE_HASH_OF_MAPS:
16983                 case BPF_MAP_TYPE_RINGBUF:
16984                 case BPF_MAP_TYPE_USER_RINGBUF:
16985                 case BPF_MAP_TYPE_INODE_STORAGE:
16986                 case BPF_MAP_TYPE_SK_STORAGE:
16987                 case BPF_MAP_TYPE_TASK_STORAGE:
16988                 case BPF_MAP_TYPE_CGRP_STORAGE:
16989                         break;
16990                 default:
16991                         verbose(env,
16992                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
16993                         return -EINVAL;
16994                 }
16995
16996         return 0;
16997 }
16998
16999 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17000 {
17001         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17002                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17003 }
17004
17005 /* find and rewrite pseudo imm in ld_imm64 instructions:
17006  *
17007  * 1. if it accesses map FD, replace it with actual map pointer.
17008  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17009  *
17010  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17011  */
17012 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17013 {
17014         struct bpf_insn *insn = env->prog->insnsi;
17015         int insn_cnt = env->prog->len;
17016         int i, j, err;
17017
17018         err = bpf_prog_calc_tag(env->prog);
17019         if (err)
17020                 return err;
17021
17022         for (i = 0; i < insn_cnt; i++, insn++) {
17023                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17024                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17025                     insn->imm != 0)) {
17026                         verbose(env, "BPF_LDX uses reserved fields\n");
17027                         return -EINVAL;
17028                 }
17029
17030                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17031                         struct bpf_insn_aux_data *aux;
17032                         struct bpf_map *map;
17033                         struct fd f;
17034                         u64 addr;
17035                         u32 fd;
17036
17037                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17038                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17039                             insn[1].off != 0) {
17040                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17041                                 return -EINVAL;
17042                         }
17043
17044                         if (insn[0].src_reg == 0)
17045                                 /* valid generic load 64-bit imm */
17046                                 goto next_insn;
17047
17048                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17049                                 aux = &env->insn_aux_data[i];
17050                                 err = check_pseudo_btf_id(env, insn, aux);
17051                                 if (err)
17052                                         return err;
17053                                 goto next_insn;
17054                         }
17055
17056                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17057                                 aux = &env->insn_aux_data[i];
17058                                 aux->ptr_type = PTR_TO_FUNC;
17059                                 goto next_insn;
17060                         }
17061
17062                         /* In final convert_pseudo_ld_imm64() step, this is
17063                          * converted into regular 64-bit imm load insn.
17064                          */
17065                         switch (insn[0].src_reg) {
17066                         case BPF_PSEUDO_MAP_VALUE:
17067                         case BPF_PSEUDO_MAP_IDX_VALUE:
17068                                 break;
17069                         case BPF_PSEUDO_MAP_FD:
17070                         case BPF_PSEUDO_MAP_IDX:
17071                                 if (insn[1].imm == 0)
17072                                         break;
17073                                 fallthrough;
17074                         default:
17075                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17076                                 return -EINVAL;
17077                         }
17078
17079                         switch (insn[0].src_reg) {
17080                         case BPF_PSEUDO_MAP_IDX_VALUE:
17081                         case BPF_PSEUDO_MAP_IDX:
17082                                 if (bpfptr_is_null(env->fd_array)) {
17083                                         verbose(env, "fd_idx without fd_array is invalid\n");
17084                                         return -EPROTO;
17085                                 }
17086                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17087                                                             insn[0].imm * sizeof(fd),
17088                                                             sizeof(fd)))
17089                                         return -EFAULT;
17090                                 break;
17091                         default:
17092                                 fd = insn[0].imm;
17093                                 break;
17094                         }
17095
17096                         f = fdget(fd);
17097                         map = __bpf_map_get(f);
17098                         if (IS_ERR(map)) {
17099                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17100                                         insn[0].imm);
17101                                 return PTR_ERR(map);
17102                         }
17103
17104                         err = check_map_prog_compatibility(env, map, env->prog);
17105                         if (err) {
17106                                 fdput(f);
17107                                 return err;
17108                         }
17109
17110                         aux = &env->insn_aux_data[i];
17111                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17112                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17113                                 addr = (unsigned long)map;
17114                         } else {
17115                                 u32 off = insn[1].imm;
17116
17117                                 if (off >= BPF_MAX_VAR_OFF) {
17118                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17119                                         fdput(f);
17120                                         return -EINVAL;
17121                                 }
17122
17123                                 if (!map->ops->map_direct_value_addr) {
17124                                         verbose(env, "no direct value access support for this map type\n");
17125                                         fdput(f);
17126                                         return -EINVAL;
17127                                 }
17128
17129                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17130                                 if (err) {
17131                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17132                                                 map->value_size, off);
17133                                         fdput(f);
17134                                         return err;
17135                                 }
17136
17137                                 aux->map_off = off;
17138                                 addr += off;
17139                         }
17140
17141                         insn[0].imm = (u32)addr;
17142                         insn[1].imm = addr >> 32;
17143
17144                         /* check whether we recorded this map already */
17145                         for (j = 0; j < env->used_map_cnt; j++) {
17146                                 if (env->used_maps[j] == map) {
17147                                         aux->map_index = j;
17148                                         fdput(f);
17149                                         goto next_insn;
17150                                 }
17151                         }
17152
17153                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17154                                 fdput(f);
17155                                 return -E2BIG;
17156                         }
17157
17158                         /* hold the map. If the program is rejected by verifier,
17159                          * the map will be released by release_maps() or it
17160                          * will be used by the valid program until it's unloaded
17161                          * and all maps are released in free_used_maps()
17162                          */
17163                         bpf_map_inc(map);
17164
17165                         aux->map_index = env->used_map_cnt;
17166                         env->used_maps[env->used_map_cnt++] = map;
17167
17168                         if (bpf_map_is_cgroup_storage(map) &&
17169                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
17170                                 verbose(env, "only one cgroup storage of each type is allowed\n");
17171                                 fdput(f);
17172                                 return -EBUSY;
17173                         }
17174
17175                         fdput(f);
17176 next_insn:
17177                         insn++;
17178                         i++;
17179                         continue;
17180                 }
17181
17182                 /* Basic sanity check before we invest more work here. */
17183                 if (!bpf_opcode_in_insntable(insn->code)) {
17184                         verbose(env, "unknown opcode %02x\n", insn->code);
17185                         return -EINVAL;
17186                 }
17187         }
17188
17189         /* now all pseudo BPF_LD_IMM64 instructions load valid
17190          * 'struct bpf_map *' into a register instead of user map_fd.
17191          * These pointers will be used later by verifier to validate map access.
17192          */
17193         return 0;
17194 }
17195
17196 /* drop refcnt of maps used by the rejected program */
17197 static void release_maps(struct bpf_verifier_env *env)
17198 {
17199         __bpf_free_used_maps(env->prog->aux, env->used_maps,
17200                              env->used_map_cnt);
17201 }
17202
17203 /* drop refcnt of maps used by the rejected program */
17204 static void release_btfs(struct bpf_verifier_env *env)
17205 {
17206         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17207                              env->used_btf_cnt);
17208 }
17209
17210 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17211 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17212 {
17213         struct bpf_insn *insn = env->prog->insnsi;
17214         int insn_cnt = env->prog->len;
17215         int i;
17216
17217         for (i = 0; i < insn_cnt; i++, insn++) {
17218                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17219                         continue;
17220                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17221                         continue;
17222                 insn->src_reg = 0;
17223         }
17224 }
17225
17226 /* single env->prog->insni[off] instruction was replaced with the range
17227  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17228  * [0, off) and [off, end) to new locations, so the patched range stays zero
17229  */
17230 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17231                                  struct bpf_insn_aux_data *new_data,
17232                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17233 {
17234         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17235         struct bpf_insn *insn = new_prog->insnsi;
17236         u32 old_seen = old_data[off].seen;
17237         u32 prog_len;
17238         int i;
17239
17240         /* aux info at OFF always needs adjustment, no matter fast path
17241          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17242          * original insn at old prog.
17243          */
17244         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17245
17246         if (cnt == 1)
17247                 return;
17248         prog_len = new_prog->len;
17249
17250         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17251         memcpy(new_data + off + cnt - 1, old_data + off,
17252                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17253         for (i = off; i < off + cnt - 1; i++) {
17254                 /* Expand insni[off]'s seen count to the patched range. */
17255                 new_data[i].seen = old_seen;
17256                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17257         }
17258         env->insn_aux_data = new_data;
17259         vfree(old_data);
17260 }
17261
17262 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17263 {
17264         int i;
17265
17266         if (len == 1)
17267                 return;
17268         /* NOTE: fake 'exit' subprog should be updated as well. */
17269         for (i = 0; i <= env->subprog_cnt; i++) {
17270                 if (env->subprog_info[i].start <= off)
17271                         continue;
17272                 env->subprog_info[i].start += len - 1;
17273         }
17274 }
17275
17276 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17277 {
17278         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17279         int i, sz = prog->aux->size_poke_tab;
17280         struct bpf_jit_poke_descriptor *desc;
17281
17282         for (i = 0; i < sz; i++) {
17283                 desc = &tab[i];
17284                 if (desc->insn_idx <= off)
17285                         continue;
17286                 desc->insn_idx += len - 1;
17287         }
17288 }
17289
17290 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17291                                             const struct bpf_insn *patch, u32 len)
17292 {
17293         struct bpf_prog *new_prog;
17294         struct bpf_insn_aux_data *new_data = NULL;
17295
17296         if (len > 1) {
17297                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17298                                               sizeof(struct bpf_insn_aux_data)));
17299                 if (!new_data)
17300                         return NULL;
17301         }
17302
17303         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17304         if (IS_ERR(new_prog)) {
17305                 if (PTR_ERR(new_prog) == -ERANGE)
17306                         verbose(env,
17307                                 "insn %d cannot be patched due to 16-bit range\n",
17308                                 env->insn_aux_data[off].orig_idx);
17309                 vfree(new_data);
17310                 return NULL;
17311         }
17312         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17313         adjust_subprog_starts(env, off, len);
17314         adjust_poke_descs(new_prog, off, len);
17315         return new_prog;
17316 }
17317
17318 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17319                                               u32 off, u32 cnt)
17320 {
17321         int i, j;
17322
17323         /* find first prog starting at or after off (first to remove) */
17324         for (i = 0; i < env->subprog_cnt; i++)
17325                 if (env->subprog_info[i].start >= off)
17326                         break;
17327         /* find first prog starting at or after off + cnt (first to stay) */
17328         for (j = i; j < env->subprog_cnt; j++)
17329                 if (env->subprog_info[j].start >= off + cnt)
17330                         break;
17331         /* if j doesn't start exactly at off + cnt, we are just removing
17332          * the front of previous prog
17333          */
17334         if (env->subprog_info[j].start != off + cnt)
17335                 j--;
17336
17337         if (j > i) {
17338                 struct bpf_prog_aux *aux = env->prog->aux;
17339                 int move;
17340
17341                 /* move fake 'exit' subprog as well */
17342                 move = env->subprog_cnt + 1 - j;
17343
17344                 memmove(env->subprog_info + i,
17345                         env->subprog_info + j,
17346                         sizeof(*env->subprog_info) * move);
17347                 env->subprog_cnt -= j - i;
17348
17349                 /* remove func_info */
17350                 if (aux->func_info) {
17351                         move = aux->func_info_cnt - j;
17352
17353                         memmove(aux->func_info + i,
17354                                 aux->func_info + j,
17355                                 sizeof(*aux->func_info) * move);
17356                         aux->func_info_cnt -= j - i;
17357                         /* func_info->insn_off is set after all code rewrites,
17358                          * in adjust_btf_func() - no need to adjust
17359                          */
17360                 }
17361         } else {
17362                 /* convert i from "first prog to remove" to "first to adjust" */
17363                 if (env->subprog_info[i].start == off)
17364                         i++;
17365         }
17366
17367         /* update fake 'exit' subprog as well */
17368         for (; i <= env->subprog_cnt; i++)
17369                 env->subprog_info[i].start -= cnt;
17370
17371         return 0;
17372 }
17373
17374 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17375                                       u32 cnt)
17376 {
17377         struct bpf_prog *prog = env->prog;
17378         u32 i, l_off, l_cnt, nr_linfo;
17379         struct bpf_line_info *linfo;
17380
17381         nr_linfo = prog->aux->nr_linfo;
17382         if (!nr_linfo)
17383                 return 0;
17384
17385         linfo = prog->aux->linfo;
17386
17387         /* find first line info to remove, count lines to be removed */
17388         for (i = 0; i < nr_linfo; i++)
17389                 if (linfo[i].insn_off >= off)
17390                         break;
17391
17392         l_off = i;
17393         l_cnt = 0;
17394         for (; i < nr_linfo; i++)
17395                 if (linfo[i].insn_off < off + cnt)
17396                         l_cnt++;
17397                 else
17398                         break;
17399
17400         /* First live insn doesn't match first live linfo, it needs to "inherit"
17401          * last removed linfo.  prog is already modified, so prog->len == off
17402          * means no live instructions after (tail of the program was removed).
17403          */
17404         if (prog->len != off && l_cnt &&
17405             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17406                 l_cnt--;
17407                 linfo[--i].insn_off = off + cnt;
17408         }
17409
17410         /* remove the line info which refer to the removed instructions */
17411         if (l_cnt) {
17412                 memmove(linfo + l_off, linfo + i,
17413                         sizeof(*linfo) * (nr_linfo - i));
17414
17415                 prog->aux->nr_linfo -= l_cnt;
17416                 nr_linfo = prog->aux->nr_linfo;
17417         }
17418
17419         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17420         for (i = l_off; i < nr_linfo; i++)
17421                 linfo[i].insn_off -= cnt;
17422
17423         /* fix up all subprogs (incl. 'exit') which start >= off */
17424         for (i = 0; i <= env->subprog_cnt; i++)
17425                 if (env->subprog_info[i].linfo_idx > l_off) {
17426                         /* program may have started in the removed region but
17427                          * may not be fully removed
17428                          */
17429                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17430                                 env->subprog_info[i].linfo_idx -= l_cnt;
17431                         else
17432                                 env->subprog_info[i].linfo_idx = l_off;
17433                 }
17434
17435         return 0;
17436 }
17437
17438 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17439 {
17440         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17441         unsigned int orig_prog_len = env->prog->len;
17442         int err;
17443
17444         if (bpf_prog_is_offloaded(env->prog->aux))
17445                 bpf_prog_offload_remove_insns(env, off, cnt);
17446
17447         err = bpf_remove_insns(env->prog, off, cnt);
17448         if (err)
17449                 return err;
17450
17451         err = adjust_subprog_starts_after_remove(env, off, cnt);
17452         if (err)
17453                 return err;
17454
17455         err = bpf_adj_linfo_after_remove(env, off, cnt);
17456         if (err)
17457                 return err;
17458
17459         memmove(aux_data + off, aux_data + off + cnt,
17460                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17461
17462         return 0;
17463 }
17464
17465 /* The verifier does more data flow analysis than llvm and will not
17466  * explore branches that are dead at run time. Malicious programs can
17467  * have dead code too. Therefore replace all dead at-run-time code
17468  * with 'ja -1'.
17469  *
17470  * Just nops are not optimal, e.g. if they would sit at the end of the
17471  * program and through another bug we would manage to jump there, then
17472  * we'd execute beyond program memory otherwise. Returning exception
17473  * code also wouldn't work since we can have subprogs where the dead
17474  * code could be located.
17475  */
17476 static void sanitize_dead_code(struct bpf_verifier_env *env)
17477 {
17478         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17479         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17480         struct bpf_insn *insn = env->prog->insnsi;
17481         const int insn_cnt = env->prog->len;
17482         int i;
17483
17484         for (i = 0; i < insn_cnt; i++) {
17485                 if (aux_data[i].seen)
17486                         continue;
17487                 memcpy(insn + i, &trap, sizeof(trap));
17488                 aux_data[i].zext_dst = false;
17489         }
17490 }
17491
17492 static bool insn_is_cond_jump(u8 code)
17493 {
17494         u8 op;
17495
17496         if (BPF_CLASS(code) == BPF_JMP32)
17497                 return true;
17498
17499         if (BPF_CLASS(code) != BPF_JMP)
17500                 return false;
17501
17502         op = BPF_OP(code);
17503         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17504 }
17505
17506 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17507 {
17508         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17509         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17510         struct bpf_insn *insn = env->prog->insnsi;
17511         const int insn_cnt = env->prog->len;
17512         int i;
17513
17514         for (i = 0; i < insn_cnt; i++, insn++) {
17515                 if (!insn_is_cond_jump(insn->code))
17516                         continue;
17517
17518                 if (!aux_data[i + 1].seen)
17519                         ja.off = insn->off;
17520                 else if (!aux_data[i + 1 + insn->off].seen)
17521                         ja.off = 0;
17522                 else
17523                         continue;
17524
17525                 if (bpf_prog_is_offloaded(env->prog->aux))
17526                         bpf_prog_offload_replace_insn(env, i, &ja);
17527
17528                 memcpy(insn, &ja, sizeof(ja));
17529         }
17530 }
17531
17532 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17533 {
17534         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17535         int insn_cnt = env->prog->len;
17536         int i, err;
17537
17538         for (i = 0; i < insn_cnt; i++) {
17539                 int j;
17540
17541                 j = 0;
17542                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17543                         j++;
17544                 if (!j)
17545                         continue;
17546
17547                 err = verifier_remove_insns(env, i, j);
17548                 if (err)
17549                         return err;
17550                 insn_cnt = env->prog->len;
17551         }
17552
17553         return 0;
17554 }
17555
17556 static int opt_remove_nops(struct bpf_verifier_env *env)
17557 {
17558         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17559         struct bpf_insn *insn = env->prog->insnsi;
17560         int insn_cnt = env->prog->len;
17561         int i, err;
17562
17563         for (i = 0; i < insn_cnt; i++) {
17564                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17565                         continue;
17566
17567                 err = verifier_remove_insns(env, i, 1);
17568                 if (err)
17569                         return err;
17570                 insn_cnt--;
17571                 i--;
17572         }
17573
17574         return 0;
17575 }
17576
17577 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17578                                          const union bpf_attr *attr)
17579 {
17580         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17581         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17582         int i, patch_len, delta = 0, len = env->prog->len;
17583         struct bpf_insn *insns = env->prog->insnsi;
17584         struct bpf_prog *new_prog;
17585         bool rnd_hi32;
17586
17587         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17588         zext_patch[1] = BPF_ZEXT_REG(0);
17589         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17590         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17591         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17592         for (i = 0; i < len; i++) {
17593                 int adj_idx = i + delta;
17594                 struct bpf_insn insn;
17595                 int load_reg;
17596
17597                 insn = insns[adj_idx];
17598                 load_reg = insn_def_regno(&insn);
17599                 if (!aux[adj_idx].zext_dst) {
17600                         u8 code, class;
17601                         u32 imm_rnd;
17602
17603                         if (!rnd_hi32)
17604                                 continue;
17605
17606                         code = insn.code;
17607                         class = BPF_CLASS(code);
17608                         if (load_reg == -1)
17609                                 continue;
17610
17611                         /* NOTE: arg "reg" (the fourth one) is only used for
17612                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17613                          *       here.
17614                          */
17615                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17616                                 if (class == BPF_LD &&
17617                                     BPF_MODE(code) == BPF_IMM)
17618                                         i++;
17619                                 continue;
17620                         }
17621
17622                         /* ctx load could be transformed into wider load. */
17623                         if (class == BPF_LDX &&
17624                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17625                                 continue;
17626
17627                         imm_rnd = get_random_u32();
17628                         rnd_hi32_patch[0] = insn;
17629                         rnd_hi32_patch[1].imm = imm_rnd;
17630                         rnd_hi32_patch[3].dst_reg = load_reg;
17631                         patch = rnd_hi32_patch;
17632                         patch_len = 4;
17633                         goto apply_patch_buffer;
17634                 }
17635
17636                 /* Add in an zero-extend instruction if a) the JIT has requested
17637                  * it or b) it's a CMPXCHG.
17638                  *
17639                  * The latter is because: BPF_CMPXCHG always loads a value into
17640                  * R0, therefore always zero-extends. However some archs'
17641                  * equivalent instruction only does this load when the
17642                  * comparison is successful. This detail of CMPXCHG is
17643                  * orthogonal to the general zero-extension behaviour of the
17644                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17645                  */
17646                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17647                         continue;
17648
17649                 /* Zero-extension is done by the caller. */
17650                 if (bpf_pseudo_kfunc_call(&insn))
17651                         continue;
17652
17653                 if (WARN_ON(load_reg == -1)) {
17654                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17655                         return -EFAULT;
17656                 }
17657
17658                 zext_patch[0] = insn;
17659                 zext_patch[1].dst_reg = load_reg;
17660                 zext_patch[1].src_reg = load_reg;
17661                 patch = zext_patch;
17662                 patch_len = 2;
17663 apply_patch_buffer:
17664                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17665                 if (!new_prog)
17666                         return -ENOMEM;
17667                 env->prog = new_prog;
17668                 insns = new_prog->insnsi;
17669                 aux = env->insn_aux_data;
17670                 delta += patch_len - 1;
17671         }
17672
17673         return 0;
17674 }
17675
17676 /* convert load instructions that access fields of a context type into a
17677  * sequence of instructions that access fields of the underlying structure:
17678  *     struct __sk_buff    -> struct sk_buff
17679  *     struct bpf_sock_ops -> struct sock
17680  */
17681 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17682 {
17683         const struct bpf_verifier_ops *ops = env->ops;
17684         int i, cnt, size, ctx_field_size, delta = 0;
17685         const int insn_cnt = env->prog->len;
17686         struct bpf_insn insn_buf[16], *insn;
17687         u32 target_size, size_default, off;
17688         struct bpf_prog *new_prog;
17689         enum bpf_access_type type;
17690         bool is_narrower_load;
17691
17692         if (ops->gen_prologue || env->seen_direct_write) {
17693                 if (!ops->gen_prologue) {
17694                         verbose(env, "bpf verifier is misconfigured\n");
17695                         return -EINVAL;
17696                 }
17697                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17698                                         env->prog);
17699                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17700                         verbose(env, "bpf verifier is misconfigured\n");
17701                         return -EINVAL;
17702                 } else if (cnt) {
17703                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17704                         if (!new_prog)
17705                                 return -ENOMEM;
17706
17707                         env->prog = new_prog;
17708                         delta += cnt - 1;
17709                 }
17710         }
17711
17712         if (bpf_prog_is_offloaded(env->prog->aux))
17713                 return 0;
17714
17715         insn = env->prog->insnsi + delta;
17716
17717         for (i = 0; i < insn_cnt; i++, insn++) {
17718                 bpf_convert_ctx_access_t convert_ctx_access;
17719                 u8 mode;
17720
17721                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17722                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17723                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17724                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17725                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17726                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17727                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17728                         type = BPF_READ;
17729                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17730                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17731                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17732                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17733                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17734                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17735                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17736                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17737                         type = BPF_WRITE;
17738                 } else {
17739                         continue;
17740                 }
17741
17742                 if (type == BPF_WRITE &&
17743                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17744                         struct bpf_insn patch[] = {
17745                                 *insn,
17746                                 BPF_ST_NOSPEC(),
17747                         };
17748
17749                         cnt = ARRAY_SIZE(patch);
17750                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17751                         if (!new_prog)
17752                                 return -ENOMEM;
17753
17754                         delta    += cnt - 1;
17755                         env->prog = new_prog;
17756                         insn      = new_prog->insnsi + i + delta;
17757                         continue;
17758                 }
17759
17760                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17761                 case PTR_TO_CTX:
17762                         if (!ops->convert_ctx_access)
17763                                 continue;
17764                         convert_ctx_access = ops->convert_ctx_access;
17765                         break;
17766                 case PTR_TO_SOCKET:
17767                 case PTR_TO_SOCK_COMMON:
17768                         convert_ctx_access = bpf_sock_convert_ctx_access;
17769                         break;
17770                 case PTR_TO_TCP_SOCK:
17771                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17772                         break;
17773                 case PTR_TO_XDP_SOCK:
17774                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17775                         break;
17776                 case PTR_TO_BTF_ID:
17777                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17778                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17779                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17780                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17781                  * any faults for loads into such types. BPF_WRITE is disallowed
17782                  * for this case.
17783                  */
17784                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17785                         if (type == BPF_READ) {
17786                                 if (BPF_MODE(insn->code) == BPF_MEM)
17787                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
17788                                                      BPF_SIZE((insn)->code);
17789                                 else
17790                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17791                                                      BPF_SIZE((insn)->code);
17792                                 env->prog->aux->num_exentries++;
17793                         }
17794                         continue;
17795                 default:
17796                         continue;
17797                 }
17798
17799                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17800                 size = BPF_LDST_BYTES(insn);
17801                 mode = BPF_MODE(insn->code);
17802
17803                 /* If the read access is a narrower load of the field,
17804                  * convert to a 4/8-byte load, to minimum program type specific
17805                  * convert_ctx_access changes. If conversion is successful,
17806                  * we will apply proper mask to the result.
17807                  */
17808                 is_narrower_load = size < ctx_field_size;
17809                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17810                 off = insn->off;
17811                 if (is_narrower_load) {
17812                         u8 size_code;
17813
17814                         if (type == BPF_WRITE) {
17815                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17816                                 return -EINVAL;
17817                         }
17818
17819                         size_code = BPF_H;
17820                         if (ctx_field_size == 4)
17821                                 size_code = BPF_W;
17822                         else if (ctx_field_size == 8)
17823                                 size_code = BPF_DW;
17824
17825                         insn->off = off & ~(size_default - 1);
17826                         insn->code = BPF_LDX | BPF_MEM | size_code;
17827                 }
17828
17829                 target_size = 0;
17830                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17831                                          &target_size);
17832                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17833                     (ctx_field_size && !target_size)) {
17834                         verbose(env, "bpf verifier is misconfigured\n");
17835                         return -EINVAL;
17836                 }
17837
17838                 if (is_narrower_load && size < target_size) {
17839                         u8 shift = bpf_ctx_narrow_access_offset(
17840                                 off, size, size_default) * 8;
17841                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17842                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17843                                 return -EINVAL;
17844                         }
17845                         if (ctx_field_size <= 4) {
17846                                 if (shift)
17847                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17848                                                                         insn->dst_reg,
17849                                                                         shift);
17850                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17851                                                                 (1 << size * 8) - 1);
17852                         } else {
17853                                 if (shift)
17854                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17855                                                                         insn->dst_reg,
17856                                                                         shift);
17857                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17858                                                                 (1ULL << size * 8) - 1);
17859                         }
17860                 }
17861                 if (mode == BPF_MEMSX)
17862                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17863                                                        insn->dst_reg, insn->dst_reg,
17864                                                        size * 8, 0);
17865
17866                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17867                 if (!new_prog)
17868                         return -ENOMEM;
17869
17870                 delta += cnt - 1;
17871
17872                 /* keep walking new program and skip insns we just inserted */
17873                 env->prog = new_prog;
17874                 insn      = new_prog->insnsi + i + delta;
17875         }
17876
17877         return 0;
17878 }
17879
17880 static int jit_subprogs(struct bpf_verifier_env *env)
17881 {
17882         struct bpf_prog *prog = env->prog, **func, *tmp;
17883         int i, j, subprog_start, subprog_end = 0, len, subprog;
17884         struct bpf_map *map_ptr;
17885         struct bpf_insn *insn;
17886         void *old_bpf_func;
17887         int err, num_exentries;
17888
17889         if (env->subprog_cnt <= 1)
17890                 return 0;
17891
17892         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17893                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17894                         continue;
17895
17896                 /* Upon error here we cannot fall back to interpreter but
17897                  * need a hard reject of the program. Thus -EFAULT is
17898                  * propagated in any case.
17899                  */
17900                 subprog = find_subprog(env, i + insn->imm + 1);
17901                 if (subprog < 0) {
17902                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17903                                   i + insn->imm + 1);
17904                         return -EFAULT;
17905                 }
17906                 /* temporarily remember subprog id inside insn instead of
17907                  * aux_data, since next loop will split up all insns into funcs
17908                  */
17909                 insn->off = subprog;
17910                 /* remember original imm in case JIT fails and fallback
17911                  * to interpreter will be needed
17912                  */
17913                 env->insn_aux_data[i].call_imm = insn->imm;
17914                 /* point imm to __bpf_call_base+1 from JITs point of view */
17915                 insn->imm = 1;
17916                 if (bpf_pseudo_func(insn))
17917                         /* jit (e.g. x86_64) may emit fewer instructions
17918                          * if it learns a u32 imm is the same as a u64 imm.
17919                          * Force a non zero here.
17920                          */
17921                         insn[1].imm = 1;
17922         }
17923
17924         err = bpf_prog_alloc_jited_linfo(prog);
17925         if (err)
17926                 goto out_undo_insn;
17927
17928         err = -ENOMEM;
17929         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17930         if (!func)
17931                 goto out_undo_insn;
17932
17933         for (i = 0; i < env->subprog_cnt; i++) {
17934                 subprog_start = subprog_end;
17935                 subprog_end = env->subprog_info[i + 1].start;
17936
17937                 len = subprog_end - subprog_start;
17938                 /* bpf_prog_run() doesn't call subprogs directly,
17939                  * hence main prog stats include the runtime of subprogs.
17940                  * subprogs don't have IDs and not reachable via prog_get_next_id
17941                  * func[i]->stats will never be accessed and stays NULL
17942                  */
17943                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
17944                 if (!func[i])
17945                         goto out_free;
17946                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
17947                        len * sizeof(struct bpf_insn));
17948                 func[i]->type = prog->type;
17949                 func[i]->len = len;
17950                 if (bpf_prog_calc_tag(func[i]))
17951                         goto out_free;
17952                 func[i]->is_func = 1;
17953                 func[i]->aux->func_idx = i;
17954                 /* Below members will be freed only at prog->aux */
17955                 func[i]->aux->btf = prog->aux->btf;
17956                 func[i]->aux->func_info = prog->aux->func_info;
17957                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
17958                 func[i]->aux->poke_tab = prog->aux->poke_tab;
17959                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
17960
17961                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
17962                         struct bpf_jit_poke_descriptor *poke;
17963
17964                         poke = &prog->aux->poke_tab[j];
17965                         if (poke->insn_idx < subprog_end &&
17966                             poke->insn_idx >= subprog_start)
17967                                 poke->aux = func[i]->aux;
17968                 }
17969
17970                 func[i]->aux->name[0] = 'F';
17971                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
17972                 func[i]->jit_requested = 1;
17973                 func[i]->blinding_requested = prog->blinding_requested;
17974                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
17975                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
17976                 func[i]->aux->linfo = prog->aux->linfo;
17977                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
17978                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
17979                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
17980                 num_exentries = 0;
17981                 insn = func[i]->insnsi;
17982                 for (j = 0; j < func[i]->len; j++, insn++) {
17983                         if (BPF_CLASS(insn->code) == BPF_LDX &&
17984                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
17985                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
17986                                 num_exentries++;
17987                 }
17988                 func[i]->aux->num_exentries = num_exentries;
17989                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
17990                 func[i] = bpf_int_jit_compile(func[i]);
17991                 if (!func[i]->jited) {
17992                         err = -ENOTSUPP;
17993                         goto out_free;
17994                 }
17995                 cond_resched();
17996         }
17997
17998         /* at this point all bpf functions were successfully JITed
17999          * now populate all bpf_calls with correct addresses and
18000          * run last pass of JIT
18001          */
18002         for (i = 0; i < env->subprog_cnt; i++) {
18003                 insn = func[i]->insnsi;
18004                 for (j = 0; j < func[i]->len; j++, insn++) {
18005                         if (bpf_pseudo_func(insn)) {
18006                                 subprog = insn->off;
18007                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18008                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18009                                 continue;
18010                         }
18011                         if (!bpf_pseudo_call(insn))
18012                                 continue;
18013                         subprog = insn->off;
18014                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18015                 }
18016
18017                 /* we use the aux data to keep a list of the start addresses
18018                  * of the JITed images for each function in the program
18019                  *
18020                  * for some architectures, such as powerpc64, the imm field
18021                  * might not be large enough to hold the offset of the start
18022                  * address of the callee's JITed image from __bpf_call_base
18023                  *
18024                  * in such cases, we can lookup the start address of a callee
18025                  * by using its subprog id, available from the off field of
18026                  * the call instruction, as an index for this list
18027                  */
18028                 func[i]->aux->func = func;
18029                 func[i]->aux->func_cnt = env->subprog_cnt;
18030         }
18031         for (i = 0; i < env->subprog_cnt; i++) {
18032                 old_bpf_func = func[i]->bpf_func;
18033                 tmp = bpf_int_jit_compile(func[i]);
18034                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18035                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18036                         err = -ENOTSUPP;
18037                         goto out_free;
18038                 }
18039                 cond_resched();
18040         }
18041
18042         /* finally lock prog and jit images for all functions and
18043          * populate kallsysm. Begin at the first subprogram, since
18044          * bpf_prog_load will add the kallsyms for the main program.
18045          */
18046         for (i = 1; i < env->subprog_cnt; i++) {
18047                 bpf_prog_lock_ro(func[i]);
18048                 bpf_prog_kallsyms_add(func[i]);
18049         }
18050
18051         /* Last step: make now unused interpreter insns from main
18052          * prog consistent for later dump requests, so they can
18053          * later look the same as if they were interpreted only.
18054          */
18055         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18056                 if (bpf_pseudo_func(insn)) {
18057                         insn[0].imm = env->insn_aux_data[i].call_imm;
18058                         insn[1].imm = insn->off;
18059                         insn->off = 0;
18060                         continue;
18061                 }
18062                 if (!bpf_pseudo_call(insn))
18063                         continue;
18064                 insn->off = env->insn_aux_data[i].call_imm;
18065                 subprog = find_subprog(env, i + insn->off + 1);
18066                 insn->imm = subprog;
18067         }
18068
18069         prog->jited = 1;
18070         prog->bpf_func = func[0]->bpf_func;
18071         prog->jited_len = func[0]->jited_len;
18072         prog->aux->extable = func[0]->aux->extable;
18073         prog->aux->num_exentries = func[0]->aux->num_exentries;
18074         prog->aux->func = func;
18075         prog->aux->func_cnt = env->subprog_cnt;
18076         bpf_prog_jit_attempt_done(prog);
18077         return 0;
18078 out_free:
18079         /* We failed JIT'ing, so at this point we need to unregister poke
18080          * descriptors from subprogs, so that kernel is not attempting to
18081          * patch it anymore as we're freeing the subprog JIT memory.
18082          */
18083         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18084                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18085                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18086         }
18087         /* At this point we're guaranteed that poke descriptors are not
18088          * live anymore. We can just unlink its descriptor table as it's
18089          * released with the main prog.
18090          */
18091         for (i = 0; i < env->subprog_cnt; i++) {
18092                 if (!func[i])
18093                         continue;
18094                 func[i]->aux->poke_tab = NULL;
18095                 bpf_jit_free(func[i]);
18096         }
18097         kfree(func);
18098 out_undo_insn:
18099         /* cleanup main prog to be interpreted */
18100         prog->jit_requested = 0;
18101         prog->blinding_requested = 0;
18102         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18103                 if (!bpf_pseudo_call(insn))
18104                         continue;
18105                 insn->off = 0;
18106                 insn->imm = env->insn_aux_data[i].call_imm;
18107         }
18108         bpf_prog_jit_attempt_done(prog);
18109         return err;
18110 }
18111
18112 static int fixup_call_args(struct bpf_verifier_env *env)
18113 {
18114 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18115         struct bpf_prog *prog = env->prog;
18116         struct bpf_insn *insn = prog->insnsi;
18117         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18118         int i, depth;
18119 #endif
18120         int err = 0;
18121
18122         if (env->prog->jit_requested &&
18123             !bpf_prog_is_offloaded(env->prog->aux)) {
18124                 err = jit_subprogs(env);
18125                 if (err == 0)
18126                         return 0;
18127                 if (err == -EFAULT)
18128                         return err;
18129         }
18130 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18131         if (has_kfunc_call) {
18132                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18133                 return -EINVAL;
18134         }
18135         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18136                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18137                  * have to be rejected, since interpreter doesn't support them yet.
18138                  */
18139                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18140                 return -EINVAL;
18141         }
18142         for (i = 0; i < prog->len; i++, insn++) {
18143                 if (bpf_pseudo_func(insn)) {
18144                         /* When JIT fails the progs with callback calls
18145                          * have to be rejected, since interpreter doesn't support them yet.
18146                          */
18147                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18148                         return -EINVAL;
18149                 }
18150
18151                 if (!bpf_pseudo_call(insn))
18152                         continue;
18153                 depth = get_callee_stack_depth(env, insn, i);
18154                 if (depth < 0)
18155                         return depth;
18156                 bpf_patch_call_args(insn, depth);
18157         }
18158         err = 0;
18159 #endif
18160         return err;
18161 }
18162
18163 /* replace a generic kfunc with a specialized version if necessary */
18164 static void specialize_kfunc(struct bpf_verifier_env *env,
18165                              u32 func_id, u16 offset, unsigned long *addr)
18166 {
18167         struct bpf_prog *prog = env->prog;
18168         bool seen_direct_write;
18169         void *xdp_kfunc;
18170         bool is_rdonly;
18171
18172         if (bpf_dev_bound_kfunc_id(func_id)) {
18173                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18174                 if (xdp_kfunc) {
18175                         *addr = (unsigned long)xdp_kfunc;
18176                         return;
18177                 }
18178                 /* fallback to default kfunc when not supported by netdev */
18179         }
18180
18181         if (offset)
18182                 return;
18183
18184         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18185                 seen_direct_write = env->seen_direct_write;
18186                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18187
18188                 if (is_rdonly)
18189                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18190
18191                 /* restore env->seen_direct_write to its original value, since
18192                  * may_access_direct_pkt_data mutates it
18193                  */
18194                 env->seen_direct_write = seen_direct_write;
18195         }
18196 }
18197
18198 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18199                                             u16 struct_meta_reg,
18200                                             u16 node_offset_reg,
18201                                             struct bpf_insn *insn,
18202                                             struct bpf_insn *insn_buf,
18203                                             int *cnt)
18204 {
18205         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18206         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18207
18208         insn_buf[0] = addr[0];
18209         insn_buf[1] = addr[1];
18210         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18211         insn_buf[3] = *insn;
18212         *cnt = 4;
18213 }
18214
18215 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18216                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18217 {
18218         const struct bpf_kfunc_desc *desc;
18219
18220         if (!insn->imm) {
18221                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18222                 return -EINVAL;
18223         }
18224
18225         *cnt = 0;
18226
18227         /* insn->imm has the btf func_id. Replace it with an offset relative to
18228          * __bpf_call_base, unless the JIT needs to call functions that are
18229          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18230          */
18231         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18232         if (!desc) {
18233                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18234                         insn->imm);
18235                 return -EFAULT;
18236         }
18237
18238         if (!bpf_jit_supports_far_kfunc_call())
18239                 insn->imm = BPF_CALL_IMM(desc->addr);
18240         if (insn->off)
18241                 return 0;
18242         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18243                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18244                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18245                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18246
18247                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18248                 insn_buf[1] = addr[0];
18249                 insn_buf[2] = addr[1];
18250                 insn_buf[3] = *insn;
18251                 *cnt = 4;
18252         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18253                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18254                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18255                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18256
18257                 insn_buf[0] = addr[0];
18258                 insn_buf[1] = addr[1];
18259                 insn_buf[2] = *insn;
18260                 *cnt = 3;
18261         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18262                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18263                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18264                 int struct_meta_reg = BPF_REG_3;
18265                 int node_offset_reg = BPF_REG_4;
18266
18267                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18268                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18269                         struct_meta_reg = BPF_REG_4;
18270                         node_offset_reg = BPF_REG_5;
18271                 }
18272
18273                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18274                                                 node_offset_reg, insn, insn_buf, cnt);
18275         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18276                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18277                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18278                 *cnt = 1;
18279         }
18280         return 0;
18281 }
18282
18283 /* Do various post-verification rewrites in a single program pass.
18284  * These rewrites simplify JIT and interpreter implementations.
18285  */
18286 static int do_misc_fixups(struct bpf_verifier_env *env)
18287 {
18288         struct bpf_prog *prog = env->prog;
18289         enum bpf_attach_type eatype = prog->expected_attach_type;
18290         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18291         struct bpf_insn *insn = prog->insnsi;
18292         const struct bpf_func_proto *fn;
18293         const int insn_cnt = prog->len;
18294         const struct bpf_map_ops *ops;
18295         struct bpf_insn_aux_data *aux;
18296         struct bpf_insn insn_buf[16];
18297         struct bpf_prog *new_prog;
18298         struct bpf_map *map_ptr;
18299         int i, ret, cnt, delta = 0;
18300
18301         for (i = 0; i < insn_cnt; i++, insn++) {
18302                 /* Make divide-by-zero exceptions impossible. */
18303                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18304                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18305                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18306                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18307                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18308                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18309                         struct bpf_insn *patchlet;
18310                         struct bpf_insn chk_and_div[] = {
18311                                 /* [R,W]x div 0 -> 0 */
18312                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18313                                              BPF_JNE | BPF_K, insn->src_reg,
18314                                              0, 2, 0),
18315                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18316                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18317                                 *insn,
18318                         };
18319                         struct bpf_insn chk_and_mod[] = {
18320                                 /* [R,W]x mod 0 -> [R,W]x */
18321                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18322                                              BPF_JEQ | BPF_K, insn->src_reg,
18323                                              0, 1 + (is64 ? 0 : 1), 0),
18324                                 *insn,
18325                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18326                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18327                         };
18328
18329                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18330                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18331                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18332
18333                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18334                         if (!new_prog)
18335                                 return -ENOMEM;
18336
18337                         delta    += cnt - 1;
18338                         env->prog = prog = new_prog;
18339                         insn      = new_prog->insnsi + i + delta;
18340                         continue;
18341                 }
18342
18343                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18344                 if (BPF_CLASS(insn->code) == BPF_LD &&
18345                     (BPF_MODE(insn->code) == BPF_ABS ||
18346                      BPF_MODE(insn->code) == BPF_IND)) {
18347                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18348                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18349                                 verbose(env, "bpf verifier is misconfigured\n");
18350                                 return -EINVAL;
18351                         }
18352
18353                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18354                         if (!new_prog)
18355                                 return -ENOMEM;
18356
18357                         delta    += cnt - 1;
18358                         env->prog = prog = new_prog;
18359                         insn      = new_prog->insnsi + i + delta;
18360                         continue;
18361                 }
18362
18363                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18364                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18365                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18366                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18367                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18368                         struct bpf_insn *patch = &insn_buf[0];
18369                         bool issrc, isneg, isimm;
18370                         u32 off_reg;
18371
18372                         aux = &env->insn_aux_data[i + delta];
18373                         if (!aux->alu_state ||
18374                             aux->alu_state == BPF_ALU_NON_POINTER)
18375                                 continue;
18376
18377                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18378                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18379                                 BPF_ALU_SANITIZE_SRC;
18380                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18381
18382                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18383                         if (isimm) {
18384                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18385                         } else {
18386                                 if (isneg)
18387                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18388                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18389                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18390                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18391                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18392                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18393                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18394                         }
18395                         if (!issrc)
18396                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18397                         insn->src_reg = BPF_REG_AX;
18398                         if (isneg)
18399                                 insn->code = insn->code == code_add ?
18400                                              code_sub : code_add;
18401                         *patch++ = *insn;
18402                         if (issrc && isneg && !isimm)
18403                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18404                         cnt = patch - insn_buf;
18405
18406                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18407                         if (!new_prog)
18408                                 return -ENOMEM;
18409
18410                         delta    += cnt - 1;
18411                         env->prog = prog = new_prog;
18412                         insn      = new_prog->insnsi + i + delta;
18413                         continue;
18414                 }
18415
18416                 if (insn->code != (BPF_JMP | BPF_CALL))
18417                         continue;
18418                 if (insn->src_reg == BPF_PSEUDO_CALL)
18419                         continue;
18420                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18421                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18422                         if (ret)
18423                                 return ret;
18424                         if (cnt == 0)
18425                                 continue;
18426
18427                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18428                         if (!new_prog)
18429                                 return -ENOMEM;
18430
18431                         delta    += cnt - 1;
18432                         env->prog = prog = new_prog;
18433                         insn      = new_prog->insnsi + i + delta;
18434                         continue;
18435                 }
18436
18437                 if (insn->imm == BPF_FUNC_get_route_realm)
18438                         prog->dst_needed = 1;
18439                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18440                         bpf_user_rnd_init_once();
18441                 if (insn->imm == BPF_FUNC_override_return)
18442                         prog->kprobe_override = 1;
18443                 if (insn->imm == BPF_FUNC_tail_call) {
18444                         /* If we tail call into other programs, we
18445                          * cannot make any assumptions since they can
18446                          * be replaced dynamically during runtime in
18447                          * the program array.
18448                          */
18449                         prog->cb_access = 1;
18450                         if (!allow_tail_call_in_subprogs(env))
18451                                 prog->aux->stack_depth = MAX_BPF_STACK;
18452                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18453
18454                         /* mark bpf_tail_call as different opcode to avoid
18455                          * conditional branch in the interpreter for every normal
18456                          * call and to prevent accidental JITing by JIT compiler
18457                          * that doesn't support bpf_tail_call yet
18458                          */
18459                         insn->imm = 0;
18460                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18461
18462                         aux = &env->insn_aux_data[i + delta];
18463                         if (env->bpf_capable && !prog->blinding_requested &&
18464                             prog->jit_requested &&
18465                             !bpf_map_key_poisoned(aux) &&
18466                             !bpf_map_ptr_poisoned(aux) &&
18467                             !bpf_map_ptr_unpriv(aux)) {
18468                                 struct bpf_jit_poke_descriptor desc = {
18469                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18470                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18471                                         .tail_call.key = bpf_map_key_immediate(aux),
18472                                         .insn_idx = i + delta,
18473                                 };
18474
18475                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18476                                 if (ret < 0) {
18477                                         verbose(env, "adding tail call poke descriptor failed\n");
18478                                         return ret;
18479                                 }
18480
18481                                 insn->imm = ret + 1;
18482                                 continue;
18483                         }
18484
18485                         if (!bpf_map_ptr_unpriv(aux))
18486                                 continue;
18487
18488                         /* instead of changing every JIT dealing with tail_call
18489                          * emit two extra insns:
18490                          * if (index >= max_entries) goto out;
18491                          * index &= array->index_mask;
18492                          * to avoid out-of-bounds cpu speculation
18493                          */
18494                         if (bpf_map_ptr_poisoned(aux)) {
18495                                 verbose(env, "tail_call abusing map_ptr\n");
18496                                 return -EINVAL;
18497                         }
18498
18499                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18500                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18501                                                   map_ptr->max_entries, 2);
18502                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18503                                                     container_of(map_ptr,
18504                                                                  struct bpf_array,
18505                                                                  map)->index_mask);
18506                         insn_buf[2] = *insn;
18507                         cnt = 3;
18508                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18509                         if (!new_prog)
18510                                 return -ENOMEM;
18511
18512                         delta    += cnt - 1;
18513                         env->prog = prog = new_prog;
18514                         insn      = new_prog->insnsi + i + delta;
18515                         continue;
18516                 }
18517
18518                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18519                         /* The verifier will process callback_fn as many times as necessary
18520                          * with different maps and the register states prepared by
18521                          * set_timer_callback_state will be accurate.
18522                          *
18523                          * The following use case is valid:
18524                          *   map1 is shared by prog1, prog2, prog3.
18525                          *   prog1 calls bpf_timer_init for some map1 elements
18526                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18527                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18528                          *   prog3 calls bpf_timer_start for some map1 elements.
18529                          *     Those that were not both bpf_timer_init-ed and
18530                          *     bpf_timer_set_callback-ed will return -EINVAL.
18531                          */
18532                         struct bpf_insn ld_addrs[2] = {
18533                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18534                         };
18535
18536                         insn_buf[0] = ld_addrs[0];
18537                         insn_buf[1] = ld_addrs[1];
18538                         insn_buf[2] = *insn;
18539                         cnt = 3;
18540
18541                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18542                         if (!new_prog)
18543                                 return -ENOMEM;
18544
18545                         delta    += cnt - 1;
18546                         env->prog = prog = new_prog;
18547                         insn      = new_prog->insnsi + i + delta;
18548                         goto patch_call_imm;
18549                 }
18550
18551                 if (is_storage_get_function(insn->imm)) {
18552                         if (!env->prog->aux->sleepable ||
18553                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18554                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18555                         else
18556                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18557                         insn_buf[1] = *insn;
18558                         cnt = 2;
18559
18560                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18561                         if (!new_prog)
18562                                 return -ENOMEM;
18563
18564                         delta += cnt - 1;
18565                         env->prog = prog = new_prog;
18566                         insn = new_prog->insnsi + i + delta;
18567                         goto patch_call_imm;
18568                 }
18569
18570                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18571                  * and other inlining handlers are currently limited to 64 bit
18572                  * only.
18573                  */
18574                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18575                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18576                      insn->imm == BPF_FUNC_map_update_elem ||
18577                      insn->imm == BPF_FUNC_map_delete_elem ||
18578                      insn->imm == BPF_FUNC_map_push_elem   ||
18579                      insn->imm == BPF_FUNC_map_pop_elem    ||
18580                      insn->imm == BPF_FUNC_map_peek_elem   ||
18581                      insn->imm == BPF_FUNC_redirect_map    ||
18582                      insn->imm == BPF_FUNC_for_each_map_elem ||
18583                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18584                         aux = &env->insn_aux_data[i + delta];
18585                         if (bpf_map_ptr_poisoned(aux))
18586                                 goto patch_call_imm;
18587
18588                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18589                         ops = map_ptr->ops;
18590                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18591                             ops->map_gen_lookup) {
18592                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18593                                 if (cnt == -EOPNOTSUPP)
18594                                         goto patch_map_ops_generic;
18595                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18596                                         verbose(env, "bpf verifier is misconfigured\n");
18597                                         return -EINVAL;
18598                                 }
18599
18600                                 new_prog = bpf_patch_insn_data(env, i + delta,
18601                                                                insn_buf, cnt);
18602                                 if (!new_prog)
18603                                         return -ENOMEM;
18604
18605                                 delta    += cnt - 1;
18606                                 env->prog = prog = new_prog;
18607                                 insn      = new_prog->insnsi + i + delta;
18608                                 continue;
18609                         }
18610
18611                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18612                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18613                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18614                                      (long (*)(struct bpf_map *map, void *key))NULL));
18615                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18616                                      (long (*)(struct bpf_map *map, void *key, void *value,
18617                                               u64 flags))NULL));
18618                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18619                                      (long (*)(struct bpf_map *map, void *value,
18620                                               u64 flags))NULL));
18621                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18622                                      (long (*)(struct bpf_map *map, void *value))NULL));
18623                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18624                                      (long (*)(struct bpf_map *map, void *value))NULL));
18625                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18626                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18627                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18628                                      (long (*)(struct bpf_map *map,
18629                                               bpf_callback_t callback_fn,
18630                                               void *callback_ctx,
18631                                               u64 flags))NULL));
18632                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18633                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18634
18635 patch_map_ops_generic:
18636                         switch (insn->imm) {
18637                         case BPF_FUNC_map_lookup_elem:
18638                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18639                                 continue;
18640                         case BPF_FUNC_map_update_elem:
18641                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18642                                 continue;
18643                         case BPF_FUNC_map_delete_elem:
18644                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18645                                 continue;
18646                         case BPF_FUNC_map_push_elem:
18647                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18648                                 continue;
18649                         case BPF_FUNC_map_pop_elem:
18650                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18651                                 continue;
18652                         case BPF_FUNC_map_peek_elem:
18653                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18654                                 continue;
18655                         case BPF_FUNC_redirect_map:
18656                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18657                                 continue;
18658                         case BPF_FUNC_for_each_map_elem:
18659                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18660                                 continue;
18661                         case BPF_FUNC_map_lookup_percpu_elem:
18662                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18663                                 continue;
18664                         }
18665
18666                         goto patch_call_imm;
18667                 }
18668
18669                 /* Implement bpf_jiffies64 inline. */
18670                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18671                     insn->imm == BPF_FUNC_jiffies64) {
18672                         struct bpf_insn ld_jiffies_addr[2] = {
18673                                 BPF_LD_IMM64(BPF_REG_0,
18674                                              (unsigned long)&jiffies),
18675                         };
18676
18677                         insn_buf[0] = ld_jiffies_addr[0];
18678                         insn_buf[1] = ld_jiffies_addr[1];
18679                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18680                                                   BPF_REG_0, 0);
18681                         cnt = 3;
18682
18683                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18684                                                        cnt);
18685                         if (!new_prog)
18686                                 return -ENOMEM;
18687
18688                         delta    += cnt - 1;
18689                         env->prog = prog = new_prog;
18690                         insn      = new_prog->insnsi + i + delta;
18691                         continue;
18692                 }
18693
18694                 /* Implement bpf_get_func_arg inline. */
18695                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18696                     insn->imm == BPF_FUNC_get_func_arg) {
18697                         /* Load nr_args from ctx - 8 */
18698                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18699                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18700                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18701                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18702                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18703                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18704                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18705                         insn_buf[7] = BPF_JMP_A(1);
18706                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18707                         cnt = 9;
18708
18709                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18710                         if (!new_prog)
18711                                 return -ENOMEM;
18712
18713                         delta    += cnt - 1;
18714                         env->prog = prog = new_prog;
18715                         insn      = new_prog->insnsi + i + delta;
18716                         continue;
18717                 }
18718
18719                 /* Implement bpf_get_func_ret inline. */
18720                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18721                     insn->imm == BPF_FUNC_get_func_ret) {
18722                         if (eatype == BPF_TRACE_FEXIT ||
18723                             eatype == BPF_MODIFY_RETURN) {
18724                                 /* Load nr_args from ctx - 8 */
18725                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18726                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18727                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18728                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18729                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18730                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18731                                 cnt = 6;
18732                         } else {
18733                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18734                                 cnt = 1;
18735                         }
18736
18737                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18738                         if (!new_prog)
18739                                 return -ENOMEM;
18740
18741                         delta    += cnt - 1;
18742                         env->prog = prog = new_prog;
18743                         insn      = new_prog->insnsi + i + delta;
18744                         continue;
18745                 }
18746
18747                 /* Implement get_func_arg_cnt inline. */
18748                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18749                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18750                         /* Load nr_args from ctx - 8 */
18751                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18752
18753                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18754                         if (!new_prog)
18755                                 return -ENOMEM;
18756
18757                         env->prog = prog = new_prog;
18758                         insn      = new_prog->insnsi + i + delta;
18759                         continue;
18760                 }
18761
18762                 /* Implement bpf_get_func_ip inline. */
18763                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18764                     insn->imm == BPF_FUNC_get_func_ip) {
18765                         /* Load IP address from ctx - 16 */
18766                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18767
18768                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18769                         if (!new_prog)
18770                                 return -ENOMEM;
18771
18772                         env->prog = prog = new_prog;
18773                         insn      = new_prog->insnsi + i + delta;
18774                         continue;
18775                 }
18776
18777 patch_call_imm:
18778                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18779                 /* all functions that have prototype and verifier allowed
18780                  * programs to call them, must be real in-kernel functions
18781                  */
18782                 if (!fn->func) {
18783                         verbose(env,
18784                                 "kernel subsystem misconfigured func %s#%d\n",
18785                                 func_id_name(insn->imm), insn->imm);
18786                         return -EFAULT;
18787                 }
18788                 insn->imm = fn->func - __bpf_call_base;
18789         }
18790
18791         /* Since poke tab is now finalized, publish aux to tracker. */
18792         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18793                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18794                 if (!map_ptr->ops->map_poke_track ||
18795                     !map_ptr->ops->map_poke_untrack ||
18796                     !map_ptr->ops->map_poke_run) {
18797                         verbose(env, "bpf verifier is misconfigured\n");
18798                         return -EINVAL;
18799                 }
18800
18801                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18802                 if (ret < 0) {
18803                         verbose(env, "tracking tail call prog failed\n");
18804                         return ret;
18805                 }
18806         }
18807
18808         sort_kfunc_descs_by_imm_off(env->prog);
18809
18810         return 0;
18811 }
18812
18813 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18814                                         int position,
18815                                         s32 stack_base,
18816                                         u32 callback_subprogno,
18817                                         u32 *cnt)
18818 {
18819         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18820         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18821         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18822         int reg_loop_max = BPF_REG_6;
18823         int reg_loop_cnt = BPF_REG_7;
18824         int reg_loop_ctx = BPF_REG_8;
18825
18826         struct bpf_prog *new_prog;
18827         u32 callback_start;
18828         u32 call_insn_offset;
18829         s32 callback_offset;
18830
18831         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18832          * be careful to modify this code in sync.
18833          */
18834         struct bpf_insn insn_buf[] = {
18835                 /* Return error and jump to the end of the patch if
18836                  * expected number of iterations is too big.
18837                  */
18838                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18839                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18840                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18841                 /* spill R6, R7, R8 to use these as loop vars */
18842                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18843                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18844                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18845                 /* initialize loop vars */
18846                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18847                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18848                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18849                 /* loop header,
18850                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18851                  */
18852                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18853                 /* callback call,
18854                  * correct callback offset would be set after patching
18855                  */
18856                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18857                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18858                 BPF_CALL_REL(0),
18859                 /* increment loop counter */
18860                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18861                 /* jump to loop header if callback returned 0 */
18862                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18863                 /* return value of bpf_loop,
18864                  * set R0 to the number of iterations
18865                  */
18866                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18867                 /* restore original values of R6, R7, R8 */
18868                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18869                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18870                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18871         };
18872
18873         *cnt = ARRAY_SIZE(insn_buf);
18874         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18875         if (!new_prog)
18876                 return new_prog;
18877
18878         /* callback start is known only after patching */
18879         callback_start = env->subprog_info[callback_subprogno].start;
18880         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18881         call_insn_offset = position + 12;
18882         callback_offset = callback_start - call_insn_offset - 1;
18883         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18884
18885         return new_prog;
18886 }
18887
18888 static bool is_bpf_loop_call(struct bpf_insn *insn)
18889 {
18890         return insn->code == (BPF_JMP | BPF_CALL) &&
18891                 insn->src_reg == 0 &&
18892                 insn->imm == BPF_FUNC_loop;
18893 }
18894
18895 /* For all sub-programs in the program (including main) check
18896  * insn_aux_data to see if there are bpf_loop calls that require
18897  * inlining. If such calls are found the calls are replaced with a
18898  * sequence of instructions produced by `inline_bpf_loop` function and
18899  * subprog stack_depth is increased by the size of 3 registers.
18900  * This stack space is used to spill values of the R6, R7, R8.  These
18901  * registers are used to store the loop bound, counter and context
18902  * variables.
18903  */
18904 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18905 {
18906         struct bpf_subprog_info *subprogs = env->subprog_info;
18907         int i, cur_subprog = 0, cnt, delta = 0;
18908         struct bpf_insn *insn = env->prog->insnsi;
18909         int insn_cnt = env->prog->len;
18910         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18911         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18912         u16 stack_depth_extra = 0;
18913
18914         for (i = 0; i < insn_cnt; i++, insn++) {
18915                 struct bpf_loop_inline_state *inline_state =
18916                         &env->insn_aux_data[i + delta].loop_inline_state;
18917
18918                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
18919                         struct bpf_prog *new_prog;
18920
18921                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
18922                         new_prog = inline_bpf_loop(env,
18923                                                    i + delta,
18924                                                    -(stack_depth + stack_depth_extra),
18925                                                    inline_state->callback_subprogno,
18926                                                    &cnt);
18927                         if (!new_prog)
18928                                 return -ENOMEM;
18929
18930                         delta     += cnt - 1;
18931                         env->prog  = new_prog;
18932                         insn       = new_prog->insnsi + i + delta;
18933                 }
18934
18935                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
18936                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
18937                         cur_subprog++;
18938                         stack_depth = subprogs[cur_subprog].stack_depth;
18939                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18940                         stack_depth_extra = 0;
18941                 }
18942         }
18943
18944         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
18945
18946         return 0;
18947 }
18948
18949 static void free_states(struct bpf_verifier_env *env)
18950 {
18951         struct bpf_verifier_state_list *sl, *sln;
18952         int i;
18953
18954         sl = env->free_list;
18955         while (sl) {
18956                 sln = sl->next;
18957                 free_verifier_state(&sl->state, false);
18958                 kfree(sl);
18959                 sl = sln;
18960         }
18961         env->free_list = NULL;
18962
18963         if (!env->explored_states)
18964                 return;
18965
18966         for (i = 0; i < state_htab_size(env); i++) {
18967                 sl = env->explored_states[i];
18968
18969                 while (sl) {
18970                         sln = sl->next;
18971                         free_verifier_state(&sl->state, false);
18972                         kfree(sl);
18973                         sl = sln;
18974                 }
18975                 env->explored_states[i] = NULL;
18976         }
18977 }
18978
18979 static int do_check_common(struct bpf_verifier_env *env, int subprog)
18980 {
18981         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
18982         struct bpf_verifier_state *state;
18983         struct bpf_reg_state *regs;
18984         int ret, i;
18985
18986         env->prev_linfo = NULL;
18987         env->pass_cnt++;
18988
18989         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
18990         if (!state)
18991                 return -ENOMEM;
18992         state->curframe = 0;
18993         state->speculative = false;
18994         state->branches = 1;
18995         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
18996         if (!state->frame[0]) {
18997                 kfree(state);
18998                 return -ENOMEM;
18999         }
19000         env->cur_state = state;
19001         init_func_state(env, state->frame[0],
19002                         BPF_MAIN_FUNC /* callsite */,
19003                         0 /* frameno */,
19004                         subprog);
19005         state->first_insn_idx = env->subprog_info[subprog].start;
19006         state->last_insn_idx = -1;
19007
19008         regs = state->frame[state->curframe]->regs;
19009         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19010                 ret = btf_prepare_func_args(env, subprog, regs);
19011                 if (ret)
19012                         goto out;
19013                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19014                         if (regs[i].type == PTR_TO_CTX)
19015                                 mark_reg_known_zero(env, regs, i);
19016                         else if (regs[i].type == SCALAR_VALUE)
19017                                 mark_reg_unknown(env, regs, i);
19018                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19019                                 const u32 mem_size = regs[i].mem_size;
19020
19021                                 mark_reg_known_zero(env, regs, i);
19022                                 regs[i].mem_size = mem_size;
19023                                 regs[i].id = ++env->id_gen;
19024                         }
19025                 }
19026         } else {
19027                 /* 1st arg to a function */
19028                 regs[BPF_REG_1].type = PTR_TO_CTX;
19029                 mark_reg_known_zero(env, regs, BPF_REG_1);
19030                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19031                 if (ret == -EFAULT)
19032                         /* unlikely verifier bug. abort.
19033                          * ret == 0 and ret < 0 are sadly acceptable for
19034                          * main() function due to backward compatibility.
19035                          * Like socket filter program may be written as:
19036                          * int bpf_prog(struct pt_regs *ctx)
19037                          * and never dereference that ctx in the program.
19038                          * 'struct pt_regs' is a type mismatch for socket
19039                          * filter that should be using 'struct __sk_buff'.
19040                          */
19041                         goto out;
19042         }
19043
19044         ret = do_check(env);
19045 out:
19046         /* check for NULL is necessary, since cur_state can be freed inside
19047          * do_check() under memory pressure.
19048          */
19049         if (env->cur_state) {
19050                 free_verifier_state(env->cur_state, true);
19051                 env->cur_state = NULL;
19052         }
19053         while (!pop_stack(env, NULL, NULL, false));
19054         if (!ret && pop_log)
19055                 bpf_vlog_reset(&env->log, 0);
19056         free_states(env);
19057         return ret;
19058 }
19059
19060 /* Verify all global functions in a BPF program one by one based on their BTF.
19061  * All global functions must pass verification. Otherwise the whole program is rejected.
19062  * Consider:
19063  * int bar(int);
19064  * int foo(int f)
19065  * {
19066  *    return bar(f);
19067  * }
19068  * int bar(int b)
19069  * {
19070  *    ...
19071  * }
19072  * foo() will be verified first for R1=any_scalar_value. During verification it
19073  * will be assumed that bar() already verified successfully and call to bar()
19074  * from foo() will be checked for type match only. Later bar() will be verified
19075  * independently to check that it's safe for R1=any_scalar_value.
19076  */
19077 static int do_check_subprogs(struct bpf_verifier_env *env)
19078 {
19079         struct bpf_prog_aux *aux = env->prog->aux;
19080         int i, ret;
19081
19082         if (!aux->func_info)
19083                 return 0;
19084
19085         for (i = 1; i < env->subprog_cnt; i++) {
19086                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19087                         continue;
19088                 env->insn_idx = env->subprog_info[i].start;
19089                 WARN_ON_ONCE(env->insn_idx == 0);
19090                 ret = do_check_common(env, i);
19091                 if (ret) {
19092                         return ret;
19093                 } else if (env->log.level & BPF_LOG_LEVEL) {
19094                         verbose(env,
19095                                 "Func#%d is safe for any args that match its prototype\n",
19096                                 i);
19097                 }
19098         }
19099         return 0;
19100 }
19101
19102 static int do_check_main(struct bpf_verifier_env *env)
19103 {
19104         int ret;
19105
19106         env->insn_idx = 0;
19107         ret = do_check_common(env, 0);
19108         if (!ret)
19109                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19110         return ret;
19111 }
19112
19113
19114 static void print_verification_stats(struct bpf_verifier_env *env)
19115 {
19116         int i;
19117
19118         if (env->log.level & BPF_LOG_STATS) {
19119                 verbose(env, "verification time %lld usec\n",
19120                         div_u64(env->verification_time, 1000));
19121                 verbose(env, "stack depth ");
19122                 for (i = 0; i < env->subprog_cnt; i++) {
19123                         u32 depth = env->subprog_info[i].stack_depth;
19124
19125                         verbose(env, "%d", depth);
19126                         if (i + 1 < env->subprog_cnt)
19127                                 verbose(env, "+");
19128                 }
19129                 verbose(env, "\n");
19130         }
19131         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19132                 "total_states %d peak_states %d mark_read %d\n",
19133                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19134                 env->max_states_per_insn, env->total_states,
19135                 env->peak_states, env->longest_mark_read_walk);
19136 }
19137
19138 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19139 {
19140         const struct btf_type *t, *func_proto;
19141         const struct bpf_struct_ops *st_ops;
19142         const struct btf_member *member;
19143         struct bpf_prog *prog = env->prog;
19144         u32 btf_id, member_idx;
19145         const char *mname;
19146
19147         if (!prog->gpl_compatible) {
19148                 verbose(env, "struct ops programs must have a GPL compatible license\n");
19149                 return -EINVAL;
19150         }
19151
19152         btf_id = prog->aux->attach_btf_id;
19153         st_ops = bpf_struct_ops_find(btf_id);
19154         if (!st_ops) {
19155                 verbose(env, "attach_btf_id %u is not a supported struct\n",
19156                         btf_id);
19157                 return -ENOTSUPP;
19158         }
19159
19160         t = st_ops->type;
19161         member_idx = prog->expected_attach_type;
19162         if (member_idx >= btf_type_vlen(t)) {
19163                 verbose(env, "attach to invalid member idx %u of struct %s\n",
19164                         member_idx, st_ops->name);
19165                 return -EINVAL;
19166         }
19167
19168         member = &btf_type_member(t)[member_idx];
19169         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19170         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19171                                                NULL);
19172         if (!func_proto) {
19173                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19174                         mname, member_idx, st_ops->name);
19175                 return -EINVAL;
19176         }
19177
19178         if (st_ops->check_member) {
19179                 int err = st_ops->check_member(t, member, prog);
19180
19181                 if (err) {
19182                         verbose(env, "attach to unsupported member %s of struct %s\n",
19183                                 mname, st_ops->name);
19184                         return err;
19185                 }
19186         }
19187
19188         prog->aux->attach_func_proto = func_proto;
19189         prog->aux->attach_func_name = mname;
19190         env->ops = st_ops->verifier_ops;
19191
19192         return 0;
19193 }
19194 #define SECURITY_PREFIX "security_"
19195
19196 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19197 {
19198         if (within_error_injection_list(addr) ||
19199             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19200                 return 0;
19201
19202         return -EINVAL;
19203 }
19204
19205 /* list of non-sleepable functions that are otherwise on
19206  * ALLOW_ERROR_INJECTION list
19207  */
19208 BTF_SET_START(btf_non_sleepable_error_inject)
19209 /* Three functions below can be called from sleepable and non-sleepable context.
19210  * Assume non-sleepable from bpf safety point of view.
19211  */
19212 BTF_ID(func, __filemap_add_folio)
19213 BTF_ID(func, should_fail_alloc_page)
19214 BTF_ID(func, should_failslab)
19215 BTF_SET_END(btf_non_sleepable_error_inject)
19216
19217 static int check_non_sleepable_error_inject(u32 btf_id)
19218 {
19219         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19220 }
19221
19222 int bpf_check_attach_target(struct bpf_verifier_log *log,
19223                             const struct bpf_prog *prog,
19224                             const struct bpf_prog *tgt_prog,
19225                             u32 btf_id,
19226                             struct bpf_attach_target_info *tgt_info)
19227 {
19228         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19229         const char prefix[] = "btf_trace_";
19230         int ret = 0, subprog = -1, i;
19231         const struct btf_type *t;
19232         bool conservative = true;
19233         const char *tname;
19234         struct btf *btf;
19235         long addr = 0;
19236         struct module *mod = NULL;
19237
19238         if (!btf_id) {
19239                 bpf_log(log, "Tracing programs must provide btf_id\n");
19240                 return -EINVAL;
19241         }
19242         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19243         if (!btf) {
19244                 bpf_log(log,
19245                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19246                 return -EINVAL;
19247         }
19248         t = btf_type_by_id(btf, btf_id);
19249         if (!t) {
19250                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19251                 return -EINVAL;
19252         }
19253         tname = btf_name_by_offset(btf, t->name_off);
19254         if (!tname) {
19255                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19256                 return -EINVAL;
19257         }
19258         if (tgt_prog) {
19259                 struct bpf_prog_aux *aux = tgt_prog->aux;
19260
19261                 if (bpf_prog_is_dev_bound(prog->aux) &&
19262                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19263                         bpf_log(log, "Target program bound device mismatch");
19264                         return -EINVAL;
19265                 }
19266
19267                 for (i = 0; i < aux->func_info_cnt; i++)
19268                         if (aux->func_info[i].type_id == btf_id) {
19269                                 subprog = i;
19270                                 break;
19271                         }
19272                 if (subprog == -1) {
19273                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19274                         return -EINVAL;
19275                 }
19276                 conservative = aux->func_info_aux[subprog].unreliable;
19277                 if (prog_extension) {
19278                         if (conservative) {
19279                                 bpf_log(log,
19280                                         "Cannot replace static functions\n");
19281                                 return -EINVAL;
19282                         }
19283                         if (!prog->jit_requested) {
19284                                 bpf_log(log,
19285                                         "Extension programs should be JITed\n");
19286                                 return -EINVAL;
19287                         }
19288                 }
19289                 if (!tgt_prog->jited) {
19290                         bpf_log(log, "Can attach to only JITed progs\n");
19291                         return -EINVAL;
19292                 }
19293                 if (tgt_prog->type == prog->type) {
19294                         /* Cannot fentry/fexit another fentry/fexit program.
19295                          * Cannot attach program extension to another extension.
19296                          * It's ok to attach fentry/fexit to extension program.
19297                          */
19298                         bpf_log(log, "Cannot recursively attach\n");
19299                         return -EINVAL;
19300                 }
19301                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19302                     prog_extension &&
19303                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19304                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19305                         /* Program extensions can extend all program types
19306                          * except fentry/fexit. The reason is the following.
19307                          * The fentry/fexit programs are used for performance
19308                          * analysis, stats and can be attached to any program
19309                          * type except themselves. When extension program is
19310                          * replacing XDP function it is necessary to allow
19311                          * performance analysis of all functions. Both original
19312                          * XDP program and its program extension. Hence
19313                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19314                          * allowed. If extending of fentry/fexit was allowed it
19315                          * would be possible to create long call chain
19316                          * fentry->extension->fentry->extension beyond
19317                          * reasonable stack size. Hence extending fentry is not
19318                          * allowed.
19319                          */
19320                         bpf_log(log, "Cannot extend fentry/fexit\n");
19321                         return -EINVAL;
19322                 }
19323         } else {
19324                 if (prog_extension) {
19325                         bpf_log(log, "Cannot replace kernel functions\n");
19326                         return -EINVAL;
19327                 }
19328         }
19329
19330         switch (prog->expected_attach_type) {
19331         case BPF_TRACE_RAW_TP:
19332                 if (tgt_prog) {
19333                         bpf_log(log,
19334                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19335                         return -EINVAL;
19336                 }
19337                 if (!btf_type_is_typedef(t)) {
19338                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19339                                 btf_id);
19340                         return -EINVAL;
19341                 }
19342                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19343                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19344                                 btf_id, tname);
19345                         return -EINVAL;
19346                 }
19347                 tname += sizeof(prefix) - 1;
19348                 t = btf_type_by_id(btf, t->type);
19349                 if (!btf_type_is_ptr(t))
19350                         /* should never happen in valid vmlinux build */
19351                         return -EINVAL;
19352                 t = btf_type_by_id(btf, t->type);
19353                 if (!btf_type_is_func_proto(t))
19354                         /* should never happen in valid vmlinux build */
19355                         return -EINVAL;
19356
19357                 break;
19358         case BPF_TRACE_ITER:
19359                 if (!btf_type_is_func(t)) {
19360                         bpf_log(log, "attach_btf_id %u is not a function\n",
19361                                 btf_id);
19362                         return -EINVAL;
19363                 }
19364                 t = btf_type_by_id(btf, t->type);
19365                 if (!btf_type_is_func_proto(t))
19366                         return -EINVAL;
19367                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19368                 if (ret)
19369                         return ret;
19370                 break;
19371         default:
19372                 if (!prog_extension)
19373                         return -EINVAL;
19374                 fallthrough;
19375         case BPF_MODIFY_RETURN:
19376         case BPF_LSM_MAC:
19377         case BPF_LSM_CGROUP:
19378         case BPF_TRACE_FENTRY:
19379         case BPF_TRACE_FEXIT:
19380                 if (!btf_type_is_func(t)) {
19381                         bpf_log(log, "attach_btf_id %u is not a function\n",
19382                                 btf_id);
19383                         return -EINVAL;
19384                 }
19385                 if (prog_extension &&
19386                     btf_check_type_match(log, prog, btf, t))
19387                         return -EINVAL;
19388                 t = btf_type_by_id(btf, t->type);
19389                 if (!btf_type_is_func_proto(t))
19390                         return -EINVAL;
19391
19392                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19393                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19394                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19395                         return -EINVAL;
19396
19397                 if (tgt_prog && conservative)
19398                         t = NULL;
19399
19400                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19401                 if (ret < 0)
19402                         return ret;
19403
19404                 if (tgt_prog) {
19405                         if (subprog == 0)
19406                                 addr = (long) tgt_prog->bpf_func;
19407                         else
19408                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19409                 } else {
19410                         if (btf_is_module(btf)) {
19411                                 mod = btf_try_get_module(btf);
19412                                 if (mod)
19413                                         addr = find_kallsyms_symbol_value(mod, tname);
19414                                 else
19415                                         addr = 0;
19416                         } else {
19417                                 addr = kallsyms_lookup_name(tname);
19418                         }
19419                         if (!addr) {
19420                                 module_put(mod);
19421                                 bpf_log(log,
19422                                         "The address of function %s cannot be found\n",
19423                                         tname);
19424                                 return -ENOENT;
19425                         }
19426                 }
19427
19428                 if (prog->aux->sleepable) {
19429                         ret = -EINVAL;
19430                         switch (prog->type) {
19431                         case BPF_PROG_TYPE_TRACING:
19432
19433                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19434                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19435                                  */
19436                                 if (!check_non_sleepable_error_inject(btf_id) &&
19437                                     within_error_injection_list(addr))
19438                                         ret = 0;
19439                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19440                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19441                                  */
19442                                 else {
19443                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19444                                                                                 prog);
19445
19446                                         if (flags && (*flags & KF_SLEEPABLE))
19447                                                 ret = 0;
19448                                 }
19449                                 break;
19450                         case BPF_PROG_TYPE_LSM:
19451                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19452                                  * Only some of them are sleepable.
19453                                  */
19454                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19455                                         ret = 0;
19456                                 break;
19457                         default:
19458                                 break;
19459                         }
19460                         if (ret) {
19461                                 module_put(mod);
19462                                 bpf_log(log, "%s is not sleepable\n", tname);
19463                                 return ret;
19464                         }
19465                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19466                         if (tgt_prog) {
19467                                 module_put(mod);
19468                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19469                                 return -EINVAL;
19470                         }
19471                         ret = -EINVAL;
19472                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19473                             !check_attach_modify_return(addr, tname))
19474                                 ret = 0;
19475                         if (ret) {
19476                                 module_put(mod);
19477                                 bpf_log(log, "%s() is not modifiable\n", tname);
19478                                 return ret;
19479                         }
19480                 }
19481
19482                 break;
19483         }
19484         tgt_info->tgt_addr = addr;
19485         tgt_info->tgt_name = tname;
19486         tgt_info->tgt_type = t;
19487         tgt_info->tgt_mod = mod;
19488         return 0;
19489 }
19490
19491 BTF_SET_START(btf_id_deny)
19492 BTF_ID_UNUSED
19493 #ifdef CONFIG_SMP
19494 BTF_ID(func, migrate_disable)
19495 BTF_ID(func, migrate_enable)
19496 #endif
19497 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19498 BTF_ID(func, rcu_read_unlock_strict)
19499 #endif
19500 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19501 BTF_ID(func, preempt_count_add)
19502 BTF_ID(func, preempt_count_sub)
19503 #endif
19504 #ifdef CONFIG_PREEMPT_RCU
19505 BTF_ID(func, __rcu_read_lock)
19506 BTF_ID(func, __rcu_read_unlock)
19507 #endif
19508 BTF_SET_END(btf_id_deny)
19509
19510 static bool can_be_sleepable(struct bpf_prog *prog)
19511 {
19512         if (prog->type == BPF_PROG_TYPE_TRACING) {
19513                 switch (prog->expected_attach_type) {
19514                 case BPF_TRACE_FENTRY:
19515                 case BPF_TRACE_FEXIT:
19516                 case BPF_MODIFY_RETURN:
19517                 case BPF_TRACE_ITER:
19518                         return true;
19519                 default:
19520                         return false;
19521                 }
19522         }
19523         return prog->type == BPF_PROG_TYPE_LSM ||
19524                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19525                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19526 }
19527
19528 static int check_attach_btf_id(struct bpf_verifier_env *env)
19529 {
19530         struct bpf_prog *prog = env->prog;
19531         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19532         struct bpf_attach_target_info tgt_info = {};
19533         u32 btf_id = prog->aux->attach_btf_id;
19534         struct bpf_trampoline *tr;
19535         int ret;
19536         u64 key;
19537
19538         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19539                 if (prog->aux->sleepable)
19540                         /* attach_btf_id checked to be zero already */
19541                         return 0;
19542                 verbose(env, "Syscall programs can only be sleepable\n");
19543                 return -EINVAL;
19544         }
19545
19546         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19547                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19548                 return -EINVAL;
19549         }
19550
19551         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19552                 return check_struct_ops_btf_id(env);
19553
19554         if (prog->type != BPF_PROG_TYPE_TRACING &&
19555             prog->type != BPF_PROG_TYPE_LSM &&
19556             prog->type != BPF_PROG_TYPE_EXT)
19557                 return 0;
19558
19559         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19560         if (ret)
19561                 return ret;
19562
19563         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19564                 /* to make freplace equivalent to their targets, they need to
19565                  * inherit env->ops and expected_attach_type for the rest of the
19566                  * verification
19567                  */
19568                 env->ops = bpf_verifier_ops[tgt_prog->type];
19569                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19570         }
19571
19572         /* store info about the attachment target that will be used later */
19573         prog->aux->attach_func_proto = tgt_info.tgt_type;
19574         prog->aux->attach_func_name = tgt_info.tgt_name;
19575         prog->aux->mod = tgt_info.tgt_mod;
19576
19577         if (tgt_prog) {
19578                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19579                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19580         }
19581
19582         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19583                 prog->aux->attach_btf_trace = true;
19584                 return 0;
19585         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19586                 if (!bpf_iter_prog_supported(prog))
19587                         return -EINVAL;
19588                 return 0;
19589         }
19590
19591         if (prog->type == BPF_PROG_TYPE_LSM) {
19592                 ret = bpf_lsm_verify_prog(&env->log, prog);
19593                 if (ret < 0)
19594                         return ret;
19595         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19596                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19597                 return -EINVAL;
19598         }
19599
19600         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19601         tr = bpf_trampoline_get(key, &tgt_info);
19602         if (!tr)
19603                 return -ENOMEM;
19604
19605         prog->aux->dst_trampoline = tr;
19606         return 0;
19607 }
19608
19609 struct btf *bpf_get_btf_vmlinux(void)
19610 {
19611         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19612                 mutex_lock(&bpf_verifier_lock);
19613                 if (!btf_vmlinux)
19614                         btf_vmlinux = btf_parse_vmlinux();
19615                 mutex_unlock(&bpf_verifier_lock);
19616         }
19617         return btf_vmlinux;
19618 }
19619
19620 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19621 {
19622         u64 start_time = ktime_get_ns();
19623         struct bpf_verifier_env *env;
19624         int i, len, ret = -EINVAL, err;
19625         u32 log_true_size;
19626         bool is_priv;
19627
19628         /* no program is valid */
19629         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19630                 return -EINVAL;
19631
19632         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19633          * allocate/free it every time bpf_check() is called
19634          */
19635         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19636         if (!env)
19637                 return -ENOMEM;
19638
19639         env->bt.env = env;
19640
19641         len = (*prog)->len;
19642         env->insn_aux_data =
19643                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19644         ret = -ENOMEM;
19645         if (!env->insn_aux_data)
19646                 goto err_free_env;
19647         for (i = 0; i < len; i++)
19648                 env->insn_aux_data[i].orig_idx = i;
19649         env->prog = *prog;
19650         env->ops = bpf_verifier_ops[env->prog->type];
19651         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19652         is_priv = bpf_capable();
19653
19654         bpf_get_btf_vmlinux();
19655
19656         /* grab the mutex to protect few globals used by verifier */
19657         if (!is_priv)
19658                 mutex_lock(&bpf_verifier_lock);
19659
19660         /* user could have requested verbose verifier output
19661          * and supplied buffer to store the verification trace
19662          */
19663         ret = bpf_vlog_init(&env->log, attr->log_level,
19664                             (char __user *) (unsigned long) attr->log_buf,
19665                             attr->log_size);
19666         if (ret)
19667                 goto err_unlock;
19668
19669         mark_verifier_state_clean(env);
19670
19671         if (IS_ERR(btf_vmlinux)) {
19672                 /* Either gcc or pahole or kernel are broken. */
19673                 verbose(env, "in-kernel BTF is malformed\n");
19674                 ret = PTR_ERR(btf_vmlinux);
19675                 goto skip_full_check;
19676         }
19677
19678         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19679         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19680                 env->strict_alignment = true;
19681         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19682                 env->strict_alignment = false;
19683
19684         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19685         env->allow_uninit_stack = bpf_allow_uninit_stack();
19686         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19687         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19688         env->bpf_capable = bpf_capable();
19689
19690         if (is_priv)
19691                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19692
19693         env->explored_states = kvcalloc(state_htab_size(env),
19694                                        sizeof(struct bpf_verifier_state_list *),
19695                                        GFP_USER);
19696         ret = -ENOMEM;
19697         if (!env->explored_states)
19698                 goto skip_full_check;
19699
19700         ret = add_subprog_and_kfunc(env);
19701         if (ret < 0)
19702                 goto skip_full_check;
19703
19704         ret = check_subprogs(env);
19705         if (ret < 0)
19706                 goto skip_full_check;
19707
19708         ret = check_btf_info(env, attr, uattr);
19709         if (ret < 0)
19710                 goto skip_full_check;
19711
19712         ret = check_attach_btf_id(env);
19713         if (ret)
19714                 goto skip_full_check;
19715
19716         ret = resolve_pseudo_ldimm64(env);
19717         if (ret < 0)
19718                 goto skip_full_check;
19719
19720         if (bpf_prog_is_offloaded(env->prog->aux)) {
19721                 ret = bpf_prog_offload_verifier_prep(env->prog);
19722                 if (ret)
19723                         goto skip_full_check;
19724         }
19725
19726         ret = check_cfg(env);
19727         if (ret < 0)
19728                 goto skip_full_check;
19729
19730         ret = do_check_subprogs(env);
19731         ret = ret ?: do_check_main(env);
19732
19733         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19734                 ret = bpf_prog_offload_finalize(env);
19735
19736 skip_full_check:
19737         kvfree(env->explored_states);
19738
19739         if (ret == 0)
19740                 ret = check_max_stack_depth(env);
19741
19742         /* instruction rewrites happen after this point */
19743         if (ret == 0)
19744                 ret = optimize_bpf_loop(env);
19745
19746         if (is_priv) {
19747                 if (ret == 0)
19748                         opt_hard_wire_dead_code_branches(env);
19749                 if (ret == 0)
19750                         ret = opt_remove_dead_code(env);
19751                 if (ret == 0)
19752                         ret = opt_remove_nops(env);
19753         } else {
19754                 if (ret == 0)
19755                         sanitize_dead_code(env);
19756         }
19757
19758         if (ret == 0)
19759                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19760                 ret = convert_ctx_accesses(env);
19761
19762         if (ret == 0)
19763                 ret = do_misc_fixups(env);
19764
19765         /* do 32-bit optimization after insn patching has done so those patched
19766          * insns could be handled correctly.
19767          */
19768         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19769                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19770                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19771                                                                      : false;
19772         }
19773
19774         if (ret == 0)
19775                 ret = fixup_call_args(env);
19776
19777         env->verification_time = ktime_get_ns() - start_time;
19778         print_verification_stats(env);
19779         env->prog->aux->verified_insns = env->insn_processed;
19780
19781         /* preserve original error even if log finalization is successful */
19782         err = bpf_vlog_finalize(&env->log, &log_true_size);
19783         if (err)
19784                 ret = err;
19785
19786         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19787             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19788                                   &log_true_size, sizeof(log_true_size))) {
19789                 ret = -EFAULT;
19790                 goto err_release_maps;
19791         }
19792
19793         if (ret)
19794                 goto err_release_maps;
19795
19796         if (env->used_map_cnt) {
19797                 /* if program passed verifier, update used_maps in bpf_prog_info */
19798                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19799                                                           sizeof(env->used_maps[0]),
19800                                                           GFP_KERNEL);
19801
19802                 if (!env->prog->aux->used_maps) {
19803                         ret = -ENOMEM;
19804                         goto err_release_maps;
19805                 }
19806
19807                 memcpy(env->prog->aux->used_maps, env->used_maps,
19808                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19809                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19810         }
19811         if (env->used_btf_cnt) {
19812                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19813                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19814                                                           sizeof(env->used_btfs[0]),
19815                                                           GFP_KERNEL);
19816                 if (!env->prog->aux->used_btfs) {
19817                         ret = -ENOMEM;
19818                         goto err_release_maps;
19819                 }
19820
19821                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19822                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19823                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19824         }
19825         if (env->used_map_cnt || env->used_btf_cnt) {
19826                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19827                  * bpf_ld_imm64 instructions
19828                  */
19829                 convert_pseudo_ld_imm64(env);
19830         }
19831
19832         adjust_btf_func(env);
19833
19834 err_release_maps:
19835         if (!env->prog->aux->used_maps)
19836                 /* if we didn't copy map pointers into bpf_prog_info, release
19837                  * them now. Otherwise free_used_maps() will release them.
19838                  */
19839                 release_maps(env);
19840         if (!env->prog->aux->used_btfs)
19841                 release_btfs(env);
19842
19843         /* extension progs temporarily inherit the attach_type of their targets
19844            for verification purposes, so set it back to zero before returning
19845          */
19846         if (env->prog->type == BPF_PROG_TYPE_EXT)
19847                 env->prog->expected_attach_type = 0;
19848
19849         *prog = env->prog;
19850 err_unlock:
19851         if (!is_priv)
19852                 mutex_unlock(&bpf_verifier_lock);
19853         vfree(env->insn_aux_data);
19854 err_free_env:
19855         kfree(env);
19856         return ret;
19857 }