bpf: fix check for attempt to corrupt spilled pointer
[platform/kernel/linux-rpi.git] / kernel / bpf / verifier.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  * Copyright (c) 2016 Facebook
4  * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io
5  */
6 #include <uapi/linux/btf.h>
7 #include <linux/bpf-cgroup.h>
8 #include <linux/kernel.h>
9 #include <linux/types.h>
10 #include <linux/slab.h>
11 #include <linux/bpf.h>
12 #include <linux/btf.h>
13 #include <linux/bpf_verifier.h>
14 #include <linux/filter.h>
15 #include <net/netlink.h>
16 #include <linux/file.h>
17 #include <linux/vmalloc.h>
18 #include <linux/stringify.h>
19 #include <linux/bsearch.h>
20 #include <linux/sort.h>
21 #include <linux/perf_event.h>
22 #include <linux/ctype.h>
23 #include <linux/error-injection.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/btf_ids.h>
26 #include <linux/poison.h>
27 #include <linux/module.h>
28 #include <linux/cpumask.h>
29 #include <net/xdp.h>
30
31 #include "disasm.h"
32
33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
34 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
35         [_id] = & _name ## _verifier_ops,
36 #define BPF_MAP_TYPE(_id, _ops)
37 #define BPF_LINK_TYPE(_id, _name)
38 #include <linux/bpf_types.h>
39 #undef BPF_PROG_TYPE
40 #undef BPF_MAP_TYPE
41 #undef BPF_LINK_TYPE
42 };
43
44 /* bpf_check() is a static code analyzer that walks eBPF program
45  * instruction by instruction and updates register/stack state.
46  * All paths of conditional branches are analyzed until 'bpf_exit' insn.
47  *
48  * The first pass is depth-first-search to check that the program is a DAG.
49  * It rejects the following programs:
50  * - larger than BPF_MAXINSNS insns
51  * - if loop is present (detected via back-edge)
52  * - unreachable insns exist (shouldn't be a forest. program = one function)
53  * - out of bounds or malformed jumps
54  * The second pass is all possible path descent from the 1st insn.
55  * Since it's analyzing all paths through the program, the length of the
56  * analysis is limited to 64k insn, which may be hit even if total number of
57  * insn is less then 4K, but there are too many branches that change stack/regs.
58  * Number of 'branches to be analyzed' is limited to 1k
59  *
60  * On entry to each instruction, each register has a type, and the instruction
61  * changes the types of the registers depending on instruction semantics.
62  * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is
63  * copied to R1.
64  *
65  * All registers are 64-bit.
66  * R0 - return register
67  * R1-R5 argument passing registers
68  * R6-R9 callee saved registers
69  * R10 - frame pointer read-only
70  *
71  * At the start of BPF program the register R1 contains a pointer to bpf_context
72  * and has type PTR_TO_CTX.
73  *
74  * Verifier tracks arithmetic operations on pointers in case:
75  *    BPF_MOV64_REG(BPF_REG_1, BPF_REG_10),
76  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20),
77  * 1st insn copies R10 (which has FRAME_PTR) type into R1
78  * and 2nd arithmetic instruction is pattern matched to recognize
79  * that it wants to construct a pointer to some element within stack.
80  * So after 2nd insn, the register R1 has type PTR_TO_STACK
81  * (and -20 constant is saved for further stack bounds checking).
82  * Meaning that this reg is a pointer to stack plus known immediate constant.
83  *
84  * Most of the time the registers have SCALAR_VALUE type, which
85  * means the register has some value, but it's not a valid pointer.
86  * (like pointer plus pointer becomes SCALAR_VALUE type)
87  *
88  * When verifier sees load or store instructions the type of base register
89  * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are
90  * four pointer types recognized by check_mem_access() function.
91  *
92  * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value'
93  * and the range of [ptr, ptr + map's value_size) is accessible.
94  *
95  * registers used to pass values to function calls are checked against
96  * function argument constraints.
97  *
98  * ARG_PTR_TO_MAP_KEY is one of such argument constraints.
99  * It means that the register type passed to this function must be
100  * PTR_TO_STACK and it will be used inside the function as
101  * 'pointer to map element key'
102  *
103  * For example the argument constraints for bpf_map_lookup_elem():
104  *   .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL,
105  *   .arg1_type = ARG_CONST_MAP_PTR,
106  *   .arg2_type = ARG_PTR_TO_MAP_KEY,
107  *
108  * ret_type says that this function returns 'pointer to map elem value or null'
109  * function expects 1st argument to be a const pointer to 'struct bpf_map' and
110  * 2nd argument should be a pointer to stack, which will be used inside
111  * the helper function as a pointer to map element key.
112  *
113  * On the kernel side the helper function looks like:
114  * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
115  * {
116  *    struct bpf_map *map = (struct bpf_map *) (unsigned long) r1;
117  *    void *key = (void *) (unsigned long) r2;
118  *    void *value;
119  *
120  *    here kernel can access 'key' and 'map' pointers safely, knowing that
121  *    [key, key + map->key_size) bytes are valid and were initialized on
122  *    the stack of eBPF program.
123  * }
124  *
125  * Corresponding eBPF program may look like:
126  *    BPF_MOV64_REG(BPF_REG_2, BPF_REG_10),  // after this insn R2 type is FRAME_PTR
127  *    BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK
128  *    BPF_LD_MAP_FD(BPF_REG_1, map_fd),      // after this insn R1 type is CONST_PTR_TO_MAP
129  *    BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem),
130  * here verifier looks at prototype of map_lookup_elem() and sees:
131  * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok,
132  * Now verifier knows that this map has key of R1->map_ptr->key_size bytes
133  *
134  * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far,
135  * Now verifier checks that [R2, R2 + map's key_size) are within stack limits
136  * and were initialized prior to this call.
137  * If it's ok, then verifier allows this BPF_CALL insn and looks at
138  * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets
139  * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function
140  * returns either pointer to map value or NULL.
141  *
142  * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off'
143  * insn, the register holding that pointer in the true branch changes state to
144  * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false
145  * branch. See check_cond_jmp_op().
146  *
147  * After the call R0 is set to return type of the function and registers R1-R5
148  * are set to NOT_INIT to indicate that they are no longer readable.
149  *
150  * The following reference types represent a potential reference to a kernel
151  * resource which, after first being allocated, must be checked and freed by
152  * the BPF program:
153  * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET
154  *
155  * When the verifier sees a helper call return a reference type, it allocates a
156  * pointer id for the reference and stores it in the current function state.
157  * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into
158  * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type
159  * passes through a NULL-check conditional. For the branch wherein the state is
160  * changed to CONST_IMM, the verifier releases the reference.
161  *
162  * For each helper function that allocates a reference, such as
163  * bpf_sk_lookup_tcp(), there is a corresponding release function, such as
164  * bpf_sk_release(). When a reference type passes into the release function,
165  * the verifier also releases the reference. If any unchecked or unreleased
166  * reference remains at the end of the program, the verifier rejects it.
167  */
168
169 /* verifier_state + insn_idx are pushed to stack when branch is encountered */
170 struct bpf_verifier_stack_elem {
171         /* verifer state is 'st'
172          * before processing instruction 'insn_idx'
173          * and after processing instruction 'prev_insn_idx'
174          */
175         struct bpf_verifier_state st;
176         int insn_idx;
177         int prev_insn_idx;
178         struct bpf_verifier_stack_elem *next;
179         /* length of verifier log at the time this state was pushed on stack */
180         u32 log_pos;
181 };
182
183 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ    8192
184 #define BPF_COMPLEXITY_LIMIT_STATES     64
185
186 #define BPF_MAP_KEY_POISON      (1ULL << 63)
187 #define BPF_MAP_KEY_SEEN        (1ULL << 62)
188
189 #define BPF_MAP_PTR_UNPRIV      1UL
190 #define BPF_MAP_PTR_POISON      ((void *)((0xeB9FUL << 1) +     \
191                                           POISON_POINTER_DELTA))
192 #define BPF_MAP_PTR(X)          ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV))
193
194 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx);
195 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id);
196 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
197 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
198 static int ref_set_non_owning(struct bpf_verifier_env *env,
199                               struct bpf_reg_state *reg);
200 static void specialize_kfunc(struct bpf_verifier_env *env,
201                              u32 func_id, u16 offset, unsigned long *addr);
202 static bool is_trusted_reg(const struct bpf_reg_state *reg);
203
204 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
205 {
206         return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON;
207 }
208
209 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux)
210 {
211         return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV;
212 }
213
214 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
215                               const struct bpf_map *map, bool unpriv)
216 {
217         BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV);
218         unpriv |= bpf_map_ptr_unpriv(aux);
219         aux->map_ptr_state = (unsigned long)map |
220                              (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL);
221 }
222
223 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux)
224 {
225         return aux->map_key_state & BPF_MAP_KEY_POISON;
226 }
227
228 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux)
229 {
230         return !(aux->map_key_state & BPF_MAP_KEY_SEEN);
231 }
232
233 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux)
234 {
235         return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON);
236 }
237
238 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state)
239 {
240         bool poisoned = bpf_map_key_poisoned(aux);
241
242         aux->map_key_state = state | BPF_MAP_KEY_SEEN |
243                              (poisoned ? BPF_MAP_KEY_POISON : 0ULL);
244 }
245
246 static bool bpf_helper_call(const struct bpf_insn *insn)
247 {
248         return insn->code == (BPF_JMP | BPF_CALL) &&
249                insn->src_reg == 0;
250 }
251
252 static bool bpf_pseudo_call(const struct bpf_insn *insn)
253 {
254         return insn->code == (BPF_JMP | BPF_CALL) &&
255                insn->src_reg == BPF_PSEUDO_CALL;
256 }
257
258 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn)
259 {
260         return insn->code == (BPF_JMP | BPF_CALL) &&
261                insn->src_reg == BPF_PSEUDO_KFUNC_CALL;
262 }
263
264 struct bpf_call_arg_meta {
265         struct bpf_map *map_ptr;
266         bool raw_mode;
267         bool pkt_access;
268         u8 release_regno;
269         int regno;
270         int access_size;
271         int mem_size;
272         u64 msize_max_value;
273         int ref_obj_id;
274         int dynptr_id;
275         int map_uid;
276         int func_id;
277         struct btf *btf;
278         u32 btf_id;
279         struct btf *ret_btf;
280         u32 ret_btf_id;
281         u32 subprogno;
282         struct btf_field *kptr_field;
283 };
284
285 struct bpf_kfunc_call_arg_meta {
286         /* In parameters */
287         struct btf *btf;
288         u32 func_id;
289         u32 kfunc_flags;
290         const struct btf_type *func_proto;
291         const char *func_name;
292         /* Out parameters */
293         u32 ref_obj_id;
294         u8 release_regno;
295         bool r0_rdonly;
296         u32 ret_btf_id;
297         u64 r0_size;
298         u32 subprogno;
299         struct {
300                 u64 value;
301                 bool found;
302         } arg_constant;
303
304         /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling,
305          * generally to pass info about user-defined local kptr types to later
306          * verification logic
307          *   bpf_obj_drop
308          *     Record the local kptr type to be drop'd
309          *   bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type)
310          *     Record the local kptr type to be refcount_incr'd and use
311          *     arg_owning_ref to determine whether refcount_acquire should be
312          *     fallible
313          */
314         struct btf *arg_btf;
315         u32 arg_btf_id;
316         bool arg_owning_ref;
317
318         struct {
319                 struct btf_field *field;
320         } arg_list_head;
321         struct {
322                 struct btf_field *field;
323         } arg_rbtree_root;
324         struct {
325                 enum bpf_dynptr_type type;
326                 u32 id;
327                 u32 ref_obj_id;
328         } initialized_dynptr;
329         struct {
330                 u8 spi;
331                 u8 frameno;
332         } iter;
333         u64 mem_size;
334 };
335
336 struct btf *btf_vmlinux;
337
338 static DEFINE_MUTEX(bpf_verifier_lock);
339
340 static const struct bpf_line_info *
341 find_linfo(const struct bpf_verifier_env *env, u32 insn_off)
342 {
343         const struct bpf_line_info *linfo;
344         const struct bpf_prog *prog;
345         u32 i, nr_linfo;
346
347         prog = env->prog;
348         nr_linfo = prog->aux->nr_linfo;
349
350         if (!nr_linfo || insn_off >= prog->len)
351                 return NULL;
352
353         linfo = prog->aux->linfo;
354         for (i = 1; i < nr_linfo; i++)
355                 if (insn_off < linfo[i].insn_off)
356                         break;
357
358         return &linfo[i - 1];
359 }
360
361 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...)
362 {
363         struct bpf_verifier_env *env = private_data;
364         va_list args;
365
366         if (!bpf_verifier_log_needed(&env->log))
367                 return;
368
369         va_start(args, fmt);
370         bpf_verifier_vlog(&env->log, fmt, args);
371         va_end(args);
372 }
373
374 static const char *ltrim(const char *s)
375 {
376         while (isspace(*s))
377                 s++;
378
379         return s;
380 }
381
382 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env,
383                                          u32 insn_off,
384                                          const char *prefix_fmt, ...)
385 {
386         const struct bpf_line_info *linfo;
387
388         if (!bpf_verifier_log_needed(&env->log))
389                 return;
390
391         linfo = find_linfo(env, insn_off);
392         if (!linfo || linfo == env->prev_linfo)
393                 return;
394
395         if (prefix_fmt) {
396                 va_list args;
397
398                 va_start(args, prefix_fmt);
399                 bpf_verifier_vlog(&env->log, prefix_fmt, args);
400                 va_end(args);
401         }
402
403         verbose(env, "%s\n",
404                 ltrim(btf_name_by_offset(env->prog->aux->btf,
405                                          linfo->line_off)));
406
407         env->prev_linfo = linfo;
408 }
409
410 static void verbose_invalid_scalar(struct bpf_verifier_env *env,
411                                    struct bpf_reg_state *reg,
412                                    struct tnum *range, const char *ctx,
413                                    const char *reg_name)
414 {
415         char tn_buf[48];
416
417         verbose(env, "At %s the register %s ", ctx, reg_name);
418         if (!tnum_is_unknown(reg->var_off)) {
419                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
420                 verbose(env, "has value %s", tn_buf);
421         } else {
422                 verbose(env, "has unknown scalar value");
423         }
424         tnum_strn(tn_buf, sizeof(tn_buf), *range);
425         verbose(env, " should have been in %s\n", tn_buf);
426 }
427
428 static bool type_is_pkt_pointer(enum bpf_reg_type type)
429 {
430         type = base_type(type);
431         return type == PTR_TO_PACKET ||
432                type == PTR_TO_PACKET_META;
433 }
434
435 static bool type_is_sk_pointer(enum bpf_reg_type type)
436 {
437         return type == PTR_TO_SOCKET ||
438                 type == PTR_TO_SOCK_COMMON ||
439                 type == PTR_TO_TCP_SOCK ||
440                 type == PTR_TO_XDP_SOCK;
441 }
442
443 static bool type_may_be_null(u32 type)
444 {
445         return type & PTR_MAYBE_NULL;
446 }
447
448 static bool reg_not_null(const struct bpf_reg_state *reg)
449 {
450         enum bpf_reg_type type;
451
452         type = reg->type;
453         if (type_may_be_null(type))
454                 return false;
455
456         type = base_type(type);
457         return type == PTR_TO_SOCKET ||
458                 type == PTR_TO_TCP_SOCK ||
459                 type == PTR_TO_MAP_VALUE ||
460                 type == PTR_TO_MAP_KEY ||
461                 type == PTR_TO_SOCK_COMMON ||
462                 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) ||
463                 type == PTR_TO_MEM;
464 }
465
466 static bool type_is_ptr_alloc_obj(u32 type)
467 {
468         return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC;
469 }
470
471 static bool type_is_non_owning_ref(u32 type)
472 {
473         return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
474 }
475
476 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg)
477 {
478         struct btf_record *rec = NULL;
479         struct btf_struct_meta *meta;
480
481         if (reg->type == PTR_TO_MAP_VALUE) {
482                 rec = reg->map_ptr->record;
483         } else if (type_is_ptr_alloc_obj(reg->type)) {
484                 meta = btf_find_struct_meta(reg->btf, reg->btf_id);
485                 if (meta)
486                         rec = meta->record;
487         }
488         return rec;
489 }
490
491 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog)
492 {
493         struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux;
494
495         return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL;
496 }
497
498 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg)
499 {
500         return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK);
501 }
502
503 static bool type_is_rdonly_mem(u32 type)
504 {
505         return type & MEM_RDONLY;
506 }
507
508 static bool is_acquire_function(enum bpf_func_id func_id,
509                                 const struct bpf_map *map)
510 {
511         enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC;
512
513         if (func_id == BPF_FUNC_sk_lookup_tcp ||
514             func_id == BPF_FUNC_sk_lookup_udp ||
515             func_id == BPF_FUNC_skc_lookup_tcp ||
516             func_id == BPF_FUNC_ringbuf_reserve ||
517             func_id == BPF_FUNC_kptr_xchg)
518                 return true;
519
520         if (func_id == BPF_FUNC_map_lookup_elem &&
521             (map_type == BPF_MAP_TYPE_SOCKMAP ||
522              map_type == BPF_MAP_TYPE_SOCKHASH))
523                 return true;
524
525         return false;
526 }
527
528 static bool is_ptr_cast_function(enum bpf_func_id func_id)
529 {
530         return func_id == BPF_FUNC_tcp_sock ||
531                 func_id == BPF_FUNC_sk_fullsock ||
532                 func_id == BPF_FUNC_skc_to_tcp_sock ||
533                 func_id == BPF_FUNC_skc_to_tcp6_sock ||
534                 func_id == BPF_FUNC_skc_to_udp6_sock ||
535                 func_id == BPF_FUNC_skc_to_mptcp_sock ||
536                 func_id == BPF_FUNC_skc_to_tcp_timewait_sock ||
537                 func_id == BPF_FUNC_skc_to_tcp_request_sock;
538 }
539
540 static bool is_dynptr_ref_function(enum bpf_func_id func_id)
541 {
542         return func_id == BPF_FUNC_dynptr_data;
543 }
544
545 static bool is_callback_calling_kfunc(u32 btf_id);
546
547 static bool is_callback_calling_function(enum bpf_func_id func_id)
548 {
549         return func_id == BPF_FUNC_for_each_map_elem ||
550                func_id == BPF_FUNC_timer_set_callback ||
551                func_id == BPF_FUNC_find_vma ||
552                func_id == BPF_FUNC_loop ||
553                func_id == BPF_FUNC_user_ringbuf_drain;
554 }
555
556 static bool is_async_callback_calling_function(enum bpf_func_id func_id)
557 {
558         return func_id == BPF_FUNC_timer_set_callback;
559 }
560
561 static bool is_storage_get_function(enum bpf_func_id func_id)
562 {
563         return func_id == BPF_FUNC_sk_storage_get ||
564                func_id == BPF_FUNC_inode_storage_get ||
565                func_id == BPF_FUNC_task_storage_get ||
566                func_id == BPF_FUNC_cgrp_storage_get;
567 }
568
569 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id,
570                                         const struct bpf_map *map)
571 {
572         int ref_obj_uses = 0;
573
574         if (is_ptr_cast_function(func_id))
575                 ref_obj_uses++;
576         if (is_acquire_function(func_id, map))
577                 ref_obj_uses++;
578         if (is_dynptr_ref_function(func_id))
579                 ref_obj_uses++;
580
581         return ref_obj_uses > 1;
582 }
583
584 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
585 {
586         return BPF_CLASS(insn->code) == BPF_STX &&
587                BPF_MODE(insn->code) == BPF_ATOMIC &&
588                insn->imm == BPF_CMPXCHG;
589 }
590
591 /* string representation of 'enum bpf_reg_type'
592  *
593  * Note that reg_type_str() can not appear more than once in a single verbose()
594  * statement.
595  */
596 static const char *reg_type_str(struct bpf_verifier_env *env,
597                                 enum bpf_reg_type type)
598 {
599         char postfix[16] = {0}, prefix[64] = {0};
600         static const char * const str[] = {
601                 [NOT_INIT]              = "?",
602                 [SCALAR_VALUE]          = "scalar",
603                 [PTR_TO_CTX]            = "ctx",
604                 [CONST_PTR_TO_MAP]      = "map_ptr",
605                 [PTR_TO_MAP_VALUE]      = "map_value",
606                 [PTR_TO_STACK]          = "fp",
607                 [PTR_TO_PACKET]         = "pkt",
608                 [PTR_TO_PACKET_META]    = "pkt_meta",
609                 [PTR_TO_PACKET_END]     = "pkt_end",
610                 [PTR_TO_FLOW_KEYS]      = "flow_keys",
611                 [PTR_TO_SOCKET]         = "sock",
612                 [PTR_TO_SOCK_COMMON]    = "sock_common",
613                 [PTR_TO_TCP_SOCK]       = "tcp_sock",
614                 [PTR_TO_TP_BUFFER]      = "tp_buffer",
615                 [PTR_TO_XDP_SOCK]       = "xdp_sock",
616                 [PTR_TO_BTF_ID]         = "ptr_",
617                 [PTR_TO_MEM]            = "mem",
618                 [PTR_TO_BUF]            = "buf",
619                 [PTR_TO_FUNC]           = "func",
620                 [PTR_TO_MAP_KEY]        = "map_key",
621                 [CONST_PTR_TO_DYNPTR]   = "dynptr_ptr",
622         };
623
624         if (type & PTR_MAYBE_NULL) {
625                 if (base_type(type) == PTR_TO_BTF_ID)
626                         strncpy(postfix, "or_null_", 16);
627                 else
628                         strncpy(postfix, "_or_null", 16);
629         }
630
631         snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s",
632                  type & MEM_RDONLY ? "rdonly_" : "",
633                  type & MEM_RINGBUF ? "ringbuf_" : "",
634                  type & MEM_USER ? "user_" : "",
635                  type & MEM_PERCPU ? "percpu_" : "",
636                  type & MEM_RCU ? "rcu_" : "",
637                  type & PTR_UNTRUSTED ? "untrusted_" : "",
638                  type & PTR_TRUSTED ? "trusted_" : ""
639         );
640
641         snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s",
642                  prefix, str[base_type(type)], postfix);
643         return env->tmp_str_buf;
644 }
645
646 static char slot_type_char[] = {
647         [STACK_INVALID] = '?',
648         [STACK_SPILL]   = 'r',
649         [STACK_MISC]    = 'm',
650         [STACK_ZERO]    = '0',
651         [STACK_DYNPTR]  = 'd',
652         [STACK_ITER]    = 'i',
653 };
654
655 static void print_liveness(struct bpf_verifier_env *env,
656                            enum bpf_reg_liveness live)
657 {
658         if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE))
659             verbose(env, "_");
660         if (live & REG_LIVE_READ)
661                 verbose(env, "r");
662         if (live & REG_LIVE_WRITTEN)
663                 verbose(env, "w");
664         if (live & REG_LIVE_DONE)
665                 verbose(env, "D");
666 }
667
668 static int __get_spi(s32 off)
669 {
670         return (-off - 1) / BPF_REG_SIZE;
671 }
672
673 static struct bpf_func_state *func(struct bpf_verifier_env *env,
674                                    const struct bpf_reg_state *reg)
675 {
676         struct bpf_verifier_state *cur = env->cur_state;
677
678         return cur->frame[reg->frameno];
679 }
680
681 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots)
682 {
683        int allocated_slots = state->allocated_stack / BPF_REG_SIZE;
684
685        /* We need to check that slots between [spi - nr_slots + 1, spi] are
686         * within [0, allocated_stack).
687         *
688         * Please note that the spi grows downwards. For example, a dynptr
689         * takes the size of two stack slots; the first slot will be at
690         * spi and the second slot will be at spi - 1.
691         */
692        return spi - nr_slots + 1 >= 0 && spi < allocated_slots;
693 }
694
695 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
696                                   const char *obj_kind, int nr_slots)
697 {
698         int off, spi;
699
700         if (!tnum_is_const(reg->var_off)) {
701                 verbose(env, "%s has to be at a constant offset\n", obj_kind);
702                 return -EINVAL;
703         }
704
705         off = reg->off + reg->var_off.value;
706         if (off % BPF_REG_SIZE) {
707                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
708                 return -EINVAL;
709         }
710
711         spi = __get_spi(off);
712         if (spi + 1 < nr_slots) {
713                 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off);
714                 return -EINVAL;
715         }
716
717         if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots))
718                 return -ERANGE;
719         return spi;
720 }
721
722 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
723 {
724         return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS);
725 }
726
727 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots)
728 {
729         return stack_slot_obj_get_spi(env, reg, "iter", nr_slots);
730 }
731
732 static const char *btf_type_name(const struct btf *btf, u32 id)
733 {
734         return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off);
735 }
736
737 static const char *dynptr_type_str(enum bpf_dynptr_type type)
738 {
739         switch (type) {
740         case BPF_DYNPTR_TYPE_LOCAL:
741                 return "local";
742         case BPF_DYNPTR_TYPE_RINGBUF:
743                 return "ringbuf";
744         case BPF_DYNPTR_TYPE_SKB:
745                 return "skb";
746         case BPF_DYNPTR_TYPE_XDP:
747                 return "xdp";
748         case BPF_DYNPTR_TYPE_INVALID:
749                 return "<invalid>";
750         default:
751                 WARN_ONCE(1, "unknown dynptr type %d\n", type);
752                 return "<unknown>";
753         }
754 }
755
756 static const char *iter_type_str(const struct btf *btf, u32 btf_id)
757 {
758         if (!btf || btf_id == 0)
759                 return "<invalid>";
760
761         /* we already validated that type is valid and has conforming name */
762         return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1;
763 }
764
765 static const char *iter_state_str(enum bpf_iter_state state)
766 {
767         switch (state) {
768         case BPF_ITER_STATE_ACTIVE:
769                 return "active";
770         case BPF_ITER_STATE_DRAINED:
771                 return "drained";
772         case BPF_ITER_STATE_INVALID:
773                 return "<invalid>";
774         default:
775                 WARN_ONCE(1, "unknown iter state %d\n", state);
776                 return "<unknown>";
777         }
778 }
779
780 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
781 {
782         env->scratched_regs |= 1U << regno;
783 }
784
785 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi)
786 {
787         env->scratched_stack_slots |= 1ULL << spi;
788 }
789
790 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno)
791 {
792         return (env->scratched_regs >> regno) & 1;
793 }
794
795 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno)
796 {
797         return (env->scratched_stack_slots >> regno) & 1;
798 }
799
800 static bool verifier_state_scratched(const struct bpf_verifier_env *env)
801 {
802         return env->scratched_regs || env->scratched_stack_slots;
803 }
804
805 static void mark_verifier_state_clean(struct bpf_verifier_env *env)
806 {
807         env->scratched_regs = 0U;
808         env->scratched_stack_slots = 0ULL;
809 }
810
811 /* Used for printing the entire verifier state. */
812 static void mark_verifier_state_scratched(struct bpf_verifier_env *env)
813 {
814         env->scratched_regs = ~0U;
815         env->scratched_stack_slots = ~0ULL;
816 }
817
818 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
819 {
820         switch (arg_type & DYNPTR_TYPE_FLAG_MASK) {
821         case DYNPTR_TYPE_LOCAL:
822                 return BPF_DYNPTR_TYPE_LOCAL;
823         case DYNPTR_TYPE_RINGBUF:
824                 return BPF_DYNPTR_TYPE_RINGBUF;
825         case DYNPTR_TYPE_SKB:
826                 return BPF_DYNPTR_TYPE_SKB;
827         case DYNPTR_TYPE_XDP:
828                 return BPF_DYNPTR_TYPE_XDP;
829         default:
830                 return BPF_DYNPTR_TYPE_INVALID;
831         }
832 }
833
834 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
835 {
836         switch (type) {
837         case BPF_DYNPTR_TYPE_LOCAL:
838                 return DYNPTR_TYPE_LOCAL;
839         case BPF_DYNPTR_TYPE_RINGBUF:
840                 return DYNPTR_TYPE_RINGBUF;
841         case BPF_DYNPTR_TYPE_SKB:
842                 return DYNPTR_TYPE_SKB;
843         case BPF_DYNPTR_TYPE_XDP:
844                 return DYNPTR_TYPE_XDP;
845         default:
846                 return 0;
847         }
848 }
849
850 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
851 {
852         return type == BPF_DYNPTR_TYPE_RINGBUF;
853 }
854
855 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
856                               enum bpf_dynptr_type type,
857                               bool first_slot, int dynptr_id);
858
859 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
860                                 struct bpf_reg_state *reg);
861
862 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env,
863                                    struct bpf_reg_state *sreg1,
864                                    struct bpf_reg_state *sreg2,
865                                    enum bpf_dynptr_type type)
866 {
867         int id = ++env->id_gen;
868
869         __mark_dynptr_reg(sreg1, type, true, id);
870         __mark_dynptr_reg(sreg2, type, false, id);
871 }
872
873 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env,
874                                struct bpf_reg_state *reg,
875                                enum bpf_dynptr_type type)
876 {
877         __mark_dynptr_reg(reg, type, true, ++env->id_gen);
878 }
879
880 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
881                                         struct bpf_func_state *state, int spi);
882
883 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
884                                    enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id)
885 {
886         struct bpf_func_state *state = func(env, reg);
887         enum bpf_dynptr_type type;
888         int spi, i, err;
889
890         spi = dynptr_get_spi(env, reg);
891         if (spi < 0)
892                 return spi;
893
894         /* We cannot assume both spi and spi - 1 belong to the same dynptr,
895          * hence we need to call destroy_if_dynptr_stack_slot twice for both,
896          * to ensure that for the following example:
897          *      [d1][d1][d2][d2]
898          * spi    3   2   1   0
899          * So marking spi = 2 should lead to destruction of both d1 and d2. In
900          * case they do belong to same dynptr, second call won't see slot_type
901          * as STACK_DYNPTR and will simply skip destruction.
902          */
903         err = destroy_if_dynptr_stack_slot(env, state, spi);
904         if (err)
905                 return err;
906         err = destroy_if_dynptr_stack_slot(env, state, spi - 1);
907         if (err)
908                 return err;
909
910         for (i = 0; i < BPF_REG_SIZE; i++) {
911                 state->stack[spi].slot_type[i] = STACK_DYNPTR;
912                 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR;
913         }
914
915         type = arg_to_dynptr_type(arg_type);
916         if (type == BPF_DYNPTR_TYPE_INVALID)
917                 return -EINVAL;
918
919         mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr,
920                                &state->stack[spi - 1].spilled_ptr, type);
921
922         if (dynptr_type_refcounted(type)) {
923                 /* The id is used to track proper releasing */
924                 int id;
925
926                 if (clone_ref_obj_id)
927                         id = clone_ref_obj_id;
928                 else
929                         id = acquire_reference_state(env, insn_idx);
930
931                 if (id < 0)
932                         return id;
933
934                 state->stack[spi].spilled_ptr.ref_obj_id = id;
935                 state->stack[spi - 1].spilled_ptr.ref_obj_id = id;
936         }
937
938         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
939         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
940
941         return 0;
942 }
943
944 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi)
945 {
946         int i;
947
948         for (i = 0; i < BPF_REG_SIZE; i++) {
949                 state->stack[spi].slot_type[i] = STACK_INVALID;
950                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
951         }
952
953         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
954         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
955
956         /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot?
957          *
958          * While we don't allow reading STACK_INVALID, it is still possible to
959          * do <8 byte writes marking some but not all slots as STACK_MISC. Then,
960          * helpers or insns can do partial read of that part without failing,
961          * but check_stack_range_initialized, check_stack_read_var_off, and
962          * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of
963          * the slot conservatively. Hence we need to prevent those liveness
964          * marking walks.
965          *
966          * This was not a problem before because STACK_INVALID is only set by
967          * default (where the default reg state has its reg->parent as NULL), or
968          * in clean_live_states after REG_LIVE_DONE (at which point
969          * mark_reg_read won't walk reg->parent chain), but not randomly during
970          * verifier state exploration (like we did above). Hence, for our case
971          * parentage chain will still be live (i.e. reg->parent may be
972          * non-NULL), while earlier reg->parent was NULL, so we need
973          * REG_LIVE_WRITTEN to screen off read marker propagation when it is
974          * done later on reads or by mark_dynptr_read as well to unnecessary
975          * mark registers in verifier state.
976          */
977         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
978         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
979 }
980
981 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
982 {
983         struct bpf_func_state *state = func(env, reg);
984         int spi, ref_obj_id, i;
985
986         spi = dynptr_get_spi(env, reg);
987         if (spi < 0)
988                 return spi;
989
990         if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
991                 invalidate_dynptr(env, state, spi);
992                 return 0;
993         }
994
995         ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id;
996
997         /* If the dynptr has a ref_obj_id, then we need to invalidate
998          * two things:
999          *
1000          * 1) Any dynptrs with a matching ref_obj_id (clones)
1001          * 2) Any slices derived from this dynptr.
1002          */
1003
1004         /* Invalidate any slices associated with this dynptr */
1005         WARN_ON_ONCE(release_reference(env, ref_obj_id));
1006
1007         /* Invalidate any dynptr clones */
1008         for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1009                 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id)
1010                         continue;
1011
1012                 /* it should always be the case that if the ref obj id
1013                  * matches then the stack slot also belongs to a
1014                  * dynptr
1015                  */
1016                 if (state->stack[i].slot_type[0] != STACK_DYNPTR) {
1017                         verbose(env, "verifier internal error: misconfigured ref_obj_id\n");
1018                         return -EFAULT;
1019                 }
1020                 if (state->stack[i].spilled_ptr.dynptr.first_slot)
1021                         invalidate_dynptr(env, state, i);
1022         }
1023
1024         return 0;
1025 }
1026
1027 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
1028                                struct bpf_reg_state *reg);
1029
1030 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1031 {
1032         if (!env->allow_ptr_leaks)
1033                 __mark_reg_not_init(env, reg);
1034         else
1035                 __mark_reg_unknown(env, reg);
1036 }
1037
1038 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env,
1039                                         struct bpf_func_state *state, int spi)
1040 {
1041         struct bpf_func_state *fstate;
1042         struct bpf_reg_state *dreg;
1043         int i, dynptr_id;
1044
1045         /* We always ensure that STACK_DYNPTR is never set partially,
1046          * hence just checking for slot_type[0] is enough. This is
1047          * different for STACK_SPILL, where it may be only set for
1048          * 1 byte, so code has to use is_spilled_reg.
1049          */
1050         if (state->stack[spi].slot_type[0] != STACK_DYNPTR)
1051                 return 0;
1052
1053         /* Reposition spi to first slot */
1054         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1055                 spi = spi + 1;
1056
1057         if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) {
1058                 verbose(env, "cannot overwrite referenced dynptr\n");
1059                 return -EINVAL;
1060         }
1061
1062         mark_stack_slot_scratched(env, spi);
1063         mark_stack_slot_scratched(env, spi - 1);
1064
1065         /* Writing partially to one dynptr stack slot destroys both. */
1066         for (i = 0; i < BPF_REG_SIZE; i++) {
1067                 state->stack[spi].slot_type[i] = STACK_INVALID;
1068                 state->stack[spi - 1].slot_type[i] = STACK_INVALID;
1069         }
1070
1071         dynptr_id = state->stack[spi].spilled_ptr.id;
1072         /* Invalidate any slices associated with this dynptr */
1073         bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({
1074                 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */
1075                 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM)
1076                         continue;
1077                 if (dreg->dynptr_id == dynptr_id)
1078                         mark_reg_invalid(env, dreg);
1079         }));
1080
1081         /* Do not release reference state, we are destroying dynptr on stack,
1082          * not using some helper to release it. Just reset register.
1083          */
1084         __mark_reg_not_init(env, &state->stack[spi].spilled_ptr);
1085         __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr);
1086
1087         /* Same reason as unmark_stack_slots_dynptr above */
1088         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
1089         state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN;
1090
1091         return 0;
1092 }
1093
1094 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1095 {
1096         int spi;
1097
1098         if (reg->type == CONST_PTR_TO_DYNPTR)
1099                 return false;
1100
1101         spi = dynptr_get_spi(env, reg);
1102
1103         /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an
1104          * error because this just means the stack state hasn't been updated yet.
1105          * We will do check_mem_access to check and update stack bounds later.
1106          */
1107         if (spi < 0 && spi != -ERANGE)
1108                 return false;
1109
1110         /* We don't need to check if the stack slots are marked by previous
1111          * dynptr initializations because we allow overwriting existing unreferenced
1112          * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls
1113          * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are
1114          * touching are completely destructed before we reinitialize them for a new
1115          * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early
1116          * instead of delaying it until the end where the user will get "Unreleased
1117          * reference" error.
1118          */
1119         return true;
1120 }
1121
1122 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
1123 {
1124         struct bpf_func_state *state = func(env, reg);
1125         int i, spi;
1126
1127         /* This already represents first slot of initialized bpf_dynptr.
1128          *
1129          * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to
1130          * check_func_arg_reg_off's logic, so we don't need to check its
1131          * offset and alignment.
1132          */
1133         if (reg->type == CONST_PTR_TO_DYNPTR)
1134                 return true;
1135
1136         spi = dynptr_get_spi(env, reg);
1137         if (spi < 0)
1138                 return false;
1139         if (!state->stack[spi].spilled_ptr.dynptr.first_slot)
1140                 return false;
1141
1142         for (i = 0; i < BPF_REG_SIZE; i++) {
1143                 if (state->stack[spi].slot_type[i] != STACK_DYNPTR ||
1144                     state->stack[spi - 1].slot_type[i] != STACK_DYNPTR)
1145                         return false;
1146         }
1147
1148         return true;
1149 }
1150
1151 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1152                                     enum bpf_arg_type arg_type)
1153 {
1154         struct bpf_func_state *state = func(env, reg);
1155         enum bpf_dynptr_type dynptr_type;
1156         int spi;
1157
1158         /* ARG_PTR_TO_DYNPTR takes any type of dynptr */
1159         if (arg_type == ARG_PTR_TO_DYNPTR)
1160                 return true;
1161
1162         dynptr_type = arg_to_dynptr_type(arg_type);
1163         if (reg->type == CONST_PTR_TO_DYNPTR) {
1164                 return reg->dynptr.type == dynptr_type;
1165         } else {
1166                 spi = dynptr_get_spi(env, reg);
1167                 if (spi < 0)
1168                         return false;
1169                 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type;
1170         }
1171 }
1172
1173 static void __mark_reg_known_zero(struct bpf_reg_state *reg);
1174
1175 static int mark_stack_slots_iter(struct bpf_verifier_env *env,
1176                                  struct bpf_reg_state *reg, int insn_idx,
1177                                  struct btf *btf, u32 btf_id, int nr_slots)
1178 {
1179         struct bpf_func_state *state = func(env, reg);
1180         int spi, i, j, id;
1181
1182         spi = iter_get_spi(env, reg, nr_slots);
1183         if (spi < 0)
1184                 return spi;
1185
1186         id = acquire_reference_state(env, insn_idx);
1187         if (id < 0)
1188                 return id;
1189
1190         for (i = 0; i < nr_slots; i++) {
1191                 struct bpf_stack_state *slot = &state->stack[spi - i];
1192                 struct bpf_reg_state *st = &slot->spilled_ptr;
1193
1194                 __mark_reg_known_zero(st);
1195                 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */
1196                 st->live |= REG_LIVE_WRITTEN;
1197                 st->ref_obj_id = i == 0 ? id : 0;
1198                 st->iter.btf = btf;
1199                 st->iter.btf_id = btf_id;
1200                 st->iter.state = BPF_ITER_STATE_ACTIVE;
1201                 st->iter.depth = 0;
1202
1203                 for (j = 0; j < BPF_REG_SIZE; j++)
1204                         slot->slot_type[j] = STACK_ITER;
1205
1206                 mark_stack_slot_scratched(env, spi - i);
1207         }
1208
1209         return 0;
1210 }
1211
1212 static int unmark_stack_slots_iter(struct bpf_verifier_env *env,
1213                                    struct bpf_reg_state *reg, int nr_slots)
1214 {
1215         struct bpf_func_state *state = func(env, reg);
1216         int spi, i, j;
1217
1218         spi = iter_get_spi(env, reg, nr_slots);
1219         if (spi < 0)
1220                 return spi;
1221
1222         for (i = 0; i < nr_slots; i++) {
1223                 struct bpf_stack_state *slot = &state->stack[spi - i];
1224                 struct bpf_reg_state *st = &slot->spilled_ptr;
1225
1226                 if (i == 0)
1227                         WARN_ON_ONCE(release_reference(env, st->ref_obj_id));
1228
1229                 __mark_reg_not_init(env, st);
1230
1231                 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */
1232                 st->live |= REG_LIVE_WRITTEN;
1233
1234                 for (j = 0; j < BPF_REG_SIZE; j++)
1235                         slot->slot_type[j] = STACK_INVALID;
1236
1237                 mark_stack_slot_scratched(env, spi - i);
1238         }
1239
1240         return 0;
1241 }
1242
1243 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env,
1244                                      struct bpf_reg_state *reg, int nr_slots)
1245 {
1246         struct bpf_func_state *state = func(env, reg);
1247         int spi, i, j;
1248
1249         /* For -ERANGE (i.e. spi not falling into allocated stack slots), we
1250          * will do check_mem_access to check and update stack bounds later, so
1251          * return true for that case.
1252          */
1253         spi = iter_get_spi(env, reg, nr_slots);
1254         if (spi == -ERANGE)
1255                 return true;
1256         if (spi < 0)
1257                 return false;
1258
1259         for (i = 0; i < nr_slots; i++) {
1260                 struct bpf_stack_state *slot = &state->stack[spi - i];
1261
1262                 for (j = 0; j < BPF_REG_SIZE; j++)
1263                         if (slot->slot_type[j] == STACK_ITER)
1264                                 return false;
1265         }
1266
1267         return true;
1268 }
1269
1270 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
1271                                    struct btf *btf, u32 btf_id, int nr_slots)
1272 {
1273         struct bpf_func_state *state = func(env, reg);
1274         int spi, i, j;
1275
1276         spi = iter_get_spi(env, reg, nr_slots);
1277         if (spi < 0)
1278                 return false;
1279
1280         for (i = 0; i < nr_slots; i++) {
1281                 struct bpf_stack_state *slot = &state->stack[spi - i];
1282                 struct bpf_reg_state *st = &slot->spilled_ptr;
1283
1284                 /* only main (first) slot has ref_obj_id set */
1285                 if (i == 0 && !st->ref_obj_id)
1286                         return false;
1287                 if (i != 0 && st->ref_obj_id)
1288                         return false;
1289                 if (st->iter.btf != btf || st->iter.btf_id != btf_id)
1290                         return false;
1291
1292                 for (j = 0; j < BPF_REG_SIZE; j++)
1293                         if (slot->slot_type[j] != STACK_ITER)
1294                                 return false;
1295         }
1296
1297         return true;
1298 }
1299
1300 /* Check if given stack slot is "special":
1301  *   - spilled register state (STACK_SPILL);
1302  *   - dynptr state (STACK_DYNPTR);
1303  *   - iter state (STACK_ITER).
1304  */
1305 static bool is_stack_slot_special(const struct bpf_stack_state *stack)
1306 {
1307         enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1];
1308
1309         switch (type) {
1310         case STACK_SPILL:
1311         case STACK_DYNPTR:
1312         case STACK_ITER:
1313                 return true;
1314         case STACK_INVALID:
1315         case STACK_MISC:
1316         case STACK_ZERO:
1317                 return false;
1318         default:
1319                 WARN_ONCE(1, "unknown stack slot type %d\n", type);
1320                 return true;
1321         }
1322 }
1323
1324 /* The reg state of a pointer or a bounded scalar was saved when
1325  * it was spilled to the stack.
1326  */
1327 static bool is_spilled_reg(const struct bpf_stack_state *stack)
1328 {
1329         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL;
1330 }
1331
1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack)
1333 {
1334         return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL &&
1335                stack->spilled_ptr.type == SCALAR_VALUE;
1336 }
1337
1338 static void scrub_spilled_slot(u8 *stype)
1339 {
1340         if (*stype != STACK_INVALID)
1341                 *stype = STACK_MISC;
1342 }
1343
1344 static void print_verifier_state(struct bpf_verifier_env *env,
1345                                  const struct bpf_func_state *state,
1346                                  bool print_all)
1347 {
1348         const struct bpf_reg_state *reg;
1349         enum bpf_reg_type t;
1350         int i;
1351
1352         if (state->frameno)
1353                 verbose(env, " frame%d:", state->frameno);
1354         for (i = 0; i < MAX_BPF_REG; i++) {
1355                 reg = &state->regs[i];
1356                 t = reg->type;
1357                 if (t == NOT_INIT)
1358                         continue;
1359                 if (!print_all && !reg_scratched(env, i))
1360                         continue;
1361                 verbose(env, " R%d", i);
1362                 print_liveness(env, reg->live);
1363                 verbose(env, "=");
1364                 if (t == SCALAR_VALUE && reg->precise)
1365                         verbose(env, "P");
1366                 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) &&
1367                     tnum_is_const(reg->var_off)) {
1368                         /* reg->off should be 0 for SCALAR_VALUE */
1369                         verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1370                         verbose(env, "%lld", reg->var_off.value + reg->off);
1371                 } else {
1372                         const char *sep = "";
1373
1374                         verbose(env, "%s", reg_type_str(env, t));
1375                         if (base_type(t) == PTR_TO_BTF_ID)
1376                                 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id));
1377                         verbose(env, "(");
1378 /*
1379  * _a stands for append, was shortened to avoid multiline statements below.
1380  * This macro is used to output a comma separated list of attributes.
1381  */
1382 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; })
1383
1384                         if (reg->id)
1385                                 verbose_a("id=%d", reg->id);
1386                         if (reg->ref_obj_id)
1387                                 verbose_a("ref_obj_id=%d", reg->ref_obj_id);
1388                         if (type_is_non_owning_ref(reg->type))
1389                                 verbose_a("%s", "non_own_ref");
1390                         if (t != SCALAR_VALUE)
1391                                 verbose_a("off=%d", reg->off);
1392                         if (type_is_pkt_pointer(t))
1393                                 verbose_a("r=%d", reg->range);
1394                         else if (base_type(t) == CONST_PTR_TO_MAP ||
1395                                  base_type(t) == PTR_TO_MAP_KEY ||
1396                                  base_type(t) == PTR_TO_MAP_VALUE)
1397                                 verbose_a("ks=%d,vs=%d",
1398                                           reg->map_ptr->key_size,
1399                                           reg->map_ptr->value_size);
1400                         if (tnum_is_const(reg->var_off)) {
1401                                 /* Typically an immediate SCALAR_VALUE, but
1402                                  * could be a pointer whose offset is too big
1403                                  * for reg->off
1404                                  */
1405                                 verbose_a("imm=%llx", reg->var_off.value);
1406                         } else {
1407                                 if (reg->smin_value != reg->umin_value &&
1408                                     reg->smin_value != S64_MIN)
1409                                         verbose_a("smin=%lld", (long long)reg->smin_value);
1410                                 if (reg->smax_value != reg->umax_value &&
1411                                     reg->smax_value != S64_MAX)
1412                                         verbose_a("smax=%lld", (long long)reg->smax_value);
1413                                 if (reg->umin_value != 0)
1414                                         verbose_a("umin=%llu", (unsigned long long)reg->umin_value);
1415                                 if (reg->umax_value != U64_MAX)
1416                                         verbose_a("umax=%llu", (unsigned long long)reg->umax_value);
1417                                 if (!tnum_is_unknown(reg->var_off)) {
1418                                         char tn_buf[48];
1419
1420                                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
1421                                         verbose_a("var_off=%s", tn_buf);
1422                                 }
1423                                 if (reg->s32_min_value != reg->smin_value &&
1424                                     reg->s32_min_value != S32_MIN)
1425                                         verbose_a("s32_min=%d", (int)(reg->s32_min_value));
1426                                 if (reg->s32_max_value != reg->smax_value &&
1427                                     reg->s32_max_value != S32_MAX)
1428                                         verbose_a("s32_max=%d", (int)(reg->s32_max_value));
1429                                 if (reg->u32_min_value != reg->umin_value &&
1430                                     reg->u32_min_value != U32_MIN)
1431                                         verbose_a("u32_min=%d", (int)(reg->u32_min_value));
1432                                 if (reg->u32_max_value != reg->umax_value &&
1433                                     reg->u32_max_value != U32_MAX)
1434                                         verbose_a("u32_max=%d", (int)(reg->u32_max_value));
1435                         }
1436 #undef verbose_a
1437
1438                         verbose(env, ")");
1439                 }
1440         }
1441         for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
1442                 char types_buf[BPF_REG_SIZE + 1];
1443                 bool valid = false;
1444                 int j;
1445
1446                 for (j = 0; j < BPF_REG_SIZE; j++) {
1447                         if (state->stack[i].slot_type[j] != STACK_INVALID)
1448                                 valid = true;
1449                         types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1450                 }
1451                 types_buf[BPF_REG_SIZE] = 0;
1452                 if (!valid)
1453                         continue;
1454                 if (!print_all && !stack_slot_scratched(env, i))
1455                         continue;
1456                 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) {
1457                 case STACK_SPILL:
1458                         reg = &state->stack[i].spilled_ptr;
1459                         t = reg->type;
1460
1461                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1462                         print_liveness(env, reg->live);
1463                         verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t));
1464                         if (t == SCALAR_VALUE && reg->precise)
1465                                 verbose(env, "P");
1466                         if (t == SCALAR_VALUE && tnum_is_const(reg->var_off))
1467                                 verbose(env, "%lld", reg->var_off.value + reg->off);
1468                         break;
1469                 case STACK_DYNPTR:
1470                         i += BPF_DYNPTR_NR_SLOTS - 1;
1471                         reg = &state->stack[i].spilled_ptr;
1472
1473                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1474                         print_liveness(env, reg->live);
1475                         verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type));
1476                         if (reg->ref_obj_id)
1477                                 verbose(env, "(ref_id=%d)", reg->ref_obj_id);
1478                         break;
1479                 case STACK_ITER:
1480                         /* only main slot has ref_obj_id set; skip others */
1481                         reg = &state->stack[i].spilled_ptr;
1482                         if (!reg->ref_obj_id)
1483                                 continue;
1484
1485                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1486                         print_liveness(env, reg->live);
1487                         verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)",
1488                                 iter_type_str(reg->iter.btf, reg->iter.btf_id),
1489                                 reg->ref_obj_id, iter_state_str(reg->iter.state),
1490                                 reg->iter.depth);
1491                         break;
1492                 case STACK_MISC:
1493                 case STACK_ZERO:
1494                 default:
1495                         reg = &state->stack[i].spilled_ptr;
1496
1497                         for (j = 0; j < BPF_REG_SIZE; j++)
1498                                 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]];
1499                         types_buf[BPF_REG_SIZE] = 0;
1500
1501                         verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
1502                         print_liveness(env, reg->live);
1503                         verbose(env, "=%s", types_buf);
1504                         break;
1505                 }
1506         }
1507         if (state->acquired_refs && state->refs[0].id) {
1508                 verbose(env, " refs=%d", state->refs[0].id);
1509                 for (i = 1; i < state->acquired_refs; i++)
1510                         if (state->refs[i].id)
1511                                 verbose(env, ",%d", state->refs[i].id);
1512         }
1513         if (state->in_callback_fn)
1514                 verbose(env, " cb");
1515         if (state->in_async_callback_fn)
1516                 verbose(env, " async_cb");
1517         verbose(env, "\n");
1518         if (!print_all)
1519                 mark_verifier_state_clean(env);
1520 }
1521
1522 static inline u32 vlog_alignment(u32 pos)
1523 {
1524         return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT),
1525                         BPF_LOG_MIN_ALIGNMENT) - pos - 1;
1526 }
1527
1528 static void print_insn_state(struct bpf_verifier_env *env,
1529                              const struct bpf_func_state *state)
1530 {
1531         if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) {
1532                 /* remove new line character */
1533                 bpf_vlog_reset(&env->log, env->prev_log_pos - 1);
1534                 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' ');
1535         } else {
1536                 verbose(env, "%d:", env->insn_idx);
1537         }
1538         print_verifier_state(env, state, false);
1539 }
1540
1541 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too
1542  * small to hold src. This is different from krealloc since we don't want to preserve
1543  * the contents of dst.
1544  *
1545  * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could
1546  * not be allocated.
1547  */
1548 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags)
1549 {
1550         size_t alloc_bytes;
1551         void *orig = dst;
1552         size_t bytes;
1553
1554         if (ZERO_OR_NULL_PTR(src))
1555                 goto out;
1556
1557         if (unlikely(check_mul_overflow(n, size, &bytes)))
1558                 return NULL;
1559
1560         alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes));
1561         dst = krealloc(orig, alloc_bytes, flags);
1562         if (!dst) {
1563                 kfree(orig);
1564                 return NULL;
1565         }
1566
1567         memcpy(dst, src, bytes);
1568 out:
1569         return dst ? dst : ZERO_SIZE_PTR;
1570 }
1571
1572 /* resize an array from old_n items to new_n items. the array is reallocated if it's too
1573  * small to hold new_n items. new items are zeroed out if the array grows.
1574  *
1575  * Contrary to krealloc_array, does not free arr if new_n is zero.
1576  */
1577 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size)
1578 {
1579         size_t alloc_size;
1580         void *new_arr;
1581
1582         if (!new_n || old_n == new_n)
1583                 goto out;
1584
1585         alloc_size = kmalloc_size_roundup(size_mul(new_n, size));
1586         new_arr = krealloc(arr, alloc_size, GFP_KERNEL);
1587         if (!new_arr) {
1588                 kfree(arr);
1589                 return NULL;
1590         }
1591         arr = new_arr;
1592
1593         if (new_n > old_n)
1594                 memset(arr + old_n * size, 0, (new_n - old_n) * size);
1595
1596 out:
1597         return arr ? arr : ZERO_SIZE_PTR;
1598 }
1599
1600 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1601 {
1602         dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs,
1603                                sizeof(struct bpf_reference_state), GFP_KERNEL);
1604         if (!dst->refs)
1605                 return -ENOMEM;
1606
1607         dst->acquired_refs = src->acquired_refs;
1608         return 0;
1609 }
1610
1611 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src)
1612 {
1613         size_t n = src->allocated_stack / BPF_REG_SIZE;
1614
1615         dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state),
1616                                 GFP_KERNEL);
1617         if (!dst->stack)
1618                 return -ENOMEM;
1619
1620         dst->allocated_stack = src->allocated_stack;
1621         return 0;
1622 }
1623
1624 static int resize_reference_state(struct bpf_func_state *state, size_t n)
1625 {
1626         state->refs = realloc_array(state->refs, state->acquired_refs, n,
1627                                     sizeof(struct bpf_reference_state));
1628         if (!state->refs)
1629                 return -ENOMEM;
1630
1631         state->acquired_refs = n;
1632         return 0;
1633 }
1634
1635 static int grow_stack_state(struct bpf_func_state *state, int size)
1636 {
1637         size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE;
1638
1639         if (old_n >= n)
1640                 return 0;
1641
1642         state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state));
1643         if (!state->stack)
1644                 return -ENOMEM;
1645
1646         state->allocated_stack = size;
1647         return 0;
1648 }
1649
1650 /* Acquire a pointer id from the env and update the state->refs to include
1651  * this new pointer reference.
1652  * On success, returns a valid pointer id to associate with the register
1653  * On failure, returns a negative errno.
1654  */
1655 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx)
1656 {
1657         struct bpf_func_state *state = cur_func(env);
1658         int new_ofs = state->acquired_refs;
1659         int id, err;
1660
1661         err = resize_reference_state(state, state->acquired_refs + 1);
1662         if (err)
1663                 return err;
1664         id = ++env->id_gen;
1665         state->refs[new_ofs].id = id;
1666         state->refs[new_ofs].insn_idx = insn_idx;
1667         state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0;
1668
1669         return id;
1670 }
1671
1672 /* release function corresponding to acquire_reference_state(). Idempotent. */
1673 static int release_reference_state(struct bpf_func_state *state, int ptr_id)
1674 {
1675         int i, last_idx;
1676
1677         last_idx = state->acquired_refs - 1;
1678         for (i = 0; i < state->acquired_refs; i++) {
1679                 if (state->refs[i].id == ptr_id) {
1680                         /* Cannot release caller references in callbacks */
1681                         if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
1682                                 return -EINVAL;
1683                         if (last_idx && i != last_idx)
1684                                 memcpy(&state->refs[i], &state->refs[last_idx],
1685                                        sizeof(*state->refs));
1686                         memset(&state->refs[last_idx], 0, sizeof(*state->refs));
1687                         state->acquired_refs--;
1688                         return 0;
1689                 }
1690         }
1691         return -EINVAL;
1692 }
1693
1694 static void free_func_state(struct bpf_func_state *state)
1695 {
1696         if (!state)
1697                 return;
1698         kfree(state->refs);
1699         kfree(state->stack);
1700         kfree(state);
1701 }
1702
1703 static void clear_jmp_history(struct bpf_verifier_state *state)
1704 {
1705         kfree(state->jmp_history);
1706         state->jmp_history = NULL;
1707         state->jmp_history_cnt = 0;
1708 }
1709
1710 static void free_verifier_state(struct bpf_verifier_state *state,
1711                                 bool free_self)
1712 {
1713         int i;
1714
1715         for (i = 0; i <= state->curframe; i++) {
1716                 free_func_state(state->frame[i]);
1717                 state->frame[i] = NULL;
1718         }
1719         clear_jmp_history(state);
1720         if (free_self)
1721                 kfree(state);
1722 }
1723
1724 /* copy verifier state from src to dst growing dst stack space
1725  * when necessary to accommodate larger src stack
1726  */
1727 static int copy_func_state(struct bpf_func_state *dst,
1728                            const struct bpf_func_state *src)
1729 {
1730         int err;
1731
1732         memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs));
1733         err = copy_reference_state(dst, src);
1734         if (err)
1735                 return err;
1736         return copy_stack_state(dst, src);
1737 }
1738
1739 static int copy_verifier_state(struct bpf_verifier_state *dst_state,
1740                                const struct bpf_verifier_state *src)
1741 {
1742         struct bpf_func_state *dst;
1743         int i, err;
1744
1745         dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history,
1746                                             src->jmp_history_cnt, sizeof(struct bpf_idx_pair),
1747                                             GFP_USER);
1748         if (!dst_state->jmp_history)
1749                 return -ENOMEM;
1750         dst_state->jmp_history_cnt = src->jmp_history_cnt;
1751
1752         /* if dst has more stack frames then src frame, free them */
1753         for (i = src->curframe + 1; i <= dst_state->curframe; i++) {
1754                 free_func_state(dst_state->frame[i]);
1755                 dst_state->frame[i] = NULL;
1756         }
1757         dst_state->speculative = src->speculative;
1758         dst_state->active_rcu_lock = src->active_rcu_lock;
1759         dst_state->curframe = src->curframe;
1760         dst_state->active_lock.ptr = src->active_lock.ptr;
1761         dst_state->active_lock.id = src->active_lock.id;
1762         dst_state->branches = src->branches;
1763         dst_state->parent = src->parent;
1764         dst_state->first_insn_idx = src->first_insn_idx;
1765         dst_state->last_insn_idx = src->last_insn_idx;
1766         for (i = 0; i <= src->curframe; i++) {
1767                 dst = dst_state->frame[i];
1768                 if (!dst) {
1769                         dst = kzalloc(sizeof(*dst), GFP_KERNEL);
1770                         if (!dst)
1771                                 return -ENOMEM;
1772                         dst_state->frame[i] = dst;
1773                 }
1774                 err = copy_func_state(dst, src->frame[i]);
1775                 if (err)
1776                         return err;
1777         }
1778         return 0;
1779 }
1780
1781 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
1782 {
1783         while (st) {
1784                 u32 br = --st->branches;
1785
1786                 /* WARN_ON(br > 1) technically makes sense here,
1787                  * but see comment in push_stack(), hence:
1788                  */
1789                 WARN_ONCE((int)br < 0,
1790                           "BUG update_branch_counts:branches_to_explore=%d\n",
1791                           br);
1792                 if (br)
1793                         break;
1794                 st = st->parent;
1795         }
1796 }
1797
1798 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
1799                      int *insn_idx, bool pop_log)
1800 {
1801         struct bpf_verifier_state *cur = env->cur_state;
1802         struct bpf_verifier_stack_elem *elem, *head = env->head;
1803         int err;
1804
1805         if (env->head == NULL)
1806                 return -ENOENT;
1807
1808         if (cur) {
1809                 err = copy_verifier_state(cur, &head->st);
1810                 if (err)
1811                         return err;
1812         }
1813         if (pop_log)
1814                 bpf_vlog_reset(&env->log, head->log_pos);
1815         if (insn_idx)
1816                 *insn_idx = head->insn_idx;
1817         if (prev_insn_idx)
1818                 *prev_insn_idx = head->prev_insn_idx;
1819         elem = head->next;
1820         free_verifier_state(&head->st, false);
1821         kfree(head);
1822         env->head = elem;
1823         env->stack_size--;
1824         return 0;
1825 }
1826
1827 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
1828                                              int insn_idx, int prev_insn_idx,
1829                                              bool speculative)
1830 {
1831         struct bpf_verifier_state *cur = env->cur_state;
1832         struct bpf_verifier_stack_elem *elem;
1833         int err;
1834
1835         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
1836         if (!elem)
1837                 goto err;
1838
1839         elem->insn_idx = insn_idx;
1840         elem->prev_insn_idx = prev_insn_idx;
1841         elem->next = env->head;
1842         elem->log_pos = env->log.end_pos;
1843         env->head = elem;
1844         env->stack_size++;
1845         err = copy_verifier_state(&elem->st, cur);
1846         if (err)
1847                 goto err;
1848         elem->st.speculative |= speculative;
1849         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
1850                 verbose(env, "The sequence of %d jumps is too complex.\n",
1851                         env->stack_size);
1852                 goto err;
1853         }
1854         if (elem->st.parent) {
1855                 ++elem->st.parent->branches;
1856                 /* WARN_ON(branches > 2) technically makes sense here,
1857                  * but
1858                  * 1. speculative states will bump 'branches' for non-branch
1859                  * instructions
1860                  * 2. is_state_visited() heuristics may decide not to create
1861                  * a new state for a sequence of branches and all such current
1862                  * and cloned states will be pointing to a single parent state
1863                  * which might have large 'branches' count.
1864                  */
1865         }
1866         return &elem->st;
1867 err:
1868         free_verifier_state(env->cur_state, true);
1869         env->cur_state = NULL;
1870         /* pop all elements and return */
1871         while (!pop_stack(env, NULL, NULL, false));
1872         return NULL;
1873 }
1874
1875 #define CALLER_SAVED_REGS 6
1876 static const int caller_saved[CALLER_SAVED_REGS] = {
1877         BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
1878 };
1879
1880 /* This helper doesn't clear reg->id */
1881 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1882 {
1883         reg->var_off = tnum_const(imm);
1884         reg->smin_value = (s64)imm;
1885         reg->smax_value = (s64)imm;
1886         reg->umin_value = imm;
1887         reg->umax_value = imm;
1888
1889         reg->s32_min_value = (s32)imm;
1890         reg->s32_max_value = (s32)imm;
1891         reg->u32_min_value = (u32)imm;
1892         reg->u32_max_value = (u32)imm;
1893 }
1894
1895 /* Mark the unknown part of a register (variable offset or scalar value) as
1896  * known to have the value @imm.
1897  */
1898 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm)
1899 {
1900         /* Clear off and union(map_ptr, range) */
1901         memset(((u8 *)reg) + sizeof(reg->type), 0,
1902                offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type));
1903         reg->id = 0;
1904         reg->ref_obj_id = 0;
1905         ___mark_reg_known(reg, imm);
1906 }
1907
1908 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm)
1909 {
1910         reg->var_off = tnum_const_subreg(reg->var_off, imm);
1911         reg->s32_min_value = (s32)imm;
1912         reg->s32_max_value = (s32)imm;
1913         reg->u32_min_value = (u32)imm;
1914         reg->u32_max_value = (u32)imm;
1915 }
1916
1917 /* Mark the 'variable offset' part of a register as zero.  This should be
1918  * used only on registers holding a pointer type.
1919  */
1920 static void __mark_reg_known_zero(struct bpf_reg_state *reg)
1921 {
1922         __mark_reg_known(reg, 0);
1923 }
1924
1925 static void __mark_reg_const_zero(struct bpf_reg_state *reg)
1926 {
1927         __mark_reg_known(reg, 0);
1928         reg->type = SCALAR_VALUE;
1929 }
1930
1931 static void mark_reg_known_zero(struct bpf_verifier_env *env,
1932                                 struct bpf_reg_state *regs, u32 regno)
1933 {
1934         if (WARN_ON(regno >= MAX_BPF_REG)) {
1935                 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno);
1936                 /* Something bad happened, let's kill all regs */
1937                 for (regno = 0; regno < MAX_BPF_REG; regno++)
1938                         __mark_reg_not_init(env, regs + regno);
1939                 return;
1940         }
1941         __mark_reg_known_zero(regs + regno);
1942 }
1943
1944 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type,
1945                               bool first_slot, int dynptr_id)
1946 {
1947         /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for
1948          * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply
1949          * set it unconditionally as it is ignored for STACK_DYNPTR anyway.
1950          */
1951         __mark_reg_known_zero(reg);
1952         reg->type = CONST_PTR_TO_DYNPTR;
1953         /* Give each dynptr a unique id to uniquely associate slices to it. */
1954         reg->id = dynptr_id;
1955         reg->dynptr.type = type;
1956         reg->dynptr.first_slot = first_slot;
1957 }
1958
1959 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg)
1960 {
1961         if (base_type(reg->type) == PTR_TO_MAP_VALUE) {
1962                 const struct bpf_map *map = reg->map_ptr;
1963
1964                 if (map->inner_map_meta) {
1965                         reg->type = CONST_PTR_TO_MAP;
1966                         reg->map_ptr = map->inner_map_meta;
1967                         /* transfer reg's id which is unique for every map_lookup_elem
1968                          * as UID of the inner map.
1969                          */
1970                         if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER))
1971                                 reg->map_uid = reg->id;
1972                 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) {
1973                         reg->type = PTR_TO_XDP_SOCK;
1974                 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP ||
1975                            map->map_type == BPF_MAP_TYPE_SOCKHASH) {
1976                         reg->type = PTR_TO_SOCKET;
1977                 } else {
1978                         reg->type = PTR_TO_MAP_VALUE;
1979                 }
1980                 return;
1981         }
1982
1983         reg->type &= ~PTR_MAYBE_NULL;
1984 }
1985
1986 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno,
1987                                 struct btf_field_graph_root *ds_head)
1988 {
1989         __mark_reg_known_zero(&regs[regno]);
1990         regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC;
1991         regs[regno].btf = ds_head->btf;
1992         regs[regno].btf_id = ds_head->value_btf_id;
1993         regs[regno].off = ds_head->node_offset;
1994 }
1995
1996 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg)
1997 {
1998         return type_is_pkt_pointer(reg->type);
1999 }
2000
2001 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg)
2002 {
2003         return reg_is_pkt_pointer(reg) ||
2004                reg->type == PTR_TO_PACKET_END;
2005 }
2006
2007 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg)
2008 {
2009         return base_type(reg->type) == PTR_TO_MEM &&
2010                 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP);
2011 }
2012
2013 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */
2014 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg,
2015                                     enum bpf_reg_type which)
2016 {
2017         /* The register can already have a range from prior markings.
2018          * This is fine as long as it hasn't been advanced from its
2019          * origin.
2020          */
2021         return reg->type == which &&
2022                reg->id == 0 &&
2023                reg->off == 0 &&
2024                tnum_equals_const(reg->var_off, 0);
2025 }
2026
2027 /* Reset the min/max bounds of a register */
2028 static void __mark_reg_unbounded(struct bpf_reg_state *reg)
2029 {
2030         reg->smin_value = S64_MIN;
2031         reg->smax_value = S64_MAX;
2032         reg->umin_value = 0;
2033         reg->umax_value = U64_MAX;
2034
2035         reg->s32_min_value = S32_MIN;
2036         reg->s32_max_value = S32_MAX;
2037         reg->u32_min_value = 0;
2038         reg->u32_max_value = U32_MAX;
2039 }
2040
2041 static void __mark_reg64_unbounded(struct bpf_reg_state *reg)
2042 {
2043         reg->smin_value = S64_MIN;
2044         reg->smax_value = S64_MAX;
2045         reg->umin_value = 0;
2046         reg->umax_value = U64_MAX;
2047 }
2048
2049 static void __mark_reg32_unbounded(struct bpf_reg_state *reg)
2050 {
2051         reg->s32_min_value = S32_MIN;
2052         reg->s32_max_value = S32_MAX;
2053         reg->u32_min_value = 0;
2054         reg->u32_max_value = U32_MAX;
2055 }
2056
2057 static void __update_reg32_bounds(struct bpf_reg_state *reg)
2058 {
2059         struct tnum var32_off = tnum_subreg(reg->var_off);
2060
2061         /* min signed is max(sign bit) | min(other bits) */
2062         reg->s32_min_value = max_t(s32, reg->s32_min_value,
2063                         var32_off.value | (var32_off.mask & S32_MIN));
2064         /* max signed is min(sign bit) | max(other bits) */
2065         reg->s32_max_value = min_t(s32, reg->s32_max_value,
2066                         var32_off.value | (var32_off.mask & S32_MAX));
2067         reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value);
2068         reg->u32_max_value = min(reg->u32_max_value,
2069                                  (u32)(var32_off.value | var32_off.mask));
2070 }
2071
2072 static void __update_reg64_bounds(struct bpf_reg_state *reg)
2073 {
2074         /* min signed is max(sign bit) | min(other bits) */
2075         reg->smin_value = max_t(s64, reg->smin_value,
2076                                 reg->var_off.value | (reg->var_off.mask & S64_MIN));
2077         /* max signed is min(sign bit) | max(other bits) */
2078         reg->smax_value = min_t(s64, reg->smax_value,
2079                                 reg->var_off.value | (reg->var_off.mask & S64_MAX));
2080         reg->umin_value = max(reg->umin_value, reg->var_off.value);
2081         reg->umax_value = min(reg->umax_value,
2082                               reg->var_off.value | reg->var_off.mask);
2083 }
2084
2085 static void __update_reg_bounds(struct bpf_reg_state *reg)
2086 {
2087         __update_reg32_bounds(reg);
2088         __update_reg64_bounds(reg);
2089 }
2090
2091 /* Uses signed min/max values to inform unsigned, and vice-versa */
2092 static void __reg32_deduce_bounds(struct bpf_reg_state *reg)
2093 {
2094         /* Learn sign from signed bounds.
2095          * If we cannot cross the sign boundary, then signed and unsigned bounds
2096          * are the same, so combine.  This works even in the negative case, e.g.
2097          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2098          */
2099         if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) {
2100                 reg->s32_min_value = reg->u32_min_value =
2101                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2102                 reg->s32_max_value = reg->u32_max_value =
2103                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2104                 return;
2105         }
2106         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2107          * boundary, so we must be careful.
2108          */
2109         if ((s32)reg->u32_max_value >= 0) {
2110                 /* Positive.  We can't learn anything from the smin, but smax
2111                  * is positive, hence safe.
2112                  */
2113                 reg->s32_min_value = reg->u32_min_value;
2114                 reg->s32_max_value = reg->u32_max_value =
2115                         min_t(u32, reg->s32_max_value, reg->u32_max_value);
2116         } else if ((s32)reg->u32_min_value < 0) {
2117                 /* Negative.  We can't learn anything from the smax, but smin
2118                  * is negative, hence safe.
2119                  */
2120                 reg->s32_min_value = reg->u32_min_value =
2121                         max_t(u32, reg->s32_min_value, reg->u32_min_value);
2122                 reg->s32_max_value = reg->u32_max_value;
2123         }
2124 }
2125
2126 static void __reg64_deduce_bounds(struct bpf_reg_state *reg)
2127 {
2128         /* Learn sign from signed bounds.
2129          * If we cannot cross the sign boundary, then signed and unsigned bounds
2130          * are the same, so combine.  This works even in the negative case, e.g.
2131          * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff.
2132          */
2133         if (reg->smin_value >= 0 || reg->smax_value < 0) {
2134                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2135                                                           reg->umin_value);
2136                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2137                                                           reg->umax_value);
2138                 return;
2139         }
2140         /* Learn sign from unsigned bounds.  Signed bounds cross the sign
2141          * boundary, so we must be careful.
2142          */
2143         if ((s64)reg->umax_value >= 0) {
2144                 /* Positive.  We can't learn anything from the smin, but smax
2145                  * is positive, hence safe.
2146                  */
2147                 reg->smin_value = reg->umin_value;
2148                 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value,
2149                                                           reg->umax_value);
2150         } else if ((s64)reg->umin_value < 0) {
2151                 /* Negative.  We can't learn anything from the smax, but smin
2152                  * is negative, hence safe.
2153                  */
2154                 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value,
2155                                                           reg->umin_value);
2156                 reg->smax_value = reg->umax_value;
2157         }
2158 }
2159
2160 static void __reg_deduce_bounds(struct bpf_reg_state *reg)
2161 {
2162         __reg32_deduce_bounds(reg);
2163         __reg64_deduce_bounds(reg);
2164 }
2165
2166 /* Attempts to improve var_off based on unsigned min/max information */
2167 static void __reg_bound_offset(struct bpf_reg_state *reg)
2168 {
2169         struct tnum var64_off = tnum_intersect(reg->var_off,
2170                                                tnum_range(reg->umin_value,
2171                                                           reg->umax_value));
2172         struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off),
2173                                                tnum_range(reg->u32_min_value,
2174                                                           reg->u32_max_value));
2175
2176         reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off);
2177 }
2178
2179 static void reg_bounds_sync(struct bpf_reg_state *reg)
2180 {
2181         /* We might have learned new bounds from the var_off. */
2182         __update_reg_bounds(reg);
2183         /* We might have learned something about the sign bit. */
2184         __reg_deduce_bounds(reg);
2185         /* We might have learned some bits from the bounds. */
2186         __reg_bound_offset(reg);
2187         /* Intersecting with the old var_off might have improved our bounds
2188          * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc),
2189          * then new var_off is (0; 0x7f...fc) which improves our umax.
2190          */
2191         __update_reg_bounds(reg);
2192 }
2193
2194 static bool __reg32_bound_s64(s32 a)
2195 {
2196         return a >= 0 && a <= S32_MAX;
2197 }
2198
2199 static void __reg_assign_32_into_64(struct bpf_reg_state *reg)
2200 {
2201         reg->umin_value = reg->u32_min_value;
2202         reg->umax_value = reg->u32_max_value;
2203
2204         /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must
2205          * be positive otherwise set to worse case bounds and refine later
2206          * from tnum.
2207          */
2208         if (__reg32_bound_s64(reg->s32_min_value) &&
2209             __reg32_bound_s64(reg->s32_max_value)) {
2210                 reg->smin_value = reg->s32_min_value;
2211                 reg->smax_value = reg->s32_max_value;
2212         } else {
2213                 reg->smin_value = 0;
2214                 reg->smax_value = U32_MAX;
2215         }
2216 }
2217
2218 static void __reg_combine_32_into_64(struct bpf_reg_state *reg)
2219 {
2220         /* special case when 64-bit register has upper 32-bit register
2221          * zeroed. Typically happens after zext or <<32, >>32 sequence
2222          * allowing us to use 32-bit bounds directly,
2223          */
2224         if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) {
2225                 __reg_assign_32_into_64(reg);
2226         } else {
2227                 /* Otherwise the best we can do is push lower 32bit known and
2228                  * unknown bits into register (var_off set from jmp logic)
2229                  * then learn as much as possible from the 64-bit tnum
2230                  * known and unknown bits. The previous smin/smax bounds are
2231                  * invalid here because of jmp32 compare so mark them unknown
2232                  * so they do not impact tnum bounds calculation.
2233                  */
2234                 __mark_reg64_unbounded(reg);
2235         }
2236         reg_bounds_sync(reg);
2237 }
2238
2239 static bool __reg64_bound_s32(s64 a)
2240 {
2241         return a >= S32_MIN && a <= S32_MAX;
2242 }
2243
2244 static bool __reg64_bound_u32(u64 a)
2245 {
2246         return a >= U32_MIN && a <= U32_MAX;
2247 }
2248
2249 static void __reg_combine_64_into_32(struct bpf_reg_state *reg)
2250 {
2251         __mark_reg32_unbounded(reg);
2252         if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) {
2253                 reg->s32_min_value = (s32)reg->smin_value;
2254                 reg->s32_max_value = (s32)reg->smax_value;
2255         }
2256         if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) {
2257                 reg->u32_min_value = (u32)reg->umin_value;
2258                 reg->u32_max_value = (u32)reg->umax_value;
2259         }
2260         reg_bounds_sync(reg);
2261 }
2262
2263 /* Mark a register as having a completely unknown (scalar) value. */
2264 static void __mark_reg_unknown(const struct bpf_verifier_env *env,
2265                                struct bpf_reg_state *reg)
2266 {
2267         /*
2268          * Clear type, off, and union(map_ptr, range) and
2269          * padding between 'type' and union
2270          */
2271         memset(reg, 0, offsetof(struct bpf_reg_state, var_off));
2272         reg->type = SCALAR_VALUE;
2273         reg->id = 0;
2274         reg->ref_obj_id = 0;
2275         reg->var_off = tnum_unknown;
2276         reg->frameno = 0;
2277         reg->precise = !env->bpf_capable;
2278         __mark_reg_unbounded(reg);
2279 }
2280
2281 static void mark_reg_unknown(struct bpf_verifier_env *env,
2282                              struct bpf_reg_state *regs, u32 regno)
2283 {
2284         if (WARN_ON(regno >= MAX_BPF_REG)) {
2285                 verbose(env, "mark_reg_unknown(regs, %u)\n", regno);
2286                 /* Something bad happened, let's kill all regs except FP */
2287                 for (regno = 0; regno < BPF_REG_FP; regno++)
2288                         __mark_reg_not_init(env, regs + regno);
2289                 return;
2290         }
2291         __mark_reg_unknown(env, regs + regno);
2292 }
2293
2294 static void __mark_reg_not_init(const struct bpf_verifier_env *env,
2295                                 struct bpf_reg_state *reg)
2296 {
2297         __mark_reg_unknown(env, reg);
2298         reg->type = NOT_INIT;
2299 }
2300
2301 static void mark_reg_not_init(struct bpf_verifier_env *env,
2302                               struct bpf_reg_state *regs, u32 regno)
2303 {
2304         if (WARN_ON(regno >= MAX_BPF_REG)) {
2305                 verbose(env, "mark_reg_not_init(regs, %u)\n", regno);
2306                 /* Something bad happened, let's kill all regs except FP */
2307                 for (regno = 0; regno < BPF_REG_FP; regno++)
2308                         __mark_reg_not_init(env, regs + regno);
2309                 return;
2310         }
2311         __mark_reg_not_init(env, regs + regno);
2312 }
2313
2314 static void mark_btf_ld_reg(struct bpf_verifier_env *env,
2315                             struct bpf_reg_state *regs, u32 regno,
2316                             enum bpf_reg_type reg_type,
2317                             struct btf *btf, u32 btf_id,
2318                             enum bpf_type_flag flag)
2319 {
2320         if (reg_type == SCALAR_VALUE) {
2321                 mark_reg_unknown(env, regs, regno);
2322                 return;
2323         }
2324         mark_reg_known_zero(env, regs, regno);
2325         regs[regno].type = PTR_TO_BTF_ID | flag;
2326         regs[regno].btf = btf;
2327         regs[regno].btf_id = btf_id;
2328 }
2329
2330 #define DEF_NOT_SUBREG  (0)
2331 static void init_reg_state(struct bpf_verifier_env *env,
2332                            struct bpf_func_state *state)
2333 {
2334         struct bpf_reg_state *regs = state->regs;
2335         int i;
2336
2337         for (i = 0; i < MAX_BPF_REG; i++) {
2338                 mark_reg_not_init(env, regs, i);
2339                 regs[i].live = REG_LIVE_NONE;
2340                 regs[i].parent = NULL;
2341                 regs[i].subreg_def = DEF_NOT_SUBREG;
2342         }
2343
2344         /* frame pointer */
2345         regs[BPF_REG_FP].type = PTR_TO_STACK;
2346         mark_reg_known_zero(env, regs, BPF_REG_FP);
2347         regs[BPF_REG_FP].frameno = state->frameno;
2348 }
2349
2350 #define BPF_MAIN_FUNC (-1)
2351 static void init_func_state(struct bpf_verifier_env *env,
2352                             struct bpf_func_state *state,
2353                             int callsite, int frameno, int subprogno)
2354 {
2355         state->callsite = callsite;
2356         state->frameno = frameno;
2357         state->subprogno = subprogno;
2358         state->callback_ret_range = tnum_range(0, 0);
2359         init_reg_state(env, state);
2360         mark_verifier_state_scratched(env);
2361 }
2362
2363 /* Similar to push_stack(), but for async callbacks */
2364 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
2365                                                 int insn_idx, int prev_insn_idx,
2366                                                 int subprog)
2367 {
2368         struct bpf_verifier_stack_elem *elem;
2369         struct bpf_func_state *frame;
2370
2371         elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL);
2372         if (!elem)
2373                 goto err;
2374
2375         elem->insn_idx = insn_idx;
2376         elem->prev_insn_idx = prev_insn_idx;
2377         elem->next = env->head;
2378         elem->log_pos = env->log.end_pos;
2379         env->head = elem;
2380         env->stack_size++;
2381         if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
2382                 verbose(env,
2383                         "The sequence of %d jumps is too complex for async cb.\n",
2384                         env->stack_size);
2385                 goto err;
2386         }
2387         /* Unlike push_stack() do not copy_verifier_state().
2388          * The caller state doesn't matter.
2389          * This is async callback. It starts in a fresh stack.
2390          * Initialize it similar to do_check_common().
2391          */
2392         elem->st.branches = 1;
2393         frame = kzalloc(sizeof(*frame), GFP_KERNEL);
2394         if (!frame)
2395                 goto err;
2396         init_func_state(env, frame,
2397                         BPF_MAIN_FUNC /* callsite */,
2398                         0 /* frameno within this callchain */,
2399                         subprog /* subprog number within this prog */);
2400         elem->st.frame[0] = frame;
2401         return &elem->st;
2402 err:
2403         free_verifier_state(env->cur_state, true);
2404         env->cur_state = NULL;
2405         /* pop all elements and return */
2406         while (!pop_stack(env, NULL, NULL, false));
2407         return NULL;
2408 }
2409
2410
2411 enum reg_arg_type {
2412         SRC_OP,         /* register is used as source operand */
2413         DST_OP,         /* register is used as destination operand */
2414         DST_OP_NO_MARK  /* same as above, check only, don't mark */
2415 };
2416
2417 static int cmp_subprogs(const void *a, const void *b)
2418 {
2419         return ((struct bpf_subprog_info *)a)->start -
2420                ((struct bpf_subprog_info *)b)->start;
2421 }
2422
2423 static int find_subprog(struct bpf_verifier_env *env, int off)
2424 {
2425         struct bpf_subprog_info *p;
2426
2427         p = bsearch(&off, env->subprog_info, env->subprog_cnt,
2428                     sizeof(env->subprog_info[0]), cmp_subprogs);
2429         if (!p)
2430                 return -ENOENT;
2431         return p - env->subprog_info;
2432
2433 }
2434
2435 static int add_subprog(struct bpf_verifier_env *env, int off)
2436 {
2437         int insn_cnt = env->prog->len;
2438         int ret;
2439
2440         if (off >= insn_cnt || off < 0) {
2441                 verbose(env, "call to invalid destination\n");
2442                 return -EINVAL;
2443         }
2444         ret = find_subprog(env, off);
2445         if (ret >= 0)
2446                 return ret;
2447         if (env->subprog_cnt >= BPF_MAX_SUBPROGS) {
2448                 verbose(env, "too many subprograms\n");
2449                 return -E2BIG;
2450         }
2451         /* determine subprog starts. The end is one before the next starts */
2452         env->subprog_info[env->subprog_cnt++].start = off;
2453         sort(env->subprog_info, env->subprog_cnt,
2454              sizeof(env->subprog_info[0]), cmp_subprogs, NULL);
2455         return env->subprog_cnt - 1;
2456 }
2457
2458 #define MAX_KFUNC_DESCS 256
2459 #define MAX_KFUNC_BTFS  256
2460
2461 struct bpf_kfunc_desc {
2462         struct btf_func_model func_model;
2463         u32 func_id;
2464         s32 imm;
2465         u16 offset;
2466         unsigned long addr;
2467 };
2468
2469 struct bpf_kfunc_btf {
2470         struct btf *btf;
2471         struct module *module;
2472         u16 offset;
2473 };
2474
2475 struct bpf_kfunc_desc_tab {
2476         /* Sorted by func_id (BTF ID) and offset (fd_array offset) during
2477          * verification. JITs do lookups by bpf_insn, where func_id may not be
2478          * available, therefore at the end of verification do_misc_fixups()
2479          * sorts this by imm and offset.
2480          */
2481         struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS];
2482         u32 nr_descs;
2483 };
2484
2485 struct bpf_kfunc_btf_tab {
2486         struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS];
2487         u32 nr_descs;
2488 };
2489
2490 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
2491 {
2492         const struct bpf_kfunc_desc *d0 = a;
2493         const struct bpf_kfunc_desc *d1 = b;
2494
2495         /* func_id is not greater than BTF_MAX_TYPE */
2496         return d0->func_id - d1->func_id ?: d0->offset - d1->offset;
2497 }
2498
2499 static int kfunc_btf_cmp_by_off(const void *a, const void *b)
2500 {
2501         const struct bpf_kfunc_btf *d0 = a;
2502         const struct bpf_kfunc_btf *d1 = b;
2503
2504         return d0->offset - d1->offset;
2505 }
2506
2507 static const struct bpf_kfunc_desc *
2508 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
2509 {
2510         struct bpf_kfunc_desc desc = {
2511                 .func_id = func_id,
2512                 .offset = offset,
2513         };
2514         struct bpf_kfunc_desc_tab *tab;
2515
2516         tab = prog->aux->kfunc_tab;
2517         return bsearch(&desc, tab->descs, tab->nr_descs,
2518                        sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off);
2519 }
2520
2521 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
2522                        u16 btf_fd_idx, u8 **func_addr)
2523 {
2524         const struct bpf_kfunc_desc *desc;
2525
2526         desc = find_kfunc_desc(prog, func_id, btf_fd_idx);
2527         if (!desc)
2528                 return -EFAULT;
2529
2530         *func_addr = (u8 *)desc->addr;
2531         return 0;
2532 }
2533
2534 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env,
2535                                          s16 offset)
2536 {
2537         struct bpf_kfunc_btf kf_btf = { .offset = offset };
2538         struct bpf_kfunc_btf_tab *tab;
2539         struct bpf_kfunc_btf *b;
2540         struct module *mod;
2541         struct btf *btf;
2542         int btf_fd;
2543
2544         tab = env->prog->aux->kfunc_btf_tab;
2545         b = bsearch(&kf_btf, tab->descs, tab->nr_descs,
2546                     sizeof(tab->descs[0]), kfunc_btf_cmp_by_off);
2547         if (!b) {
2548                 if (tab->nr_descs == MAX_KFUNC_BTFS) {
2549                         verbose(env, "too many different module BTFs\n");
2550                         return ERR_PTR(-E2BIG);
2551                 }
2552
2553                 if (bpfptr_is_null(env->fd_array)) {
2554                         verbose(env, "kfunc offset > 0 without fd_array is invalid\n");
2555                         return ERR_PTR(-EPROTO);
2556                 }
2557
2558                 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array,
2559                                             offset * sizeof(btf_fd),
2560                                             sizeof(btf_fd)))
2561                         return ERR_PTR(-EFAULT);
2562
2563                 btf = btf_get_by_fd(btf_fd);
2564                 if (IS_ERR(btf)) {
2565                         verbose(env, "invalid module BTF fd specified\n");
2566                         return btf;
2567                 }
2568
2569                 if (!btf_is_module(btf)) {
2570                         verbose(env, "BTF fd for kfunc is not a module BTF\n");
2571                         btf_put(btf);
2572                         return ERR_PTR(-EINVAL);
2573                 }
2574
2575                 mod = btf_try_get_module(btf);
2576                 if (!mod) {
2577                         btf_put(btf);
2578                         return ERR_PTR(-ENXIO);
2579                 }
2580
2581                 b = &tab->descs[tab->nr_descs++];
2582                 b->btf = btf;
2583                 b->module = mod;
2584                 b->offset = offset;
2585
2586                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2587                      kfunc_btf_cmp_by_off, NULL);
2588         }
2589         return b->btf;
2590 }
2591
2592 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab)
2593 {
2594         if (!tab)
2595                 return;
2596
2597         while (tab->nr_descs--) {
2598                 module_put(tab->descs[tab->nr_descs].module);
2599                 btf_put(tab->descs[tab->nr_descs].btf);
2600         }
2601         kfree(tab);
2602 }
2603
2604 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset)
2605 {
2606         if (offset) {
2607                 if (offset < 0) {
2608                         /* In the future, this can be allowed to increase limit
2609                          * of fd index into fd_array, interpreted as u16.
2610                          */
2611                         verbose(env, "negative offset disallowed for kernel module function call\n");
2612                         return ERR_PTR(-EINVAL);
2613                 }
2614
2615                 return __find_kfunc_desc_btf(env, offset);
2616         }
2617         return btf_vmlinux ?: ERR_PTR(-ENOENT);
2618 }
2619
2620 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
2621 {
2622         const struct btf_type *func, *func_proto;
2623         struct bpf_kfunc_btf_tab *btf_tab;
2624         struct bpf_kfunc_desc_tab *tab;
2625         struct bpf_prog_aux *prog_aux;
2626         struct bpf_kfunc_desc *desc;
2627         const char *func_name;
2628         struct btf *desc_btf;
2629         unsigned long call_imm;
2630         unsigned long addr;
2631         int err;
2632
2633         prog_aux = env->prog->aux;
2634         tab = prog_aux->kfunc_tab;
2635         btf_tab = prog_aux->kfunc_btf_tab;
2636         if (!tab) {
2637                 if (!btf_vmlinux) {
2638                         verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n");
2639                         return -ENOTSUPP;
2640                 }
2641
2642                 if (!env->prog->jit_requested) {
2643                         verbose(env, "JIT is required for calling kernel function\n");
2644                         return -ENOTSUPP;
2645                 }
2646
2647                 if (!bpf_jit_supports_kfunc_call()) {
2648                         verbose(env, "JIT does not support calling kernel function\n");
2649                         return -ENOTSUPP;
2650                 }
2651
2652                 if (!env->prog->gpl_compatible) {
2653                         verbose(env, "cannot call kernel function from non-GPL compatible program\n");
2654                         return -EINVAL;
2655                 }
2656
2657                 tab = kzalloc(sizeof(*tab), GFP_KERNEL);
2658                 if (!tab)
2659                         return -ENOMEM;
2660                 prog_aux->kfunc_tab = tab;
2661         }
2662
2663         /* func_id == 0 is always invalid, but instead of returning an error, be
2664          * conservative and wait until the code elimination pass before returning
2665          * error, so that invalid calls that get pruned out can be in BPF programs
2666          * loaded from userspace.  It is also required that offset be untouched
2667          * for such calls.
2668          */
2669         if (!func_id && !offset)
2670                 return 0;
2671
2672         if (!btf_tab && offset) {
2673                 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL);
2674                 if (!btf_tab)
2675                         return -ENOMEM;
2676                 prog_aux->kfunc_btf_tab = btf_tab;
2677         }
2678
2679         desc_btf = find_kfunc_desc_btf(env, offset);
2680         if (IS_ERR(desc_btf)) {
2681                 verbose(env, "failed to find BTF for kernel function\n");
2682                 return PTR_ERR(desc_btf);
2683         }
2684
2685         if (find_kfunc_desc(env->prog, func_id, offset))
2686                 return 0;
2687
2688         if (tab->nr_descs == MAX_KFUNC_DESCS) {
2689                 verbose(env, "too many different kernel function calls\n");
2690                 return -E2BIG;
2691         }
2692
2693         func = btf_type_by_id(desc_btf, func_id);
2694         if (!func || !btf_type_is_func(func)) {
2695                 verbose(env, "kernel btf_id %u is not a function\n",
2696                         func_id);
2697                 return -EINVAL;
2698         }
2699         func_proto = btf_type_by_id(desc_btf, func->type);
2700         if (!func_proto || !btf_type_is_func_proto(func_proto)) {
2701                 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n",
2702                         func_id);
2703                 return -EINVAL;
2704         }
2705
2706         func_name = btf_name_by_offset(desc_btf, func->name_off);
2707         addr = kallsyms_lookup_name(func_name);
2708         if (!addr) {
2709                 verbose(env, "cannot find address for kernel function %s\n",
2710                         func_name);
2711                 return -EINVAL;
2712         }
2713         specialize_kfunc(env, func_id, offset, &addr);
2714
2715         if (bpf_jit_supports_far_kfunc_call()) {
2716                 call_imm = func_id;
2717         } else {
2718                 call_imm = BPF_CALL_IMM(addr);
2719                 /* Check whether the relative offset overflows desc->imm */
2720                 if ((unsigned long)(s32)call_imm != call_imm) {
2721                         verbose(env, "address of kernel function %s is out of range\n",
2722                                 func_name);
2723                         return -EINVAL;
2724                 }
2725         }
2726
2727         if (bpf_dev_bound_kfunc_id(func_id)) {
2728                 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
2729                 if (err)
2730                         return err;
2731         }
2732
2733         desc = &tab->descs[tab->nr_descs++];
2734         desc->func_id = func_id;
2735         desc->imm = call_imm;
2736         desc->offset = offset;
2737         desc->addr = addr;
2738         err = btf_distill_func_proto(&env->log, desc_btf,
2739                                      func_proto, func_name,
2740                                      &desc->func_model);
2741         if (!err)
2742                 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2743                      kfunc_desc_cmp_by_id_off, NULL);
2744         return err;
2745 }
2746
2747 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
2748 {
2749         const struct bpf_kfunc_desc *d0 = a;
2750         const struct bpf_kfunc_desc *d1 = b;
2751
2752         if (d0->imm != d1->imm)
2753                 return d0->imm < d1->imm ? -1 : 1;
2754         if (d0->offset != d1->offset)
2755                 return d0->offset < d1->offset ? -1 : 1;
2756         return 0;
2757 }
2758
2759 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog)
2760 {
2761         struct bpf_kfunc_desc_tab *tab;
2762
2763         tab = prog->aux->kfunc_tab;
2764         if (!tab)
2765                 return;
2766
2767         sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
2768              kfunc_desc_cmp_by_imm_off, NULL);
2769 }
2770
2771 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog)
2772 {
2773         return !!prog->aux->kfunc_tab;
2774 }
2775
2776 const struct btf_func_model *
2777 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
2778                          const struct bpf_insn *insn)
2779 {
2780         const struct bpf_kfunc_desc desc = {
2781                 .imm = insn->imm,
2782                 .offset = insn->off,
2783         };
2784         const struct bpf_kfunc_desc *res;
2785         struct bpf_kfunc_desc_tab *tab;
2786
2787         tab = prog->aux->kfunc_tab;
2788         res = bsearch(&desc, tab->descs, tab->nr_descs,
2789                       sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off);
2790
2791         return res ? &res->func_model : NULL;
2792 }
2793
2794 static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
2795 {
2796         struct bpf_subprog_info *subprog = env->subprog_info;
2797         struct bpf_insn *insn = env->prog->insnsi;
2798         int i, ret, insn_cnt = env->prog->len;
2799
2800         /* Add entry function. */
2801         ret = add_subprog(env, 0);
2802         if (ret)
2803                 return ret;
2804
2805         for (i = 0; i < insn_cnt; i++, insn++) {
2806                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) &&
2807                     !bpf_pseudo_kfunc_call(insn))
2808                         continue;
2809
2810                 if (!env->bpf_capable) {
2811                         verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
2812                         return -EPERM;
2813                 }
2814
2815                 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn))
2816                         ret = add_subprog(env, i + insn->imm + 1);
2817                 else
2818                         ret = add_kfunc_call(env, insn->imm, insn->off);
2819
2820                 if (ret < 0)
2821                         return ret;
2822         }
2823
2824         /* Add a fake 'exit' subprog which could simplify subprog iteration
2825          * logic. 'subprog_cnt' should not be increased.
2826          */
2827         subprog[env->subprog_cnt].start = insn_cnt;
2828
2829         if (env->log.level & BPF_LOG_LEVEL2)
2830                 for (i = 0; i < env->subprog_cnt; i++)
2831                         verbose(env, "func#%d @%d\n", i, subprog[i].start);
2832
2833         return 0;
2834 }
2835
2836 static int check_subprogs(struct bpf_verifier_env *env)
2837 {
2838         int i, subprog_start, subprog_end, off, cur_subprog = 0;
2839         struct bpf_subprog_info *subprog = env->subprog_info;
2840         struct bpf_insn *insn = env->prog->insnsi;
2841         int insn_cnt = env->prog->len;
2842
2843         /* now check that all jumps are within the same subprog */
2844         subprog_start = subprog[cur_subprog].start;
2845         subprog_end = subprog[cur_subprog + 1].start;
2846         for (i = 0; i < insn_cnt; i++) {
2847                 u8 code = insn[i].code;
2848
2849                 if (code == (BPF_JMP | BPF_CALL) &&
2850                     insn[i].src_reg == 0 &&
2851                     insn[i].imm == BPF_FUNC_tail_call)
2852                         subprog[cur_subprog].has_tail_call = true;
2853                 if (BPF_CLASS(code) == BPF_LD &&
2854                     (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND))
2855                         subprog[cur_subprog].has_ld_abs = true;
2856                 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32)
2857                         goto next;
2858                 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL)
2859                         goto next;
2860                 if (code == (BPF_JMP32 | BPF_JA))
2861                         off = i + insn[i].imm + 1;
2862                 else
2863                         off = i + insn[i].off + 1;
2864                 if (off < subprog_start || off >= subprog_end) {
2865                         verbose(env, "jump out of range from insn %d to %d\n", i, off);
2866                         return -EINVAL;
2867                 }
2868 next:
2869                 if (i == subprog_end - 1) {
2870                         /* to avoid fall-through from one subprog into another
2871                          * the last insn of the subprog should be either exit
2872                          * or unconditional jump back
2873                          */
2874                         if (code != (BPF_JMP | BPF_EXIT) &&
2875                             code != (BPF_JMP32 | BPF_JA) &&
2876                             code != (BPF_JMP | BPF_JA)) {
2877                                 verbose(env, "last insn is not an exit or jmp\n");
2878                                 return -EINVAL;
2879                         }
2880                         subprog_start = subprog_end;
2881                         cur_subprog++;
2882                         if (cur_subprog < env->subprog_cnt)
2883                                 subprog_end = subprog[cur_subprog + 1].start;
2884                 }
2885         }
2886         return 0;
2887 }
2888
2889 /* Parentage chain of this register (or stack slot) should take care of all
2890  * issues like callee-saved registers, stack slot allocation time, etc.
2891  */
2892 static int mark_reg_read(struct bpf_verifier_env *env,
2893                          const struct bpf_reg_state *state,
2894                          struct bpf_reg_state *parent, u8 flag)
2895 {
2896         bool writes = parent == state->parent; /* Observe write marks */
2897         int cnt = 0;
2898
2899         while (parent) {
2900                 /* if read wasn't screened by an earlier write ... */
2901                 if (writes && state->live & REG_LIVE_WRITTEN)
2902                         break;
2903                 if (parent->live & REG_LIVE_DONE) {
2904                         verbose(env, "verifier BUG type %s var_off %lld off %d\n",
2905                                 reg_type_str(env, parent->type),
2906                                 parent->var_off.value, parent->off);
2907                         return -EFAULT;
2908                 }
2909                 /* The first condition is more likely to be true than the
2910                  * second, checked it first.
2911                  */
2912                 if ((parent->live & REG_LIVE_READ) == flag ||
2913                     parent->live & REG_LIVE_READ64)
2914                         /* The parentage chain never changes and
2915                          * this parent was already marked as LIVE_READ.
2916                          * There is no need to keep walking the chain again and
2917                          * keep re-marking all parents as LIVE_READ.
2918                          * This case happens when the same register is read
2919                          * multiple times without writes into it in-between.
2920                          * Also, if parent has the stronger REG_LIVE_READ64 set,
2921                          * then no need to set the weak REG_LIVE_READ32.
2922                          */
2923                         break;
2924                 /* ... then we depend on parent's value */
2925                 parent->live |= flag;
2926                 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */
2927                 if (flag == REG_LIVE_READ64)
2928                         parent->live &= ~REG_LIVE_READ32;
2929                 state = parent;
2930                 parent = state->parent;
2931                 writes = true;
2932                 cnt++;
2933         }
2934
2935         if (env->longest_mark_read_walk < cnt)
2936                 env->longest_mark_read_walk = cnt;
2937         return 0;
2938 }
2939
2940 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
2941 {
2942         struct bpf_func_state *state = func(env, reg);
2943         int spi, ret;
2944
2945         /* For CONST_PTR_TO_DYNPTR, it must have already been done by
2946          * check_reg_arg in check_helper_call and mark_btf_func_reg_size in
2947          * check_kfunc_call.
2948          */
2949         if (reg->type == CONST_PTR_TO_DYNPTR)
2950                 return 0;
2951         spi = dynptr_get_spi(env, reg);
2952         if (spi < 0)
2953                 return spi;
2954         /* Caller ensures dynptr is valid and initialized, which means spi is in
2955          * bounds and spi is the first dynptr slot. Simply mark stack slot as
2956          * read.
2957          */
2958         ret = mark_reg_read(env, &state->stack[spi].spilled_ptr,
2959                             state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64);
2960         if (ret)
2961                 return ret;
2962         return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr,
2963                              state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64);
2964 }
2965
2966 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
2967                           int spi, int nr_slots)
2968 {
2969         struct bpf_func_state *state = func(env, reg);
2970         int err, i;
2971
2972         for (i = 0; i < nr_slots; i++) {
2973                 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr;
2974
2975                 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64);
2976                 if (err)
2977                         return err;
2978
2979                 mark_stack_slot_scratched(env, spi - i);
2980         }
2981
2982         return 0;
2983 }
2984
2985 /* This function is supposed to be used by the following 32-bit optimization
2986  * code only. It returns TRUE if the source or destination register operates
2987  * on 64-bit, otherwise return FALSE.
2988  */
2989 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn,
2990                      u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t)
2991 {
2992         u8 code, class, op;
2993
2994         code = insn->code;
2995         class = BPF_CLASS(code);
2996         op = BPF_OP(code);
2997         if (class == BPF_JMP) {
2998                 /* BPF_EXIT for "main" will reach here. Return TRUE
2999                  * conservatively.
3000                  */
3001                 if (op == BPF_EXIT)
3002                         return true;
3003                 if (op == BPF_CALL) {
3004                         /* BPF to BPF call will reach here because of marking
3005                          * caller saved clobber with DST_OP_NO_MARK for which we
3006                          * don't care the register def because they are anyway
3007                          * marked as NOT_INIT already.
3008                          */
3009                         if (insn->src_reg == BPF_PSEUDO_CALL)
3010                                 return false;
3011                         /* Helper call will reach here because of arg type
3012                          * check, conservatively return TRUE.
3013                          */
3014                         if (t == SRC_OP)
3015                                 return true;
3016
3017                         return false;
3018                 }
3019         }
3020
3021         if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32))
3022                 return false;
3023
3024         if (class == BPF_ALU64 || class == BPF_JMP ||
3025             (class == BPF_ALU && op == BPF_END && insn->imm == 64))
3026                 return true;
3027
3028         if (class == BPF_ALU || class == BPF_JMP32)
3029                 return false;
3030
3031         if (class == BPF_LDX) {
3032                 if (t != SRC_OP)
3033                         return BPF_SIZE(code) == BPF_DW;
3034                 /* LDX source must be ptr. */
3035                 return true;
3036         }
3037
3038         if (class == BPF_STX) {
3039                 /* BPF_STX (including atomic variants) has multiple source
3040                  * operands, one of which is a ptr. Check whether the caller is
3041                  * asking about it.
3042                  */
3043                 if (t == SRC_OP && reg->type != SCALAR_VALUE)
3044                         return true;
3045                 return BPF_SIZE(code) == BPF_DW;
3046         }
3047
3048         if (class == BPF_LD) {
3049                 u8 mode = BPF_MODE(code);
3050
3051                 /* LD_IMM64 */
3052                 if (mode == BPF_IMM)
3053                         return true;
3054
3055                 /* Both LD_IND and LD_ABS return 32-bit data. */
3056                 if (t != SRC_OP)
3057                         return  false;
3058
3059                 /* Implicit ctx ptr. */
3060                 if (regno == BPF_REG_6)
3061                         return true;
3062
3063                 /* Explicit source could be any width. */
3064                 return true;
3065         }
3066
3067         if (class == BPF_ST)
3068                 /* The only source register for BPF_ST is a ptr. */
3069                 return true;
3070
3071         /* Conservatively return true at default. */
3072         return true;
3073 }
3074
3075 /* Return the regno defined by the insn, or -1. */
3076 static int insn_def_regno(const struct bpf_insn *insn)
3077 {
3078         switch (BPF_CLASS(insn->code)) {
3079         case BPF_JMP:
3080         case BPF_JMP32:
3081         case BPF_ST:
3082                 return -1;
3083         case BPF_STX:
3084                 if (BPF_MODE(insn->code) == BPF_ATOMIC &&
3085                     (insn->imm & BPF_FETCH)) {
3086                         if (insn->imm == BPF_CMPXCHG)
3087                                 return BPF_REG_0;
3088                         else
3089                                 return insn->src_reg;
3090                 } else {
3091                         return -1;
3092                 }
3093         default:
3094                 return insn->dst_reg;
3095         }
3096 }
3097
3098 /* Return TRUE if INSN has defined any 32-bit value explicitly. */
3099 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn)
3100 {
3101         int dst_reg = insn_def_regno(insn);
3102
3103         if (dst_reg == -1)
3104                 return false;
3105
3106         return !is_reg64(env, insn, dst_reg, NULL, DST_OP);
3107 }
3108
3109 static void mark_insn_zext(struct bpf_verifier_env *env,
3110                            struct bpf_reg_state *reg)
3111 {
3112         s32 def_idx = reg->subreg_def;
3113
3114         if (def_idx == DEF_NOT_SUBREG)
3115                 return;
3116
3117         env->insn_aux_data[def_idx - 1].zext_dst = true;
3118         /* The dst will be zero extended, so won't be sub-register anymore. */
3119         reg->subreg_def = DEF_NOT_SUBREG;
3120 }
3121
3122 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno,
3123                          enum reg_arg_type t)
3124 {
3125         struct bpf_verifier_state *vstate = env->cur_state;
3126         struct bpf_func_state *state = vstate->frame[vstate->curframe];
3127         struct bpf_insn *insn = env->prog->insnsi + env->insn_idx;
3128         struct bpf_reg_state *reg, *regs = state->regs;
3129         bool rw64;
3130
3131         if (regno >= MAX_BPF_REG) {
3132                 verbose(env, "R%d is invalid\n", regno);
3133                 return -EINVAL;
3134         }
3135
3136         mark_reg_scratched(env, regno);
3137
3138         reg = &regs[regno];
3139         rw64 = is_reg64(env, insn, regno, reg, t);
3140         if (t == SRC_OP) {
3141                 /* check whether register used as source operand can be read */
3142                 if (reg->type == NOT_INIT) {
3143                         verbose(env, "R%d !read_ok\n", regno);
3144                         return -EACCES;
3145                 }
3146                 /* We don't need to worry about FP liveness because it's read-only */
3147                 if (regno == BPF_REG_FP)
3148                         return 0;
3149
3150                 if (rw64)
3151                         mark_insn_zext(env, reg);
3152
3153                 return mark_reg_read(env, reg, reg->parent,
3154                                      rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32);
3155         } else {
3156                 /* check whether register used as dest operand can be written to */
3157                 if (regno == BPF_REG_FP) {
3158                         verbose(env, "frame pointer is read only\n");
3159                         return -EACCES;
3160                 }
3161                 reg->live |= REG_LIVE_WRITTEN;
3162                 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1;
3163                 if (t == DST_OP)
3164                         mark_reg_unknown(env, regs, regno);
3165         }
3166         return 0;
3167 }
3168
3169 static void mark_jmp_point(struct bpf_verifier_env *env, int idx)
3170 {
3171         env->insn_aux_data[idx].jmp_point = true;
3172 }
3173
3174 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx)
3175 {
3176         return env->insn_aux_data[insn_idx].jmp_point;
3177 }
3178
3179 /* for any branch, call, exit record the history of jmps in the given state */
3180 static int push_jmp_history(struct bpf_verifier_env *env,
3181                             struct bpf_verifier_state *cur)
3182 {
3183         u32 cnt = cur->jmp_history_cnt;
3184         struct bpf_idx_pair *p;
3185         size_t alloc_size;
3186
3187         if (!is_jmp_point(env, env->insn_idx))
3188                 return 0;
3189
3190         cnt++;
3191         alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p)));
3192         p = krealloc(cur->jmp_history, alloc_size, GFP_USER);
3193         if (!p)
3194                 return -ENOMEM;
3195         p[cnt - 1].idx = env->insn_idx;
3196         p[cnt - 1].prev_idx = env->prev_insn_idx;
3197         cur->jmp_history = p;
3198         cur->jmp_history_cnt = cnt;
3199         return 0;
3200 }
3201
3202 /* Backtrack one insn at a time. If idx is not at the top of recorded
3203  * history then previous instruction came from straight line execution.
3204  * Return -ENOENT if we exhausted all instructions within given state.
3205  *
3206  * It's legal to have a bit of a looping with the same starting and ending
3207  * insn index within the same state, e.g.: 3->4->5->3, so just because current
3208  * instruction index is the same as state's first_idx doesn't mean we are
3209  * done. If there is still some jump history left, we should keep going. We
3210  * need to take into account that we might have a jump history between given
3211  * state's parent and itself, due to checkpointing. In this case, we'll have
3212  * history entry recording a jump from last instruction of parent state and
3213  * first instruction of given state.
3214  */
3215 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i,
3216                              u32 *history)
3217 {
3218         u32 cnt = *history;
3219
3220         if (i == st->first_insn_idx) {
3221                 if (cnt == 0)
3222                         return -ENOENT;
3223                 if (cnt == 1 && st->jmp_history[0].idx == i)
3224                         return -ENOENT;
3225         }
3226
3227         if (cnt && st->jmp_history[cnt - 1].idx == i) {
3228                 i = st->jmp_history[cnt - 1].prev_idx;
3229                 (*history)--;
3230         } else {
3231                 i--;
3232         }
3233         return i;
3234 }
3235
3236 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
3237 {
3238         const struct btf_type *func;
3239         struct btf *desc_btf;
3240
3241         if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL)
3242                 return NULL;
3243
3244         desc_btf = find_kfunc_desc_btf(data, insn->off);
3245         if (IS_ERR(desc_btf))
3246                 return "<error>";
3247
3248         func = btf_type_by_id(desc_btf, insn->imm);
3249         return btf_name_by_offset(desc_btf, func->name_off);
3250 }
3251
3252 static inline void bt_init(struct backtrack_state *bt, u32 frame)
3253 {
3254         bt->frame = frame;
3255 }
3256
3257 static inline void bt_reset(struct backtrack_state *bt)
3258 {
3259         struct bpf_verifier_env *env = bt->env;
3260
3261         memset(bt, 0, sizeof(*bt));
3262         bt->env = env;
3263 }
3264
3265 static inline u32 bt_empty(struct backtrack_state *bt)
3266 {
3267         u64 mask = 0;
3268         int i;
3269
3270         for (i = 0; i <= bt->frame; i++)
3271                 mask |= bt->reg_masks[i] | bt->stack_masks[i];
3272
3273         return mask == 0;
3274 }
3275
3276 static inline int bt_subprog_enter(struct backtrack_state *bt)
3277 {
3278         if (bt->frame == MAX_CALL_FRAMES - 1) {
3279                 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame);
3280                 WARN_ONCE(1, "verifier backtracking bug");
3281                 return -EFAULT;
3282         }
3283         bt->frame++;
3284         return 0;
3285 }
3286
3287 static inline int bt_subprog_exit(struct backtrack_state *bt)
3288 {
3289         if (bt->frame == 0) {
3290                 verbose(bt->env, "BUG subprog exit from frame 0\n");
3291                 WARN_ONCE(1, "verifier backtracking bug");
3292                 return -EFAULT;
3293         }
3294         bt->frame--;
3295         return 0;
3296 }
3297
3298 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3299 {
3300         bt->reg_masks[frame] |= 1 << reg;
3301 }
3302
3303 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg)
3304 {
3305         bt->reg_masks[frame] &= ~(1 << reg);
3306 }
3307
3308 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg)
3309 {
3310         bt_set_frame_reg(bt, bt->frame, reg);
3311 }
3312
3313 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg)
3314 {
3315         bt_clear_frame_reg(bt, bt->frame, reg);
3316 }
3317
3318 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3319 {
3320         bt->stack_masks[frame] |= 1ull << slot;
3321 }
3322
3323 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot)
3324 {
3325         bt->stack_masks[frame] &= ~(1ull << slot);
3326 }
3327
3328 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot)
3329 {
3330         bt_set_frame_slot(bt, bt->frame, slot);
3331 }
3332
3333 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot)
3334 {
3335         bt_clear_frame_slot(bt, bt->frame, slot);
3336 }
3337
3338 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame)
3339 {
3340         return bt->reg_masks[frame];
3341 }
3342
3343 static inline u32 bt_reg_mask(struct backtrack_state *bt)
3344 {
3345         return bt->reg_masks[bt->frame];
3346 }
3347
3348 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame)
3349 {
3350         return bt->stack_masks[frame];
3351 }
3352
3353 static inline u64 bt_stack_mask(struct backtrack_state *bt)
3354 {
3355         return bt->stack_masks[bt->frame];
3356 }
3357
3358 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg)
3359 {
3360         return bt->reg_masks[bt->frame] & (1 << reg);
3361 }
3362
3363 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot)
3364 {
3365         return bt->stack_masks[bt->frame] & (1ull << slot);
3366 }
3367
3368 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */
3369 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask)
3370 {
3371         DECLARE_BITMAP(mask, 64);
3372         bool first = true;
3373         int i, n;
3374
3375         buf[0] = '\0';
3376
3377         bitmap_from_u64(mask, reg_mask);
3378         for_each_set_bit(i, mask, 32) {
3379                 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i);
3380                 first = false;
3381                 buf += n;
3382                 buf_sz -= n;
3383                 if (buf_sz < 0)
3384                         break;
3385         }
3386 }
3387 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */
3388 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask)
3389 {
3390         DECLARE_BITMAP(mask, 64);
3391         bool first = true;
3392         int i, n;
3393
3394         buf[0] = '\0';
3395
3396         bitmap_from_u64(mask, stack_mask);
3397         for_each_set_bit(i, mask, 64) {
3398                 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8);
3399                 first = false;
3400                 buf += n;
3401                 buf_sz -= n;
3402                 if (buf_sz < 0)
3403                         break;
3404         }
3405 }
3406
3407 /* For given verifier state backtrack_insn() is called from the last insn to
3408  * the first insn. Its purpose is to compute a bitmask of registers and
3409  * stack slots that needs precision in the parent verifier state.
3410  *
3411  * @idx is an index of the instruction we are currently processing;
3412  * @subseq_idx is an index of the subsequent instruction that:
3413  *   - *would be* executed next, if jump history is viewed in forward order;
3414  *   - *was* processed previously during backtracking.
3415  */
3416 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx,
3417                           struct backtrack_state *bt)
3418 {
3419         const struct bpf_insn_cbs cbs = {
3420                 .cb_call        = disasm_kfunc_name,
3421                 .cb_print       = verbose,
3422                 .private_data   = env,
3423         };
3424         struct bpf_insn *insn = env->prog->insnsi + idx;
3425         u8 class = BPF_CLASS(insn->code);
3426         u8 opcode = BPF_OP(insn->code);
3427         u8 mode = BPF_MODE(insn->code);
3428         u32 dreg = insn->dst_reg;
3429         u32 sreg = insn->src_reg;
3430         u32 spi, i;
3431
3432         if (insn->code == 0)
3433                 return 0;
3434         if (env->log.level & BPF_LOG_LEVEL2) {
3435                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt));
3436                 verbose(env, "mark_precise: frame%d: regs=%s ",
3437                         bt->frame, env->tmp_str_buf);
3438                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt));
3439                 verbose(env, "stack=%s before ", env->tmp_str_buf);
3440                 verbose(env, "%d: ", idx);
3441                 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
3442         }
3443
3444         if (class == BPF_ALU || class == BPF_ALU64) {
3445                 if (!bt_is_reg_set(bt, dreg))
3446                         return 0;
3447                 if (opcode == BPF_END || opcode == BPF_NEG) {
3448                         /* sreg is reserved and unused
3449                          * dreg still need precision before this insn
3450                          */
3451                         return 0;
3452                 } else if (opcode == BPF_MOV) {
3453                         if (BPF_SRC(insn->code) == BPF_X) {
3454                                 /* dreg = sreg or dreg = (s8, s16, s32)sreg
3455                                  * dreg needs precision after this insn
3456                                  * sreg needs precision before this insn
3457                                  */
3458                                 bt_clear_reg(bt, dreg);
3459                                 bt_set_reg(bt, sreg);
3460                         } else {
3461                                 /* dreg = K
3462                                  * dreg needs precision after this insn.
3463                                  * Corresponding register is already marked
3464                                  * as precise=true in this verifier state.
3465                                  * No further markings in parent are necessary
3466                                  */
3467                                 bt_clear_reg(bt, dreg);
3468                         }
3469                 } else {
3470                         if (BPF_SRC(insn->code) == BPF_X) {
3471                                 /* dreg += sreg
3472                                  * both dreg and sreg need precision
3473                                  * before this insn
3474                                  */
3475                                 bt_set_reg(bt, sreg);
3476                         } /* else dreg += K
3477                            * dreg still needs precision before this insn
3478                            */
3479                 }
3480         } else if (class == BPF_LDX) {
3481                 if (!bt_is_reg_set(bt, dreg))
3482                         return 0;
3483                 bt_clear_reg(bt, dreg);
3484
3485                 /* scalars can only be spilled into stack w/o losing precision.
3486                  * Load from any other memory can be zero extended.
3487                  * The desire to keep that precision is already indicated
3488                  * by 'precise' mark in corresponding register of this state.
3489                  * No further tracking necessary.
3490                  */
3491                 if (insn->src_reg != BPF_REG_FP)
3492                         return 0;
3493
3494                 /* dreg = *(u64 *)[fp - off] was a fill from the stack.
3495                  * that [fp - off] slot contains scalar that needs to be
3496                  * tracked with precision
3497                  */
3498                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3499                 if (spi >= 64) {
3500                         verbose(env, "BUG spi %d\n", spi);
3501                         WARN_ONCE(1, "verifier backtracking bug");
3502                         return -EFAULT;
3503                 }
3504                 bt_set_slot(bt, spi);
3505         } else if (class == BPF_STX || class == BPF_ST) {
3506                 if (bt_is_reg_set(bt, dreg))
3507                         /* stx & st shouldn't be using _scalar_ dst_reg
3508                          * to access memory. It means backtracking
3509                          * encountered a case of pointer subtraction.
3510                          */
3511                         return -ENOTSUPP;
3512                 /* scalars can only be spilled into stack */
3513                 if (insn->dst_reg != BPF_REG_FP)
3514                         return 0;
3515                 spi = (-insn->off - 1) / BPF_REG_SIZE;
3516                 if (spi >= 64) {
3517                         verbose(env, "BUG spi %d\n", spi);
3518                         WARN_ONCE(1, "verifier backtracking bug");
3519                         return -EFAULT;
3520                 }
3521                 if (!bt_is_slot_set(bt, spi))
3522                         return 0;
3523                 bt_clear_slot(bt, spi);
3524                 if (class == BPF_STX)
3525                         bt_set_reg(bt, sreg);
3526         } else if (class == BPF_JMP || class == BPF_JMP32) {
3527                 if (bpf_pseudo_call(insn)) {
3528                         int subprog_insn_idx, subprog;
3529
3530                         subprog_insn_idx = idx + insn->imm + 1;
3531                         subprog = find_subprog(env, subprog_insn_idx);
3532                         if (subprog < 0)
3533                                 return -EFAULT;
3534
3535                         if (subprog_is_global(env, subprog)) {
3536                                 /* check that jump history doesn't have any
3537                                  * extra instructions from subprog; the next
3538                                  * instruction after call to global subprog
3539                                  * should be literally next instruction in
3540                                  * caller program
3541                                  */
3542                                 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug");
3543                                 /* r1-r5 are invalidated after subprog call,
3544                                  * so for global func call it shouldn't be set
3545                                  * anymore
3546                                  */
3547                                 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3548                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3549                                         WARN_ONCE(1, "verifier backtracking bug");
3550                                         return -EFAULT;
3551                                 }
3552                                 /* global subprog always sets R0 */
3553                                 bt_clear_reg(bt, BPF_REG_0);
3554                                 return 0;
3555                         } else {
3556                                 /* static subprog call instruction, which
3557                                  * means that we are exiting current subprog,
3558                                  * so only r1-r5 could be still requested as
3559                                  * precise, r0 and r6-r10 or any stack slot in
3560                                  * the current frame should be zero by now
3561                                  */
3562                                 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3563                                         verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3564                                         WARN_ONCE(1, "verifier backtracking bug");
3565                                         return -EFAULT;
3566                                 }
3567                                 /* we don't track register spills perfectly,
3568                                  * so fallback to force-precise instead of failing */
3569                                 if (bt_stack_mask(bt) != 0)
3570                                         return -ENOTSUPP;
3571                                 /* propagate r1-r5 to the caller */
3572                                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
3573                                         if (bt_is_reg_set(bt, i)) {
3574                                                 bt_clear_reg(bt, i);
3575                                                 bt_set_frame_reg(bt, bt->frame - 1, i);
3576                                         }
3577                                 }
3578                                 if (bt_subprog_exit(bt))
3579                                         return -EFAULT;
3580                                 return 0;
3581                         }
3582                 } else if ((bpf_helper_call(insn) &&
3583                             is_callback_calling_function(insn->imm) &&
3584                             !is_async_callback_calling_function(insn->imm)) ||
3585                            (bpf_pseudo_kfunc_call(insn) && is_callback_calling_kfunc(insn->imm))) {
3586                         /* callback-calling helper or kfunc call, which means
3587                          * we are exiting from subprog, but unlike the subprog
3588                          * call handling above, we shouldn't propagate
3589                          * precision of r1-r5 (if any requested), as they are
3590                          * not actually arguments passed directly to callback
3591                          * subprogs
3592                          */
3593                         if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) {
3594                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3595                                 WARN_ONCE(1, "verifier backtracking bug");
3596                                 return -EFAULT;
3597                         }
3598                         if (bt_stack_mask(bt) != 0)
3599                                 return -ENOTSUPP;
3600                         /* clear r1-r5 in callback subprog's mask */
3601                         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
3602                                 bt_clear_reg(bt, i);
3603                         if (bt_subprog_exit(bt))
3604                                 return -EFAULT;
3605                         return 0;
3606                 } else if (opcode == BPF_CALL) {
3607                         /* kfunc with imm==0 is invalid and fixup_kfunc_call will
3608                          * catch this error later. Make backtracking conservative
3609                          * with ENOTSUPP.
3610                          */
3611                         if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0)
3612                                 return -ENOTSUPP;
3613                         /* regular helper call sets R0 */
3614                         bt_clear_reg(bt, BPF_REG_0);
3615                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3616                                 /* if backtracing was looking for registers R1-R5
3617                                  * they should have been found already.
3618                                  */
3619                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3620                                 WARN_ONCE(1, "verifier backtracking bug");
3621                                 return -EFAULT;
3622                         }
3623                 } else if (opcode == BPF_EXIT) {
3624                         bool r0_precise;
3625
3626                         if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) {
3627                                 /* if backtracing was looking for registers R1-R5
3628                                  * they should have been found already.
3629                                  */
3630                                 verbose(env, "BUG regs %x\n", bt_reg_mask(bt));
3631                                 WARN_ONCE(1, "verifier backtracking bug");
3632                                 return -EFAULT;
3633                         }
3634
3635                         /* BPF_EXIT in subprog or callback always returns
3636                          * right after the call instruction, so by checking
3637                          * whether the instruction at subseq_idx-1 is subprog
3638                          * call or not we can distinguish actual exit from
3639                          * *subprog* from exit from *callback*. In the former
3640                          * case, we need to propagate r0 precision, if
3641                          * necessary. In the former we never do that.
3642                          */
3643                         r0_precise = subseq_idx - 1 >= 0 &&
3644                                      bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) &&
3645                                      bt_is_reg_set(bt, BPF_REG_0);
3646
3647                         bt_clear_reg(bt, BPF_REG_0);
3648                         if (bt_subprog_enter(bt))
3649                                 return -EFAULT;
3650
3651                         if (r0_precise)
3652                                 bt_set_reg(bt, BPF_REG_0);
3653                         /* r6-r9 and stack slots will stay set in caller frame
3654                          * bitmasks until we return back from callee(s)
3655                          */
3656                         return 0;
3657                 } else if (BPF_SRC(insn->code) == BPF_X) {
3658                         if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg))
3659                                 return 0;
3660                         /* dreg <cond> sreg
3661                          * Both dreg and sreg need precision before
3662                          * this insn. If only sreg was marked precise
3663                          * before it would be equally necessary to
3664                          * propagate it to dreg.
3665                          */
3666                         bt_set_reg(bt, dreg);
3667                         bt_set_reg(bt, sreg);
3668                          /* else dreg <cond> K
3669                           * Only dreg still needs precision before
3670                           * this insn, so for the K-based conditional
3671                           * there is nothing new to be marked.
3672                           */
3673                 }
3674         } else if (class == BPF_LD) {
3675                 if (!bt_is_reg_set(bt, dreg))
3676                         return 0;
3677                 bt_clear_reg(bt, dreg);
3678                 /* It's ld_imm64 or ld_abs or ld_ind.
3679                  * For ld_imm64 no further tracking of precision
3680                  * into parent is necessary
3681                  */
3682                 if (mode == BPF_IND || mode == BPF_ABS)
3683                         /* to be analyzed */
3684                         return -ENOTSUPP;
3685         }
3686         return 0;
3687 }
3688
3689 /* the scalar precision tracking algorithm:
3690  * . at the start all registers have precise=false.
3691  * . scalar ranges are tracked as normal through alu and jmp insns.
3692  * . once precise value of the scalar register is used in:
3693  *   .  ptr + scalar alu
3694  *   . if (scalar cond K|scalar)
3695  *   .  helper_call(.., scalar, ...) where ARG_CONST is expected
3696  *   backtrack through the verifier states and mark all registers and
3697  *   stack slots with spilled constants that these scalar regisers
3698  *   should be precise.
3699  * . during state pruning two registers (or spilled stack slots)
3700  *   are equivalent if both are not precise.
3701  *
3702  * Note the verifier cannot simply walk register parentage chain,
3703  * since many different registers and stack slots could have been
3704  * used to compute single precise scalar.
3705  *
3706  * The approach of starting with precise=true for all registers and then
3707  * backtrack to mark a register as not precise when the verifier detects
3708  * that program doesn't care about specific value (e.g., when helper
3709  * takes register as ARG_ANYTHING parameter) is not safe.
3710  *
3711  * It's ok to walk single parentage chain of the verifier states.
3712  * It's possible that this backtracking will go all the way till 1st insn.
3713  * All other branches will be explored for needing precision later.
3714  *
3715  * The backtracking needs to deal with cases like:
3716  *   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)
3717  * r9 -= r8
3718  * r5 = r9
3719  * if r5 > 0x79f goto pc+7
3720  *    R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff))
3721  * r5 += 1
3722  * ...
3723  * call bpf_perf_event_output#25
3724  *   where .arg5_type = ARG_CONST_SIZE_OR_ZERO
3725  *
3726  * and this case:
3727  * r6 = 1
3728  * call foo // uses callee's r6 inside to compute r0
3729  * r0 += r6
3730  * if r0 == 0 goto
3731  *
3732  * to track above reg_mask/stack_mask needs to be independent for each frame.
3733  *
3734  * Also if parent's curframe > frame where backtracking started,
3735  * the verifier need to mark registers in both frames, otherwise callees
3736  * may incorrectly prune callers. This is similar to
3737  * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences")
3738  *
3739  * For now backtracking falls back into conservative marking.
3740  */
3741 static void mark_all_scalars_precise(struct bpf_verifier_env *env,
3742                                      struct bpf_verifier_state *st)
3743 {
3744         struct bpf_func_state *func;
3745         struct bpf_reg_state *reg;
3746         int i, j;
3747
3748         if (env->log.level & BPF_LOG_LEVEL2) {
3749                 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n",
3750                         st->curframe);
3751         }
3752
3753         /* big hammer: mark all scalars precise in this path.
3754          * pop_stack may still get !precise scalars.
3755          * We also skip current state and go straight to first parent state,
3756          * because precision markings in current non-checkpointed state are
3757          * not needed. See why in the comment in __mark_chain_precision below.
3758          */
3759         for (st = st->parent; st; st = st->parent) {
3760                 for (i = 0; i <= st->curframe; i++) {
3761                         func = st->frame[i];
3762                         for (j = 0; j < BPF_REG_FP; j++) {
3763                                 reg = &func->regs[j];
3764                                 if (reg->type != SCALAR_VALUE || reg->precise)
3765                                         continue;
3766                                 reg->precise = true;
3767                                 if (env->log.level & BPF_LOG_LEVEL2) {
3768                                         verbose(env, "force_precise: frame%d: forcing r%d to be precise\n",
3769                                                 i, j);
3770                                 }
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 || reg->precise)
3777                                         continue;
3778                                 reg->precise = true;
3779                                 if (env->log.level & BPF_LOG_LEVEL2) {
3780                                         verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n",
3781                                                 i, -(j + 1) * 8);
3782                                 }
3783                         }
3784                 }
3785         }
3786 }
3787
3788 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3789 {
3790         struct bpf_func_state *func;
3791         struct bpf_reg_state *reg;
3792         int i, j;
3793
3794         for (i = 0; i <= st->curframe; i++) {
3795                 func = st->frame[i];
3796                 for (j = 0; j < BPF_REG_FP; j++) {
3797                         reg = &func->regs[j];
3798                         if (reg->type != SCALAR_VALUE)
3799                                 continue;
3800                         reg->precise = false;
3801                 }
3802                 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) {
3803                         if (!is_spilled_reg(&func->stack[j]))
3804                                 continue;
3805                         reg = &func->stack[j].spilled_ptr;
3806                         if (reg->type != SCALAR_VALUE)
3807                                 continue;
3808                         reg->precise = false;
3809                 }
3810         }
3811 }
3812
3813 static bool idset_contains(struct bpf_idset *s, u32 id)
3814 {
3815         u32 i;
3816
3817         for (i = 0; i < s->count; ++i)
3818                 if (s->ids[i] == id)
3819                         return true;
3820
3821         return false;
3822 }
3823
3824 static int idset_push(struct bpf_idset *s, u32 id)
3825 {
3826         if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids)))
3827                 return -EFAULT;
3828         s->ids[s->count++] = id;
3829         return 0;
3830 }
3831
3832 static void idset_reset(struct bpf_idset *s)
3833 {
3834         s->count = 0;
3835 }
3836
3837 /* Collect a set of IDs for all registers currently marked as precise in env->bt.
3838  * Mark all registers with these IDs as precise.
3839  */
3840 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
3841 {
3842         struct bpf_idset *precise_ids = &env->idset_scratch;
3843         struct backtrack_state *bt = &env->bt;
3844         struct bpf_func_state *func;
3845         struct bpf_reg_state *reg;
3846         DECLARE_BITMAP(mask, 64);
3847         int i, fr;
3848
3849         idset_reset(precise_ids);
3850
3851         for (fr = bt->frame; fr >= 0; fr--) {
3852                 func = st->frame[fr];
3853
3854                 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
3855                 for_each_set_bit(i, mask, 32) {
3856                         reg = &func->regs[i];
3857                         if (!reg->id || reg->type != SCALAR_VALUE)
3858                                 continue;
3859                         if (idset_push(precise_ids, reg->id))
3860                                 return -EFAULT;
3861                 }
3862
3863                 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
3864                 for_each_set_bit(i, mask, 64) {
3865                         if (i >= func->allocated_stack / BPF_REG_SIZE)
3866                                 break;
3867                         if (!is_spilled_scalar_reg(&func->stack[i]))
3868                                 continue;
3869                         reg = &func->stack[i].spilled_ptr;
3870                         if (!reg->id)
3871                                 continue;
3872                         if (idset_push(precise_ids, reg->id))
3873                                 return -EFAULT;
3874                 }
3875         }
3876
3877         for (fr = 0; fr <= st->curframe; ++fr) {
3878                 func = st->frame[fr];
3879
3880                 for (i = BPF_REG_0; i < BPF_REG_10; ++i) {
3881                         reg = &func->regs[i];
3882                         if (!reg->id)
3883                                 continue;
3884                         if (!idset_contains(precise_ids, reg->id))
3885                                 continue;
3886                         bt_set_frame_reg(bt, fr, i);
3887                 }
3888                 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) {
3889                         if (!is_spilled_scalar_reg(&func->stack[i]))
3890                                 continue;
3891                         reg = &func->stack[i].spilled_ptr;
3892                         if (!reg->id)
3893                                 continue;
3894                         if (!idset_contains(precise_ids, reg->id))
3895                                 continue;
3896                         bt_set_frame_slot(bt, fr, i);
3897                 }
3898         }
3899
3900         return 0;
3901 }
3902
3903 /*
3904  * __mark_chain_precision() backtracks BPF program instruction sequence and
3905  * chain of verifier states making sure that register *regno* (if regno >= 0)
3906  * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked
3907  * SCALARS, as well as any other registers and slots that contribute to
3908  * a tracked state of given registers/stack slots, depending on specific BPF
3909  * assembly instructions (see backtrack_insns() for exact instruction handling
3910  * logic). This backtracking relies on recorded jmp_history and is able to
3911  * traverse entire chain of parent states. This process ends only when all the
3912  * necessary registers/slots and their transitive dependencies are marked as
3913  * precise.
3914  *
3915  * One important and subtle aspect is that precise marks *do not matter* in
3916  * the currently verified state (current state). It is important to understand
3917  * why this is the case.
3918  *
3919  * First, note that current state is the state that is not yet "checkpointed",
3920  * i.e., it is not yet put into env->explored_states, and it has no children
3921  * states as well. It's ephemeral, and can end up either a) being discarded if
3922  * compatible explored state is found at some point or BPF_EXIT instruction is
3923  * reached or b) checkpointed and put into env->explored_states, branching out
3924  * into one or more children states.
3925  *
3926  * In the former case, precise markings in current state are completely
3927  * ignored by state comparison code (see regsafe() for details). Only
3928  * checkpointed ("old") state precise markings are important, and if old
3929  * state's register/slot is precise, regsafe() assumes current state's
3930  * register/slot as precise and checks value ranges exactly and precisely. If
3931  * states turn out to be compatible, current state's necessary precise
3932  * markings and any required parent states' precise markings are enforced
3933  * after the fact with propagate_precision() logic, after the fact. But it's
3934  * important to realize that in this case, even after marking current state
3935  * registers/slots as precise, we immediately discard current state. So what
3936  * actually matters is any of the precise markings propagated into current
3937  * state's parent states, which are always checkpointed (due to b) case above).
3938  * As such, for scenario a) it doesn't matter if current state has precise
3939  * markings set or not.
3940  *
3941  * Now, for the scenario b), checkpointing and forking into child(ren)
3942  * state(s). Note that before current state gets to checkpointing step, any
3943  * processed instruction always assumes precise SCALAR register/slot
3944  * knowledge: if precise value or range is useful to prune jump branch, BPF
3945  * verifier takes this opportunity enthusiastically. Similarly, when
3946  * register's value is used to calculate offset or memory address, exact
3947  * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to
3948  * what we mentioned above about state comparison ignoring precise markings
3949  * during state comparison, BPF verifier ignores and also assumes precise
3950  * markings *at will* during instruction verification process. But as verifier
3951  * assumes precision, it also propagates any precision dependencies across
3952  * parent states, which are not yet finalized, so can be further restricted
3953  * based on new knowledge gained from restrictions enforced by their children
3954  * states. This is so that once those parent states are finalized, i.e., when
3955  * they have no more active children state, state comparison logic in
3956  * is_state_visited() would enforce strict and precise SCALAR ranges, if
3957  * required for correctness.
3958  *
3959  * To build a bit more intuition, note also that once a state is checkpointed,
3960  * the path we took to get to that state is not important. This is crucial
3961  * property for state pruning. When state is checkpointed and finalized at
3962  * some instruction index, it can be correctly and safely used to "short
3963  * circuit" any *compatible* state that reaches exactly the same instruction
3964  * index. I.e., if we jumped to that instruction from a completely different
3965  * code path than original finalized state was derived from, it doesn't
3966  * matter, current state can be discarded because from that instruction
3967  * forward having a compatible state will ensure we will safely reach the
3968  * exit. States describe preconditions for further exploration, but completely
3969  * forget the history of how we got here.
3970  *
3971  * This also means that even if we needed precise SCALAR range to get to
3972  * finalized state, but from that point forward *that same* SCALAR register is
3973  * never used in a precise context (i.e., it's precise value is not needed for
3974  * correctness), it's correct and safe to mark such register as "imprecise"
3975  * (i.e., precise marking set to false). This is what we rely on when we do
3976  * not set precise marking in current state. If no child state requires
3977  * precision for any given SCALAR register, it's safe to dictate that it can
3978  * be imprecise. If any child state does require this register to be precise,
3979  * we'll mark it precise later retroactively during precise markings
3980  * propagation from child state to parent states.
3981  *
3982  * Skipping precise marking setting in current state is a mild version of
3983  * relying on the above observation. But we can utilize this property even
3984  * more aggressively by proactively forgetting any precise marking in the
3985  * current state (which we inherited from the parent state), right before we
3986  * checkpoint it and branch off into new child state. This is done by
3987  * mark_all_scalars_imprecise() to hopefully get more permissive and generic
3988  * finalized states which help in short circuiting more future states.
3989  */
3990 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno)
3991 {
3992         struct backtrack_state *bt = &env->bt;
3993         struct bpf_verifier_state *st = env->cur_state;
3994         int first_idx = st->first_insn_idx;
3995         int last_idx = env->insn_idx;
3996         int subseq_idx = -1;
3997         struct bpf_func_state *func;
3998         struct bpf_reg_state *reg;
3999         bool skip_first = true;
4000         int i, fr, err;
4001
4002         if (!env->bpf_capable)
4003                 return 0;
4004
4005         /* set frame number from which we are starting to backtrack */
4006         bt_init(bt, env->cur_state->curframe);
4007
4008         /* Do sanity checks against current state of register and/or stack
4009          * slot, but don't set precise flag in current state, as precision
4010          * tracking in the current state is unnecessary.
4011          */
4012         func = st->frame[bt->frame];
4013         if (regno >= 0) {
4014                 reg = &func->regs[regno];
4015                 if (reg->type != SCALAR_VALUE) {
4016                         WARN_ONCE(1, "backtracing misuse");
4017                         return -EFAULT;
4018                 }
4019                 bt_set_reg(bt, regno);
4020         }
4021
4022         if (bt_empty(bt))
4023                 return 0;
4024
4025         for (;;) {
4026                 DECLARE_BITMAP(mask, 64);
4027                 u32 history = st->jmp_history_cnt;
4028
4029                 if (env->log.level & BPF_LOG_LEVEL2) {
4030                         verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n",
4031                                 bt->frame, last_idx, first_idx, subseq_idx);
4032                 }
4033
4034                 /* If some register with scalar ID is marked as precise,
4035                  * make sure that all registers sharing this ID are also precise.
4036                  * This is needed to estimate effect of find_equal_scalars().
4037                  * Do this at the last instruction of each state,
4038                  * bpf_reg_state::id fields are valid for these instructions.
4039                  *
4040                  * Allows to track precision in situation like below:
4041                  *
4042                  *     r2 = unknown value
4043                  *     ...
4044                  *   --- state #0 ---
4045                  *     ...
4046                  *     r1 = r2                 // r1 and r2 now share the same ID
4047                  *     ...
4048                  *   --- state #1 {r1.id = A, r2.id = A} ---
4049                  *     ...
4050                  *     if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1
4051                  *     ...
4052                  *   --- state #2 {r1.id = A, r2.id = A} ---
4053                  *     r3 = r10
4054                  *     r3 += r1                // need to mark both r1 and r2
4055                  */
4056                 if (mark_precise_scalar_ids(env, st))
4057                         return -EFAULT;
4058
4059                 if (last_idx < 0) {
4060                         /* we are at the entry into subprog, which
4061                          * is expected for global funcs, but only if
4062                          * requested precise registers are R1-R5
4063                          * (which are global func's input arguments)
4064                          */
4065                         if (st->curframe == 0 &&
4066                             st->frame[0]->subprogno > 0 &&
4067                             st->frame[0]->callsite == BPF_MAIN_FUNC &&
4068                             bt_stack_mask(bt) == 0 &&
4069                             (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) {
4070                                 bitmap_from_u64(mask, bt_reg_mask(bt));
4071                                 for_each_set_bit(i, mask, 32) {
4072                                         reg = &st->frame[0]->regs[i];
4073                                         bt_clear_reg(bt, i);
4074                                         if (reg->type == SCALAR_VALUE)
4075                                                 reg->precise = true;
4076                                 }
4077                                 return 0;
4078                         }
4079
4080                         verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n",
4081                                 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt));
4082                         WARN_ONCE(1, "verifier backtracking bug");
4083                         return -EFAULT;
4084                 }
4085
4086                 for (i = last_idx;;) {
4087                         if (skip_first) {
4088                                 err = 0;
4089                                 skip_first = false;
4090                         } else {
4091                                 err = backtrack_insn(env, i, subseq_idx, bt);
4092                         }
4093                         if (err == -ENOTSUPP) {
4094                                 mark_all_scalars_precise(env, env->cur_state);
4095                                 bt_reset(bt);
4096                                 return 0;
4097                         } else if (err) {
4098                                 return err;
4099                         }
4100                         if (bt_empty(bt))
4101                                 /* Found assignment(s) into tracked register in this state.
4102                                  * Since this state is already marked, just return.
4103                                  * Nothing to be tracked further in the parent state.
4104                                  */
4105                                 return 0;
4106                         subseq_idx = i;
4107                         i = get_prev_insn_idx(st, i, &history);
4108                         if (i == -ENOENT)
4109                                 break;
4110                         if (i >= env->prog->len) {
4111                                 /* This can happen if backtracking reached insn 0
4112                                  * and there are still reg_mask or stack_mask
4113                                  * to backtrack.
4114                                  * It means the backtracking missed the spot where
4115                                  * particular register was initialized with a constant.
4116                                  */
4117                                 verbose(env, "BUG backtracking idx %d\n", i);
4118                                 WARN_ONCE(1, "verifier backtracking bug");
4119                                 return -EFAULT;
4120                         }
4121                 }
4122                 st = st->parent;
4123                 if (!st)
4124                         break;
4125
4126                 for (fr = bt->frame; fr >= 0; fr--) {
4127                         func = st->frame[fr];
4128                         bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr));
4129                         for_each_set_bit(i, mask, 32) {
4130                                 reg = &func->regs[i];
4131                                 if (reg->type != SCALAR_VALUE) {
4132                                         bt_clear_frame_reg(bt, fr, i);
4133                                         continue;
4134                                 }
4135                                 if (reg->precise)
4136                                         bt_clear_frame_reg(bt, fr, i);
4137                                 else
4138                                         reg->precise = true;
4139                         }
4140
4141                         bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr));
4142                         for_each_set_bit(i, mask, 64) {
4143                                 if (i >= func->allocated_stack / BPF_REG_SIZE) {
4144                                         /* the sequence of instructions:
4145                                          * 2: (bf) r3 = r10
4146                                          * 3: (7b) *(u64 *)(r3 -8) = r0
4147                                          * 4: (79) r4 = *(u64 *)(r10 -8)
4148                                          * doesn't contain jmps. It's backtracked
4149                                          * as a single block.
4150                                          * During backtracking insn 3 is not recognized as
4151                                          * stack access, so at the end of backtracking
4152                                          * stack slot fp-8 is still marked in stack_mask.
4153                                          * However the parent state may not have accessed
4154                                          * fp-8 and it's "unallocated" stack space.
4155                                          * In such case fallback to conservative.
4156                                          */
4157                                         mark_all_scalars_precise(env, env->cur_state);
4158                                         bt_reset(bt);
4159                                         return 0;
4160                                 }
4161
4162                                 if (!is_spilled_scalar_reg(&func->stack[i])) {
4163                                         bt_clear_frame_slot(bt, fr, i);
4164                                         continue;
4165                                 }
4166                                 reg = &func->stack[i].spilled_ptr;
4167                                 if (reg->precise)
4168                                         bt_clear_frame_slot(bt, fr, i);
4169                                 else
4170                                         reg->precise = true;
4171                         }
4172                         if (env->log.level & BPF_LOG_LEVEL2) {
4173                                 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4174                                              bt_frame_reg_mask(bt, fr));
4175                                 verbose(env, "mark_precise: frame%d: parent state regs=%s ",
4176                                         fr, env->tmp_str_buf);
4177                                 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN,
4178                                                bt_frame_stack_mask(bt, fr));
4179                                 verbose(env, "stack=%s: ", env->tmp_str_buf);
4180                                 print_verifier_state(env, func, true);
4181                         }
4182                 }
4183
4184                 if (bt_empty(bt))
4185                         return 0;
4186
4187                 subseq_idx = first_idx;
4188                 last_idx = st->last_insn_idx;
4189                 first_idx = st->first_insn_idx;
4190         }
4191
4192         /* if we still have requested precise regs or slots, we missed
4193          * something (e.g., stack access through non-r10 register), so
4194          * fallback to marking all precise
4195          */
4196         if (!bt_empty(bt)) {
4197                 mark_all_scalars_precise(env, env->cur_state);
4198                 bt_reset(bt);
4199         }
4200
4201         return 0;
4202 }
4203
4204 int mark_chain_precision(struct bpf_verifier_env *env, int regno)
4205 {
4206         return __mark_chain_precision(env, regno);
4207 }
4208
4209 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to
4210  * desired reg and stack masks across all relevant frames
4211  */
4212 static int mark_chain_precision_batch(struct bpf_verifier_env *env)
4213 {
4214         return __mark_chain_precision(env, -1);
4215 }
4216
4217 static bool is_spillable_regtype(enum bpf_reg_type type)
4218 {
4219         switch (base_type(type)) {
4220         case PTR_TO_MAP_VALUE:
4221         case PTR_TO_STACK:
4222         case PTR_TO_CTX:
4223         case PTR_TO_PACKET:
4224         case PTR_TO_PACKET_META:
4225         case PTR_TO_PACKET_END:
4226         case PTR_TO_FLOW_KEYS:
4227         case CONST_PTR_TO_MAP:
4228         case PTR_TO_SOCKET:
4229         case PTR_TO_SOCK_COMMON:
4230         case PTR_TO_TCP_SOCK:
4231         case PTR_TO_XDP_SOCK:
4232         case PTR_TO_BTF_ID:
4233         case PTR_TO_BUF:
4234         case PTR_TO_MEM:
4235         case PTR_TO_FUNC:
4236         case PTR_TO_MAP_KEY:
4237                 return true;
4238         default:
4239                 return false;
4240         }
4241 }
4242
4243 /* Does this register contain a constant zero? */
4244 static bool register_is_null(struct bpf_reg_state *reg)
4245 {
4246         return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
4247 }
4248
4249 static bool register_is_const(struct bpf_reg_state *reg)
4250 {
4251         return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off);
4252 }
4253
4254 static bool __is_scalar_unbounded(struct bpf_reg_state *reg)
4255 {
4256         return tnum_is_unknown(reg->var_off) &&
4257                reg->smin_value == S64_MIN && reg->smax_value == S64_MAX &&
4258                reg->umin_value == 0 && reg->umax_value == U64_MAX &&
4259                reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX &&
4260                reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX;
4261 }
4262
4263 static bool register_is_bounded(struct bpf_reg_state *reg)
4264 {
4265         return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg);
4266 }
4267
4268 static bool __is_pointer_value(bool allow_ptr_leaks,
4269                                const struct bpf_reg_state *reg)
4270 {
4271         if (allow_ptr_leaks)
4272                 return false;
4273
4274         return reg->type != SCALAR_VALUE;
4275 }
4276
4277 /* Copy src state preserving dst->parent and dst->live fields */
4278 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src)
4279 {
4280         struct bpf_reg_state *parent = dst->parent;
4281         enum bpf_reg_liveness live = dst->live;
4282
4283         *dst = *src;
4284         dst->parent = parent;
4285         dst->live = live;
4286 }
4287
4288 static void save_register_state(struct bpf_func_state *state,
4289                                 int spi, struct bpf_reg_state *reg,
4290                                 int size)
4291 {
4292         int i;
4293
4294         copy_register_state(&state->stack[spi].spilled_ptr, reg);
4295         if (size == BPF_REG_SIZE)
4296                 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4297
4298         for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--)
4299                 state->stack[spi].slot_type[i - 1] = STACK_SPILL;
4300
4301         /* size < 8 bytes spill */
4302         for (; i; i--)
4303                 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]);
4304 }
4305
4306 static bool is_bpf_st_mem(struct bpf_insn *insn)
4307 {
4308         return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM;
4309 }
4310
4311 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers,
4312  * stack boundary and alignment are checked in check_mem_access()
4313  */
4314 static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
4315                                        /* stack frame we're writing to */
4316                                        struct bpf_func_state *state,
4317                                        int off, int size, int value_regno,
4318                                        int insn_idx)
4319 {
4320         struct bpf_func_state *cur; /* state of the current function */
4321         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
4322         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4323         struct bpf_reg_state *reg = NULL;
4324         u32 dst_reg = insn->dst_reg;
4325
4326         err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE));
4327         if (err)
4328                 return err;
4329         /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
4330          * so it's aligned access and [off, off + size) are within stack limits
4331          */
4332         if (!env->allow_ptr_leaks &&
4333             is_spilled_reg(&state->stack[spi]) &&
4334             size != BPF_REG_SIZE) {
4335                 verbose(env, "attempt to corrupt spilled pointer on stack\n");
4336                 return -EACCES;
4337         }
4338
4339         cur = env->cur_state->frame[env->cur_state->curframe];
4340         if (value_regno >= 0)
4341                 reg = &cur->regs[value_regno];
4342         if (!env->bypass_spec_v4) {
4343                 bool sanitize = reg && is_spillable_regtype(reg->type);
4344
4345                 for (i = 0; i < size; i++) {
4346                         u8 type = state->stack[spi].slot_type[i];
4347
4348                         if (type != STACK_MISC && type != STACK_ZERO) {
4349                                 sanitize = true;
4350                                 break;
4351                         }
4352                 }
4353
4354                 if (sanitize)
4355                         env->insn_aux_data[insn_idx].sanitize_stack_spill = true;
4356         }
4357
4358         err = destroy_if_dynptr_stack_slot(env, state, spi);
4359         if (err)
4360                 return err;
4361
4362         mark_stack_slot_scratched(env, spi);
4363         if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) &&
4364             !register_is_null(reg) && env->bpf_capable) {
4365                 if (dst_reg != BPF_REG_FP) {
4366                         /* The backtracking logic can only recognize explicit
4367                          * stack slot address like [fp - 8]. Other spill of
4368                          * scalar via different register has to be conservative.
4369                          * Backtrack from here and mark all registers as precise
4370                          * that contributed into 'reg' being a constant.
4371                          */
4372                         err = mark_chain_precision(env, value_regno);
4373                         if (err)
4374                                 return err;
4375                 }
4376                 save_register_state(state, spi, reg, size);
4377                 /* Break the relation on a narrowing spill. */
4378                 if (fls64(reg->umax_value) > BITS_PER_BYTE * size)
4379                         state->stack[spi].spilled_ptr.id = 0;
4380         } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) &&
4381                    insn->imm != 0 && env->bpf_capable) {
4382                 struct bpf_reg_state fake_reg = {};
4383
4384                 __mark_reg_known(&fake_reg, insn->imm);
4385                 fake_reg.type = SCALAR_VALUE;
4386                 save_register_state(state, spi, &fake_reg, size);
4387         } else if (reg && is_spillable_regtype(reg->type)) {
4388                 /* register containing pointer is being spilled into stack */
4389                 if (size != BPF_REG_SIZE) {
4390                         verbose_linfo(env, insn_idx, "; ");
4391                         verbose(env, "invalid size of register spill\n");
4392                         return -EACCES;
4393                 }
4394                 if (state != cur && reg->type == PTR_TO_STACK) {
4395                         verbose(env, "cannot spill pointers to stack into stack frame of the caller\n");
4396                         return -EINVAL;
4397                 }
4398                 save_register_state(state, spi, reg, size);
4399         } else {
4400                 u8 type = STACK_MISC;
4401
4402                 /* regular write of data into stack destroys any spilled ptr */
4403                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4404                 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */
4405                 if (is_stack_slot_special(&state->stack[spi]))
4406                         for (i = 0; i < BPF_REG_SIZE; i++)
4407                                 scrub_spilled_slot(&state->stack[spi].slot_type[i]);
4408
4409                 /* only mark the slot as written if all 8 bytes were written
4410                  * otherwise read propagation may incorrectly stop too soon
4411                  * when stack slots are partially written.
4412                  * This heuristic means that read propagation will be
4413                  * conservative, since it will add reg_live_read marks
4414                  * to stack slots all the way to first state when programs
4415                  * writes+reads less than 8 bytes
4416                  */
4417                 if (size == BPF_REG_SIZE)
4418                         state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN;
4419
4420                 /* when we zero initialize stack slots mark them as such */
4421                 if ((reg && register_is_null(reg)) ||
4422                     (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) {
4423                         /* backtracking doesn't work for STACK_ZERO yet. */
4424                         err = mark_chain_precision(env, value_regno);
4425                         if (err)
4426                                 return err;
4427                         type = STACK_ZERO;
4428                 }
4429
4430                 /* Mark slots affected by this stack write. */
4431                 for (i = 0; i < size; i++)
4432                         state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] =
4433                                 type;
4434         }
4435         return 0;
4436 }
4437
4438 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is
4439  * known to contain a variable offset.
4440  * This function checks whether the write is permitted and conservatively
4441  * tracks the effects of the write, considering that each stack slot in the
4442  * dynamic range is potentially written to.
4443  *
4444  * 'off' includes 'regno->off'.
4445  * 'value_regno' can be -1, meaning that an unknown value is being written to
4446  * the stack.
4447  *
4448  * Spilled pointers in range are not marked as written because we don't know
4449  * what's going to be actually written. This means that read propagation for
4450  * future reads cannot be terminated by this write.
4451  *
4452  * For privileged programs, uninitialized stack slots are considered
4453  * initialized by this write (even though we don't know exactly what offsets
4454  * are going to be written to). The idea is that we don't want the verifier to
4455  * reject future reads that access slots written to through variable offsets.
4456  */
4457 static int check_stack_write_var_off(struct bpf_verifier_env *env,
4458                                      /* func where register points to */
4459                                      struct bpf_func_state *state,
4460                                      int ptr_regno, int off, int size,
4461                                      int value_regno, int insn_idx)
4462 {
4463         struct bpf_func_state *cur; /* state of the current function */
4464         int min_off, max_off;
4465         int i, err;
4466         struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL;
4467         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
4468         bool writing_zero = false;
4469         /* set if the fact that we're writing a zero is used to let any
4470          * stack slots remain STACK_ZERO
4471          */
4472         bool zero_used = false;
4473
4474         cur = env->cur_state->frame[env->cur_state->curframe];
4475         ptr_reg = &cur->regs[ptr_regno];
4476         min_off = ptr_reg->smin_value + off;
4477         max_off = ptr_reg->smax_value + off + size;
4478         if (value_regno >= 0)
4479                 value_reg = &cur->regs[value_regno];
4480         if ((value_reg && register_is_null(value_reg)) ||
4481             (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
4482                 writing_zero = true;
4483
4484         err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE));
4485         if (err)
4486                 return err;
4487
4488         for (i = min_off; i < max_off; i++) {
4489                 int spi;
4490
4491                 spi = __get_spi(i);
4492                 err = destroy_if_dynptr_stack_slot(env, state, spi);
4493                 if (err)
4494                         return err;
4495         }
4496
4497         /* Variable offset writes destroy any spilled pointers in range. */
4498         for (i = min_off; i < max_off; i++) {
4499                 u8 new_type, *stype;
4500                 int slot, spi;
4501
4502                 slot = -i - 1;
4503                 spi = slot / BPF_REG_SIZE;
4504                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
4505                 mark_stack_slot_scratched(env, spi);
4506
4507                 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) {
4508                         /* Reject the write if range we may write to has not
4509                          * been initialized beforehand. If we didn't reject
4510                          * here, the ptr status would be erased below (even
4511                          * though not all slots are actually overwritten),
4512                          * possibly opening the door to leaks.
4513                          *
4514                          * We do however catch STACK_INVALID case below, and
4515                          * only allow reading possibly uninitialized memory
4516                          * later for CAP_PERFMON, as the write may not happen to
4517                          * that slot.
4518                          */
4519                         verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d",
4520                                 insn_idx, i);
4521                         return -EINVAL;
4522                 }
4523
4524                 /* Erase all spilled pointers. */
4525                 state->stack[spi].spilled_ptr.type = NOT_INIT;
4526
4527                 /* Update the slot type. */
4528                 new_type = STACK_MISC;
4529                 if (writing_zero && *stype == STACK_ZERO) {
4530                         new_type = STACK_ZERO;
4531                         zero_used = true;
4532                 }
4533                 /* If the slot is STACK_INVALID, we check whether it's OK to
4534                  * pretend that it will be initialized by this write. The slot
4535                  * might not actually be written to, and so if we mark it as
4536                  * initialized future reads might leak uninitialized memory.
4537                  * For privileged programs, we will accept such reads to slots
4538                  * that may or may not be written because, if we're reject
4539                  * them, the error would be too confusing.
4540                  */
4541                 if (*stype == STACK_INVALID && !env->allow_uninit_stack) {
4542                         verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d",
4543                                         insn_idx, i);
4544                         return -EINVAL;
4545                 }
4546                 *stype = new_type;
4547         }
4548         if (zero_used) {
4549                 /* backtracking doesn't work for STACK_ZERO yet. */
4550                 err = mark_chain_precision(env, value_regno);
4551                 if (err)
4552                         return err;
4553         }
4554         return 0;
4555 }
4556
4557 /* When register 'dst_regno' is assigned some values from stack[min_off,
4558  * max_off), we set the register's type according to the types of the
4559  * respective stack slots. If all the stack values are known to be zeros, then
4560  * so is the destination reg. Otherwise, the register is considered to be
4561  * SCALAR. This function does not deal with register filling; the caller must
4562  * ensure that all spilled registers in the stack range have been marked as
4563  * read.
4564  */
4565 static void mark_reg_stack_read(struct bpf_verifier_env *env,
4566                                 /* func where src register points to */
4567                                 struct bpf_func_state *ptr_state,
4568                                 int min_off, int max_off, int dst_regno)
4569 {
4570         struct bpf_verifier_state *vstate = env->cur_state;
4571         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4572         int i, slot, spi;
4573         u8 *stype;
4574         int zeros = 0;
4575
4576         for (i = min_off; i < max_off; i++) {
4577                 slot = -i - 1;
4578                 spi = slot / BPF_REG_SIZE;
4579                 mark_stack_slot_scratched(env, spi);
4580                 stype = ptr_state->stack[spi].slot_type;
4581                 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO)
4582                         break;
4583                 zeros++;
4584         }
4585         if (zeros == max_off - min_off) {
4586                 /* any access_size read into register is zero extended,
4587                  * so the whole register == const_zero
4588                  */
4589                 __mark_reg_const_zero(&state->regs[dst_regno]);
4590                 /* backtracking doesn't support STACK_ZERO yet,
4591                  * so mark it precise here, so that later
4592                  * backtracking can stop here.
4593                  * Backtracking may not need this if this register
4594                  * doesn't participate in pointer adjustment.
4595                  * Forward propagation of precise flag is not
4596                  * necessary either. This mark is only to stop
4597                  * backtracking. Any register that contributed
4598                  * to const 0 was marked precise before spill.
4599                  */
4600                 state->regs[dst_regno].precise = true;
4601         } else {
4602                 /* have read misc data from the stack */
4603                 mark_reg_unknown(env, state->regs, dst_regno);
4604         }
4605         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4606 }
4607
4608 /* Read the stack at 'off' and put the results into the register indicated by
4609  * 'dst_regno'. It handles reg filling if the addressed stack slot is a
4610  * spilled reg.
4611  *
4612  * 'dst_regno' can be -1, meaning that the read value is not going to a
4613  * register.
4614  *
4615  * The access is assumed to be within the current stack bounds.
4616  */
4617 static int check_stack_read_fixed_off(struct bpf_verifier_env *env,
4618                                       /* func where src register points to */
4619                                       struct bpf_func_state *reg_state,
4620                                       int off, int size, int dst_regno)
4621 {
4622         struct bpf_verifier_state *vstate = env->cur_state;
4623         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4624         int i, slot = -off - 1, spi = slot / BPF_REG_SIZE;
4625         struct bpf_reg_state *reg;
4626         u8 *stype, type;
4627
4628         stype = reg_state->stack[spi].slot_type;
4629         reg = &reg_state->stack[spi].spilled_ptr;
4630
4631         mark_stack_slot_scratched(env, spi);
4632
4633         if (is_spilled_reg(&reg_state->stack[spi])) {
4634                 u8 spill_size = 1;
4635
4636                 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--)
4637                         spill_size++;
4638
4639                 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) {
4640                         if (reg->type != SCALAR_VALUE) {
4641                                 verbose_linfo(env, env->insn_idx, "; ");
4642                                 verbose(env, "invalid size of register fill\n");
4643                                 return -EACCES;
4644                         }
4645
4646                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4647                         if (dst_regno < 0)
4648                                 return 0;
4649
4650                         if (!(off % BPF_REG_SIZE) && size == spill_size) {
4651                                 /* The earlier check_reg_arg() has decided the
4652                                  * subreg_def for this insn.  Save it first.
4653                                  */
4654                                 s32 subreg_def = state->regs[dst_regno].subreg_def;
4655
4656                                 copy_register_state(&state->regs[dst_regno], reg);
4657                                 state->regs[dst_regno].subreg_def = subreg_def;
4658                         } else {
4659                                 for (i = 0; i < size; i++) {
4660                                         type = stype[(slot - i) % BPF_REG_SIZE];
4661                                         if (type == STACK_SPILL)
4662                                                 continue;
4663                                         if (type == STACK_MISC)
4664                                                 continue;
4665                                         if (type == STACK_INVALID && env->allow_uninit_stack)
4666                                                 continue;
4667                                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4668                                                 off, i, size);
4669                                         return -EACCES;
4670                                 }
4671                                 mark_reg_unknown(env, state->regs, dst_regno);
4672                         }
4673                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4674                         return 0;
4675                 }
4676
4677                 if (dst_regno >= 0) {
4678                         /* restore register state from stack */
4679                         copy_register_state(&state->regs[dst_regno], reg);
4680                         /* mark reg as written since spilled pointer state likely
4681                          * has its liveness marks cleared by is_state_visited()
4682                          * which resets stack/reg liveness for state transitions
4683                          */
4684                         state->regs[dst_regno].live |= REG_LIVE_WRITTEN;
4685                 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) {
4686                         /* If dst_regno==-1, the caller is asking us whether
4687                          * it is acceptable to use this value as a SCALAR_VALUE
4688                          * (e.g. for XADD).
4689                          * We must not allow unprivileged callers to do that
4690                          * with spilled pointers.
4691                          */
4692                         verbose(env, "leaking pointer from stack off %d\n",
4693                                 off);
4694                         return -EACCES;
4695                 }
4696                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4697         } else {
4698                 for (i = 0; i < size; i++) {
4699                         type = stype[(slot - i) % BPF_REG_SIZE];
4700                         if (type == STACK_MISC)
4701                                 continue;
4702                         if (type == STACK_ZERO)
4703                                 continue;
4704                         if (type == STACK_INVALID && env->allow_uninit_stack)
4705                                 continue;
4706                         verbose(env, "invalid read from stack off %d+%d size %d\n",
4707                                 off, i, size);
4708                         return -EACCES;
4709                 }
4710                 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
4711                 if (dst_regno >= 0)
4712                         mark_reg_stack_read(env, reg_state, off, off + size, dst_regno);
4713         }
4714         return 0;
4715 }
4716
4717 enum bpf_access_src {
4718         ACCESS_DIRECT = 1,  /* the access is performed by an instruction */
4719         ACCESS_HELPER = 2,  /* the access is performed by a helper */
4720 };
4721
4722 static int check_stack_range_initialized(struct bpf_verifier_env *env,
4723                                          int regno, int off, int access_size,
4724                                          bool zero_size_allowed,
4725                                          enum bpf_access_src type,
4726                                          struct bpf_call_arg_meta *meta);
4727
4728 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno)
4729 {
4730         return cur_regs(env) + regno;
4731 }
4732
4733 /* Read the stack at 'ptr_regno + off' and put the result into the register
4734  * 'dst_regno'.
4735  * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'),
4736  * but not its variable offset.
4737  * 'size' is assumed to be <= reg size and the access is assumed to be aligned.
4738  *
4739  * As opposed to check_stack_read_fixed_off, this function doesn't deal with
4740  * filling registers (i.e. reads of spilled register cannot be detected when
4741  * the offset is not fixed). We conservatively mark 'dst_regno' as containing
4742  * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable
4743  * offset; for a fixed offset check_stack_read_fixed_off should be used
4744  * instead.
4745  */
4746 static int check_stack_read_var_off(struct bpf_verifier_env *env,
4747                                     int ptr_regno, int off, int size, int dst_regno)
4748 {
4749         /* The state of the source register. */
4750         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4751         struct bpf_func_state *ptr_state = func(env, reg);
4752         int err;
4753         int min_off, max_off;
4754
4755         /* Note that we pass a NULL meta, so raw access will not be permitted.
4756          */
4757         err = check_stack_range_initialized(env, ptr_regno, off, size,
4758                                             false, ACCESS_DIRECT, NULL);
4759         if (err)
4760                 return err;
4761
4762         min_off = reg->smin_value + off;
4763         max_off = reg->smax_value + off;
4764         mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno);
4765         return 0;
4766 }
4767
4768 /* check_stack_read dispatches to check_stack_read_fixed_off or
4769  * check_stack_read_var_off.
4770  *
4771  * The caller must ensure that the offset falls within the allocated stack
4772  * bounds.
4773  *
4774  * 'dst_regno' is a register which will receive the value from the stack. It
4775  * can be -1, meaning that the read value is not going to a register.
4776  */
4777 static int check_stack_read(struct bpf_verifier_env *env,
4778                             int ptr_regno, int off, int size,
4779                             int dst_regno)
4780 {
4781         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4782         struct bpf_func_state *state = func(env, reg);
4783         int err;
4784         /* Some accesses are only permitted with a static offset. */
4785         bool var_off = !tnum_is_const(reg->var_off);
4786
4787         /* The offset is required to be static when reads don't go to a
4788          * register, in order to not leak pointers (see
4789          * check_stack_read_fixed_off).
4790          */
4791         if (dst_regno < 0 && var_off) {
4792                 char tn_buf[48];
4793
4794                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4795                 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n",
4796                         tn_buf, off, size);
4797                 return -EACCES;
4798         }
4799         /* Variable offset is prohibited for unprivileged mode for simplicity
4800          * since it requires corresponding support in Spectre masking for stack
4801          * ALU. See also retrieve_ptr_limit(). The check in
4802          * check_stack_access_for_ptr_arithmetic() called by
4803          * adjust_ptr_min_max_vals() prevents users from creating stack pointers
4804          * with variable offsets, therefore no check is required here. Further,
4805          * just checking it here would be insufficient as speculative stack
4806          * writes could still lead to unsafe speculative behaviour.
4807          */
4808         if (!var_off) {
4809                 off += reg->var_off.value;
4810                 err = check_stack_read_fixed_off(env, state, off, size,
4811                                                  dst_regno);
4812         } else {
4813                 /* Variable offset stack reads need more conservative handling
4814                  * than fixed offset ones. Note that dst_regno >= 0 on this
4815                  * branch.
4816                  */
4817                 err = check_stack_read_var_off(env, ptr_regno, off, size,
4818                                                dst_regno);
4819         }
4820         return err;
4821 }
4822
4823
4824 /* check_stack_write dispatches to check_stack_write_fixed_off or
4825  * check_stack_write_var_off.
4826  *
4827  * 'ptr_regno' is the register used as a pointer into the stack.
4828  * 'off' includes 'ptr_regno->off', but not its variable offset (if any).
4829  * 'value_regno' is the register whose value we're writing to the stack. It can
4830  * be -1, meaning that we're not writing from a register.
4831  *
4832  * The caller must ensure that the offset falls within the maximum stack size.
4833  */
4834 static int check_stack_write(struct bpf_verifier_env *env,
4835                              int ptr_regno, int off, int size,
4836                              int value_regno, int insn_idx)
4837 {
4838         struct bpf_reg_state *reg = reg_state(env, ptr_regno);
4839         struct bpf_func_state *state = func(env, reg);
4840         int err;
4841
4842         if (tnum_is_const(reg->var_off)) {
4843                 off += reg->var_off.value;
4844                 err = check_stack_write_fixed_off(env, state, off, size,
4845                                                   value_regno, insn_idx);
4846         } else {
4847                 /* Variable offset stack reads need more conservative handling
4848                  * than fixed offset ones.
4849                  */
4850                 err = check_stack_write_var_off(env, state,
4851                                                 ptr_regno, off, size,
4852                                                 value_regno, insn_idx);
4853         }
4854         return err;
4855 }
4856
4857 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno,
4858                                  int off, int size, enum bpf_access_type type)
4859 {
4860         struct bpf_reg_state *regs = cur_regs(env);
4861         struct bpf_map *map = regs[regno].map_ptr;
4862         u32 cap = bpf_map_flags_to_cap(map);
4863
4864         if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) {
4865                 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n",
4866                         map->value_size, off, size);
4867                 return -EACCES;
4868         }
4869
4870         if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) {
4871                 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n",
4872                         map->value_size, off, size);
4873                 return -EACCES;
4874         }
4875
4876         return 0;
4877 }
4878
4879 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */
4880 static int __check_mem_access(struct bpf_verifier_env *env, int regno,
4881                               int off, int size, u32 mem_size,
4882                               bool zero_size_allowed)
4883 {
4884         bool size_ok = size > 0 || (size == 0 && zero_size_allowed);
4885         struct bpf_reg_state *reg;
4886
4887         if (off >= 0 && size_ok && (u64)off + size <= mem_size)
4888                 return 0;
4889
4890         reg = &cur_regs(env)[regno];
4891         switch (reg->type) {
4892         case PTR_TO_MAP_KEY:
4893                 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n",
4894                         mem_size, off, size);
4895                 break;
4896         case PTR_TO_MAP_VALUE:
4897                 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n",
4898                         mem_size, off, size);
4899                 break;
4900         case PTR_TO_PACKET:
4901         case PTR_TO_PACKET_META:
4902         case PTR_TO_PACKET_END:
4903                 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n",
4904                         off, size, regno, reg->id, off, mem_size);
4905                 break;
4906         case PTR_TO_MEM:
4907         default:
4908                 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n",
4909                         mem_size, off, size);
4910         }
4911
4912         return -EACCES;
4913 }
4914
4915 /* check read/write into a memory region with possible variable offset */
4916 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno,
4917                                    int off, int size, u32 mem_size,
4918                                    bool zero_size_allowed)
4919 {
4920         struct bpf_verifier_state *vstate = env->cur_state;
4921         struct bpf_func_state *state = vstate->frame[vstate->curframe];
4922         struct bpf_reg_state *reg = &state->regs[regno];
4923         int err;
4924
4925         /* We may have adjusted the register pointing to memory region, so we
4926          * need to try adding each of min_value and max_value to off
4927          * to make sure our theoretical access will be safe.
4928          *
4929          * The minimum value is only important with signed
4930          * comparisons where we can't assume the floor of a
4931          * value is 0.  If we are using signed variables for our
4932          * index'es we need to make sure that whatever we use
4933          * will have a set floor within our range.
4934          */
4935         if (reg->smin_value < 0 &&
4936             (reg->smin_value == S64_MIN ||
4937              (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) ||
4938               reg->smin_value + off < 0)) {
4939                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
4940                         regno);
4941                 return -EACCES;
4942         }
4943         err = __check_mem_access(env, regno, reg->smin_value + off, size,
4944                                  mem_size, zero_size_allowed);
4945         if (err) {
4946                 verbose(env, "R%d min value is outside of the allowed memory range\n",
4947                         regno);
4948                 return err;
4949         }
4950
4951         /* If we haven't set a max value then we need to bail since we can't be
4952          * sure we won't do bad things.
4953          * If reg->umax_value + off could overflow, treat that as unbounded too.
4954          */
4955         if (reg->umax_value >= BPF_MAX_VAR_OFF) {
4956                 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n",
4957                         regno);
4958                 return -EACCES;
4959         }
4960         err = __check_mem_access(env, regno, reg->umax_value + off, size,
4961                                  mem_size, zero_size_allowed);
4962         if (err) {
4963                 verbose(env, "R%d max value is outside of the allowed memory range\n",
4964                         regno);
4965                 return err;
4966         }
4967
4968         return 0;
4969 }
4970
4971 static int __check_ptr_off_reg(struct bpf_verifier_env *env,
4972                                const struct bpf_reg_state *reg, int regno,
4973                                bool fixed_off_ok)
4974 {
4975         /* Access to this pointer-typed register or passing it to a helper
4976          * is only allowed in its original, unmodified form.
4977          */
4978
4979         if (reg->off < 0) {
4980                 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n",
4981                         reg_type_str(env, reg->type), regno, reg->off);
4982                 return -EACCES;
4983         }
4984
4985         if (!fixed_off_ok && reg->off) {
4986                 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n",
4987                         reg_type_str(env, reg->type), regno, reg->off);
4988                 return -EACCES;
4989         }
4990
4991         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
4992                 char tn_buf[48];
4993
4994                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
4995                 verbose(env, "variable %s access var_off=%s disallowed\n",
4996                         reg_type_str(env, reg->type), tn_buf);
4997                 return -EACCES;
4998         }
4999
5000         return 0;
5001 }
5002
5003 int check_ptr_off_reg(struct bpf_verifier_env *env,
5004                       const struct bpf_reg_state *reg, int regno)
5005 {
5006         return __check_ptr_off_reg(env, reg, regno, false);
5007 }
5008
5009 static int map_kptr_match_type(struct bpf_verifier_env *env,
5010                                struct btf_field *kptr_field,
5011                                struct bpf_reg_state *reg, u32 regno)
5012 {
5013         const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id);
5014         int perm_flags;
5015         const char *reg_name = "";
5016
5017         if (btf_is_kernel(reg->btf)) {
5018                 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU;
5019
5020                 /* Only unreferenced case accepts untrusted pointers */
5021                 if (kptr_field->type == BPF_KPTR_UNREF)
5022                         perm_flags |= PTR_UNTRUSTED;
5023         } else {
5024                 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC;
5025         }
5026
5027         if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags))
5028                 goto bad_type;
5029
5030         /* We need to verify reg->type and reg->btf, before accessing reg->btf */
5031         reg_name = btf_type_name(reg->btf, reg->btf_id);
5032
5033         /* For ref_ptr case, release function check should ensure we get one
5034          * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the
5035          * normal store of unreferenced kptr, we must ensure var_off is zero.
5036          * Since ref_ptr cannot be accessed directly by BPF insns, checks for
5037          * reg->off and reg->ref_obj_id are not needed here.
5038          */
5039         if (__check_ptr_off_reg(env, reg, regno, true))
5040                 return -EACCES;
5041
5042         /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and
5043          * we also need to take into account the reg->off.
5044          *
5045          * We want to support cases like:
5046          *
5047          * struct foo {
5048          *         struct bar br;
5049          *         struct baz bz;
5050          * };
5051          *
5052          * struct foo *v;
5053          * v = func();        // PTR_TO_BTF_ID
5054          * val->foo = v;      // reg->off is zero, btf and btf_id match type
5055          * val->bar = &v->br; // reg->off is still zero, but we need to retry with
5056          *                    // first member type of struct after comparison fails
5057          * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked
5058          *                    // to match type
5059          *
5060          * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off
5061          * is zero. We must also ensure that btf_struct_ids_match does not walk
5062          * the struct to match type against first member of struct, i.e. reject
5063          * second case from above. Hence, when type is BPF_KPTR_REF, we set
5064          * strict mode to true for type match.
5065          */
5066         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
5067                                   kptr_field->kptr.btf, kptr_field->kptr.btf_id,
5068                                   kptr_field->type == BPF_KPTR_REF))
5069                 goto bad_type;
5070         return 0;
5071 bad_type:
5072         verbose(env, "invalid kptr access, R%d type=%s%s ", regno,
5073                 reg_type_str(env, reg->type), reg_name);
5074         verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name);
5075         if (kptr_field->type == BPF_KPTR_UNREF)
5076                 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED),
5077                         targ_name);
5078         else
5079                 verbose(env, "\n");
5080         return -EINVAL;
5081 }
5082
5083 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock()
5084  * can dereference RCU protected pointers and result is PTR_TRUSTED.
5085  */
5086 static bool in_rcu_cs(struct bpf_verifier_env *env)
5087 {
5088         return env->cur_state->active_rcu_lock ||
5089                env->cur_state->active_lock.ptr ||
5090                !env->prog->aux->sleepable;
5091 }
5092
5093 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */
5094 BTF_SET_START(rcu_protected_types)
5095 BTF_ID(struct, prog_test_ref_kfunc)
5096 BTF_ID(struct, cgroup)
5097 BTF_ID(struct, bpf_cpumask)
5098 BTF_ID(struct, task_struct)
5099 BTF_SET_END(rcu_protected_types)
5100
5101 static bool rcu_protected_object(const struct btf *btf, u32 btf_id)
5102 {
5103         if (!btf_is_kernel(btf))
5104                 return false;
5105         return btf_id_set_contains(&rcu_protected_types, btf_id);
5106 }
5107
5108 static bool rcu_safe_kptr(const struct btf_field *field)
5109 {
5110         const struct btf_field_kptr *kptr = &field->kptr;
5111
5112         return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id);
5113 }
5114
5115 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno,
5116                                  int value_regno, int insn_idx,
5117                                  struct btf_field *kptr_field)
5118 {
5119         struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
5120         int class = BPF_CLASS(insn->code);
5121         struct bpf_reg_state *val_reg;
5122
5123         /* Things we already checked for in check_map_access and caller:
5124          *  - Reject cases where variable offset may touch kptr
5125          *  - size of access (must be BPF_DW)
5126          *  - tnum_is_const(reg->var_off)
5127          *  - kptr_field->offset == off + reg->var_off.value
5128          */
5129         /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */
5130         if (BPF_MODE(insn->code) != BPF_MEM) {
5131                 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n");
5132                 return -EACCES;
5133         }
5134
5135         /* We only allow loading referenced kptr, since it will be marked as
5136          * untrusted, similar to unreferenced kptr.
5137          */
5138         if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) {
5139                 verbose(env, "store to referenced kptr disallowed\n");
5140                 return -EACCES;
5141         }
5142
5143         if (class == BPF_LDX) {
5144                 val_reg = reg_state(env, value_regno);
5145                 /* We can simply mark the value_regno receiving the pointer
5146                  * value from map as PTR_TO_BTF_ID, with the correct type.
5147                  */
5148                 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf,
5149                                 kptr_field->kptr.btf_id,
5150                                 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ?
5151                                 PTR_MAYBE_NULL | MEM_RCU :
5152                                 PTR_MAYBE_NULL | PTR_UNTRUSTED);
5153                 /* For mark_ptr_or_null_reg */
5154                 val_reg->id = ++env->id_gen;
5155         } else if (class == BPF_STX) {
5156                 val_reg = reg_state(env, value_regno);
5157                 if (!register_is_null(val_reg) &&
5158                     map_kptr_match_type(env, kptr_field, val_reg, value_regno))
5159                         return -EACCES;
5160         } else if (class == BPF_ST) {
5161                 if (insn->imm) {
5162                         verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n",
5163                                 kptr_field->offset);
5164                         return -EACCES;
5165                 }
5166         } else {
5167                 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n");
5168                 return -EACCES;
5169         }
5170         return 0;
5171 }
5172
5173 /* check read/write into a map element with possible variable offset */
5174 static int check_map_access(struct bpf_verifier_env *env, u32 regno,
5175                             int off, int size, bool zero_size_allowed,
5176                             enum bpf_access_src src)
5177 {
5178         struct bpf_verifier_state *vstate = env->cur_state;
5179         struct bpf_func_state *state = vstate->frame[vstate->curframe];
5180         struct bpf_reg_state *reg = &state->regs[regno];
5181         struct bpf_map *map = reg->map_ptr;
5182         struct btf_record *rec;
5183         int err, i;
5184
5185         err = check_mem_region_access(env, regno, off, size, map->value_size,
5186                                       zero_size_allowed);
5187         if (err)
5188                 return err;
5189
5190         if (IS_ERR_OR_NULL(map->record))
5191                 return 0;
5192         rec = map->record;
5193         for (i = 0; i < rec->cnt; i++) {
5194                 struct btf_field *field = &rec->fields[i];
5195                 u32 p = field->offset;
5196
5197                 /* If any part of a field  can be touched by load/store, reject
5198                  * this program. To check that [x1, x2) overlaps with [y1, y2),
5199                  * it is sufficient to check x1 < y2 && y1 < x2.
5200                  */
5201                 if (reg->smin_value + off < p + btf_field_type_size(field->type) &&
5202                     p < reg->umax_value + off + size) {
5203                         switch (field->type) {
5204                         case BPF_KPTR_UNREF:
5205                         case BPF_KPTR_REF:
5206                                 if (src != ACCESS_DIRECT) {
5207                                         verbose(env, "kptr cannot be accessed indirectly by helper\n");
5208                                         return -EACCES;
5209                                 }
5210                                 if (!tnum_is_const(reg->var_off)) {
5211                                         verbose(env, "kptr access cannot have variable offset\n");
5212                                         return -EACCES;
5213                                 }
5214                                 if (p != off + reg->var_off.value) {
5215                                         verbose(env, "kptr access misaligned expected=%u off=%llu\n",
5216                                                 p, off + reg->var_off.value);
5217                                         return -EACCES;
5218                                 }
5219                                 if (size != bpf_size_to_bytes(BPF_DW)) {
5220                                         verbose(env, "kptr access size must be BPF_DW\n");
5221                                         return -EACCES;
5222                                 }
5223                                 break;
5224                         default:
5225                                 verbose(env, "%s cannot be accessed directly by load/store\n",
5226                                         btf_field_type_name(field->type));
5227                                 return -EACCES;
5228                         }
5229                 }
5230         }
5231         return 0;
5232 }
5233
5234 #define MAX_PACKET_OFF 0xffff
5235
5236 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env,
5237                                        const struct bpf_call_arg_meta *meta,
5238                                        enum bpf_access_type t)
5239 {
5240         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
5241
5242         switch (prog_type) {
5243         /* Program types only with direct read access go here! */
5244         case BPF_PROG_TYPE_LWT_IN:
5245         case BPF_PROG_TYPE_LWT_OUT:
5246         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
5247         case BPF_PROG_TYPE_SK_REUSEPORT:
5248         case BPF_PROG_TYPE_FLOW_DISSECTOR:
5249         case BPF_PROG_TYPE_CGROUP_SKB:
5250                 if (t == BPF_WRITE)
5251                         return false;
5252                 fallthrough;
5253
5254         /* Program types with direct read + write access go here! */
5255         case BPF_PROG_TYPE_SCHED_CLS:
5256         case BPF_PROG_TYPE_SCHED_ACT:
5257         case BPF_PROG_TYPE_XDP:
5258         case BPF_PROG_TYPE_LWT_XMIT:
5259         case BPF_PROG_TYPE_SK_SKB:
5260         case BPF_PROG_TYPE_SK_MSG:
5261                 if (meta)
5262                         return meta->pkt_access;
5263
5264                 env->seen_direct_write = true;
5265                 return true;
5266
5267         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
5268                 if (t == BPF_WRITE)
5269                         env->seen_direct_write = true;
5270
5271                 return true;
5272
5273         default:
5274                 return false;
5275         }
5276 }
5277
5278 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off,
5279                                int size, bool zero_size_allowed)
5280 {
5281         struct bpf_reg_state *regs = cur_regs(env);
5282         struct bpf_reg_state *reg = &regs[regno];
5283         int err;
5284
5285         /* We may have added a variable offset to the packet pointer; but any
5286          * reg->range we have comes after that.  We are only checking the fixed
5287          * offset.
5288          */
5289
5290         /* We don't allow negative numbers, because we aren't tracking enough
5291          * detail to prove they're safe.
5292          */
5293         if (reg->smin_value < 0) {
5294                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5295                         regno);
5296                 return -EACCES;
5297         }
5298
5299         err = reg->range < 0 ? -EINVAL :
5300               __check_mem_access(env, regno, off, size, reg->range,
5301                                  zero_size_allowed);
5302         if (err) {
5303                 verbose(env, "R%d offset is outside of the packet\n", regno);
5304                 return err;
5305         }
5306
5307         /* __check_mem_access has made sure "off + size - 1" is within u16.
5308          * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff,
5309          * otherwise find_good_pkt_pointers would have refused to set range info
5310          * that __check_mem_access would have rejected this pkt access.
5311          * Therefore, "off + reg->umax_value + size - 1" won't overflow u32.
5312          */
5313         env->prog->aux->max_pkt_offset =
5314                 max_t(u32, env->prog->aux->max_pkt_offset,
5315                       off + reg->umax_value + size - 1);
5316
5317         return err;
5318 }
5319
5320 /* check access to 'struct bpf_context' fields.  Supports fixed offsets only */
5321 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size,
5322                             enum bpf_access_type t, enum bpf_reg_type *reg_type,
5323                             struct btf **btf, u32 *btf_id)
5324 {
5325         struct bpf_insn_access_aux info = {
5326                 .reg_type = *reg_type,
5327                 .log = &env->log,
5328         };
5329
5330         if (env->ops->is_valid_access &&
5331             env->ops->is_valid_access(off, size, t, env->prog, &info)) {
5332                 /* A non zero info.ctx_field_size indicates that this field is a
5333                  * candidate for later verifier transformation to load the whole
5334                  * field and then apply a mask when accessed with a narrower
5335                  * access than actual ctx access size. A zero info.ctx_field_size
5336                  * will only allow for whole field access and rejects any other
5337                  * type of narrower access.
5338                  */
5339                 *reg_type = info.reg_type;
5340
5341                 if (base_type(*reg_type) == PTR_TO_BTF_ID) {
5342                         *btf = info.btf;
5343                         *btf_id = info.btf_id;
5344                 } else {
5345                         env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size;
5346                 }
5347                 /* remember the offset of last byte accessed in ctx */
5348                 if (env->prog->aux->max_ctx_offset < off + size)
5349                         env->prog->aux->max_ctx_offset = off + size;
5350                 return 0;
5351         }
5352
5353         verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size);
5354         return -EACCES;
5355 }
5356
5357 static int check_flow_keys_access(struct bpf_verifier_env *env, int off,
5358                                   int size)
5359 {
5360         if (size < 0 || off < 0 ||
5361             (u64)off + size > sizeof(struct bpf_flow_keys)) {
5362                 verbose(env, "invalid access to flow keys off=%d size=%d\n",
5363                         off, size);
5364                 return -EACCES;
5365         }
5366         return 0;
5367 }
5368
5369 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx,
5370                              u32 regno, int off, int size,
5371                              enum bpf_access_type t)
5372 {
5373         struct bpf_reg_state *regs = cur_regs(env);
5374         struct bpf_reg_state *reg = &regs[regno];
5375         struct bpf_insn_access_aux info = {};
5376         bool valid;
5377
5378         if (reg->smin_value < 0) {
5379                 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n",
5380                         regno);
5381                 return -EACCES;
5382         }
5383
5384         switch (reg->type) {
5385         case PTR_TO_SOCK_COMMON:
5386                 valid = bpf_sock_common_is_valid_access(off, size, t, &info);
5387                 break;
5388         case PTR_TO_SOCKET:
5389                 valid = bpf_sock_is_valid_access(off, size, t, &info);
5390                 break;
5391         case PTR_TO_TCP_SOCK:
5392                 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info);
5393                 break;
5394         case PTR_TO_XDP_SOCK:
5395                 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info);
5396                 break;
5397         default:
5398                 valid = false;
5399         }
5400
5401
5402         if (valid) {
5403                 env->insn_aux_data[insn_idx].ctx_field_size =
5404                         info.ctx_field_size;
5405                 return 0;
5406         }
5407
5408         verbose(env, "R%d invalid %s access off=%d size=%d\n",
5409                 regno, reg_type_str(env, reg->type), off, size);
5410
5411         return -EACCES;
5412 }
5413
5414 static bool is_pointer_value(struct bpf_verifier_env *env, int regno)
5415 {
5416         return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno));
5417 }
5418
5419 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno)
5420 {
5421         const struct bpf_reg_state *reg = reg_state(env, regno);
5422
5423         return reg->type == PTR_TO_CTX;
5424 }
5425
5426 static bool is_sk_reg(struct bpf_verifier_env *env, int regno)
5427 {
5428         const struct bpf_reg_state *reg = reg_state(env, regno);
5429
5430         return type_is_sk_pointer(reg->type);
5431 }
5432
5433 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno)
5434 {
5435         const struct bpf_reg_state *reg = reg_state(env, regno);
5436
5437         return type_is_pkt_pointer(reg->type);
5438 }
5439
5440 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno)
5441 {
5442         const struct bpf_reg_state *reg = reg_state(env, regno);
5443
5444         /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */
5445         return reg->type == PTR_TO_FLOW_KEYS;
5446 }
5447
5448 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = {
5449 #ifdef CONFIG_NET
5450         [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK],
5451         [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
5452         [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP],
5453 #endif
5454         [CONST_PTR_TO_MAP] = btf_bpf_map_id,
5455 };
5456
5457 static bool is_trusted_reg(const struct bpf_reg_state *reg)
5458 {
5459         /* A referenced register is always trusted. */
5460         if (reg->ref_obj_id)
5461                 return true;
5462
5463         /* Types listed in the reg2btf_ids are always trusted */
5464         if (reg2btf_ids[base_type(reg->type)])
5465                 return true;
5466
5467         /* If a register is not referenced, it is trusted if it has the
5468          * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the
5469          * other type modifiers may be safe, but we elect to take an opt-in
5470          * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are
5471          * not.
5472          *
5473          * Eventually, we should make PTR_TRUSTED the single source of truth
5474          * for whether a register is trusted.
5475          */
5476         return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS &&
5477                !bpf_type_has_unsafe_modifiers(reg->type);
5478 }
5479
5480 static bool is_rcu_reg(const struct bpf_reg_state *reg)
5481 {
5482         return reg->type & MEM_RCU;
5483 }
5484
5485 static void clear_trusted_flags(enum bpf_type_flag *flag)
5486 {
5487         *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU);
5488 }
5489
5490 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env,
5491                                    const struct bpf_reg_state *reg,
5492                                    int off, int size, bool strict)
5493 {
5494         struct tnum reg_off;
5495         int ip_align;
5496
5497         /* Byte size accesses are always allowed. */
5498         if (!strict || size == 1)
5499                 return 0;
5500
5501         /* For platforms that do not have a Kconfig enabling
5502          * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of
5503          * NET_IP_ALIGN is universally set to '2'.  And on platforms
5504          * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get
5505          * to this code only in strict mode where we want to emulate
5506          * the NET_IP_ALIGN==2 checking.  Therefore use an
5507          * unconditional IP align value of '2'.
5508          */
5509         ip_align = 2;
5510
5511         reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off));
5512         if (!tnum_is_aligned(reg_off, size)) {
5513                 char tn_buf[48];
5514
5515                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5516                 verbose(env,
5517                         "misaligned packet access off %d+%s+%d+%d size %d\n",
5518                         ip_align, tn_buf, reg->off, off, size);
5519                 return -EACCES;
5520         }
5521
5522         return 0;
5523 }
5524
5525 static int check_generic_ptr_alignment(struct bpf_verifier_env *env,
5526                                        const struct bpf_reg_state *reg,
5527                                        const char *pointer_desc,
5528                                        int off, int size, bool strict)
5529 {
5530         struct tnum reg_off;
5531
5532         /* Byte size accesses are always allowed. */
5533         if (!strict || size == 1)
5534                 return 0;
5535
5536         reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off));
5537         if (!tnum_is_aligned(reg_off, size)) {
5538                 char tn_buf[48];
5539
5540                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5541                 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n",
5542                         pointer_desc, tn_buf, reg->off, off, size);
5543                 return -EACCES;
5544         }
5545
5546         return 0;
5547 }
5548
5549 static int check_ptr_alignment(struct bpf_verifier_env *env,
5550                                const struct bpf_reg_state *reg, int off,
5551                                int size, bool strict_alignment_once)
5552 {
5553         bool strict = env->strict_alignment || strict_alignment_once;
5554         const char *pointer_desc = "";
5555
5556         switch (reg->type) {
5557         case PTR_TO_PACKET:
5558         case PTR_TO_PACKET_META:
5559                 /* Special case, because of NET_IP_ALIGN. Given metadata sits
5560                  * right in front, treat it the very same way.
5561                  */
5562                 return check_pkt_ptr_alignment(env, reg, off, size, strict);
5563         case PTR_TO_FLOW_KEYS:
5564                 pointer_desc = "flow keys ";
5565                 break;
5566         case PTR_TO_MAP_KEY:
5567                 pointer_desc = "key ";
5568                 break;
5569         case PTR_TO_MAP_VALUE:
5570                 pointer_desc = "value ";
5571                 break;
5572         case PTR_TO_CTX:
5573                 pointer_desc = "context ";
5574                 break;
5575         case PTR_TO_STACK:
5576                 pointer_desc = "stack ";
5577                 /* The stack spill tracking logic in check_stack_write_fixed_off()
5578                  * and check_stack_read_fixed_off() relies on stack accesses being
5579                  * aligned.
5580                  */
5581                 strict = true;
5582                 break;
5583         case PTR_TO_SOCKET:
5584                 pointer_desc = "sock ";
5585                 break;
5586         case PTR_TO_SOCK_COMMON:
5587                 pointer_desc = "sock_common ";
5588                 break;
5589         case PTR_TO_TCP_SOCK:
5590                 pointer_desc = "tcp_sock ";
5591                 break;
5592         case PTR_TO_XDP_SOCK:
5593                 pointer_desc = "xdp_sock ";
5594                 break;
5595         default:
5596                 break;
5597         }
5598         return check_generic_ptr_alignment(env, reg, pointer_desc, off, size,
5599                                            strict);
5600 }
5601
5602 static int update_stack_depth(struct bpf_verifier_env *env,
5603                               const struct bpf_func_state *func,
5604                               int off)
5605 {
5606         u16 stack = env->subprog_info[func->subprogno].stack_depth;
5607
5608         if (stack >= -off)
5609                 return 0;
5610
5611         /* update known max for given subprogram */
5612         env->subprog_info[func->subprogno].stack_depth = -off;
5613         return 0;
5614 }
5615
5616 /* starting from main bpf function walk all instructions of the function
5617  * and recursively walk all callees that given function can call.
5618  * Ignore jump and exit insns.
5619  * Since recursion is prevented by check_cfg() this algorithm
5620  * only needs a local stack of MAX_CALL_FRAMES to remember callsites
5621  */
5622 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx)
5623 {
5624         struct bpf_subprog_info *subprog = env->subprog_info;
5625         struct bpf_insn *insn = env->prog->insnsi;
5626         int depth = 0, frame = 0, i, subprog_end;
5627         bool tail_call_reachable = false;
5628         int ret_insn[MAX_CALL_FRAMES];
5629         int ret_prog[MAX_CALL_FRAMES];
5630         int j;
5631
5632         i = subprog[idx].start;
5633 process_func:
5634         /* protect against potential stack overflow that might happen when
5635          * bpf2bpf calls get combined with tailcalls. Limit the caller's stack
5636          * depth for such case down to 256 so that the worst case scenario
5637          * would result in 8k stack size (32 which is tailcall limit * 256 =
5638          * 8k).
5639          *
5640          * To get the idea what might happen, see an example:
5641          * func1 -> sub rsp, 128
5642          *  subfunc1 -> sub rsp, 256
5643          *  tailcall1 -> add rsp, 256
5644          *   func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320)
5645          *   subfunc2 -> sub rsp, 64
5646          *   subfunc22 -> sub rsp, 128
5647          *   tailcall2 -> add rsp, 128
5648          *    func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416)
5649          *
5650          * tailcall will unwind the current stack frame but it will not get rid
5651          * of caller's stack as shown on the example above.
5652          */
5653         if (idx && subprog[idx].has_tail_call && depth >= 256) {
5654                 verbose(env,
5655                         "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
5656                         depth);
5657                 return -EACCES;
5658         }
5659         /* round up to 32-bytes, since this is granularity
5660          * of interpreter stack size
5661          */
5662         depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5663         if (depth > MAX_BPF_STACK) {
5664                 verbose(env, "combined stack size of %d calls is %d. Too large\n",
5665                         frame + 1, depth);
5666                 return -EACCES;
5667         }
5668 continue_func:
5669         subprog_end = subprog[idx + 1].start;
5670         for (; i < subprog_end; i++) {
5671                 int next_insn, sidx;
5672
5673                 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i))
5674                         continue;
5675                 /* remember insn and function to return to */
5676                 ret_insn[frame] = i + 1;
5677                 ret_prog[frame] = idx;
5678
5679                 /* find the callee */
5680                 next_insn = i + insn[i].imm + 1;
5681                 sidx = find_subprog(env, next_insn);
5682                 if (sidx < 0) {
5683                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5684                                   next_insn);
5685                         return -EFAULT;
5686                 }
5687                 if (subprog[sidx].is_async_cb) {
5688                         if (subprog[sidx].has_tail_call) {
5689                                 verbose(env, "verifier bug. subprog has tail_call and async cb\n");
5690                                 return -EFAULT;
5691                         }
5692                         /* async callbacks don't increase bpf prog stack size unless called directly */
5693                         if (!bpf_pseudo_call(insn + i))
5694                                 continue;
5695                 }
5696                 i = next_insn;
5697                 idx = sidx;
5698
5699                 if (subprog[idx].has_tail_call)
5700                         tail_call_reachable = true;
5701
5702                 frame++;
5703                 if (frame >= MAX_CALL_FRAMES) {
5704                         verbose(env, "the call stack of %d frames is too deep !\n",
5705                                 frame);
5706                         return -E2BIG;
5707                 }
5708                 goto process_func;
5709         }
5710         /* if tail call got detected across bpf2bpf calls then mark each of the
5711          * currently present subprog frames as tail call reachable subprogs;
5712          * this info will be utilized by JIT so that we will be preserving the
5713          * tail call counter throughout bpf2bpf calls combined with tailcalls
5714          */
5715         if (tail_call_reachable)
5716                 for (j = 0; j < frame; j++)
5717                         subprog[ret_prog[j]].tail_call_reachable = true;
5718         if (subprog[0].tail_call_reachable)
5719                 env->prog->aux->tail_call_reachable = true;
5720
5721         /* end of for() loop means the last insn of the 'subprog'
5722          * was reached. Doesn't matter whether it was JA or EXIT
5723          */
5724         if (frame == 0)
5725                 return 0;
5726         depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32);
5727         frame--;
5728         i = ret_insn[frame];
5729         idx = ret_prog[frame];
5730         goto continue_func;
5731 }
5732
5733 static int check_max_stack_depth(struct bpf_verifier_env *env)
5734 {
5735         struct bpf_subprog_info *si = env->subprog_info;
5736         int ret;
5737
5738         for (int i = 0; i < env->subprog_cnt; i++) {
5739                 if (!i || si[i].is_async_cb) {
5740                         ret = check_max_stack_depth_subprog(env, i);
5741                         if (ret < 0)
5742                                 return ret;
5743                 }
5744                 continue;
5745         }
5746         return 0;
5747 }
5748
5749 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
5750 static int get_callee_stack_depth(struct bpf_verifier_env *env,
5751                                   const struct bpf_insn *insn, int idx)
5752 {
5753         int start = idx + insn->imm + 1, subprog;
5754
5755         subprog = find_subprog(env, start);
5756         if (subprog < 0) {
5757                 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
5758                           start);
5759                 return -EFAULT;
5760         }
5761         return env->subprog_info[subprog].stack_depth;
5762 }
5763 #endif
5764
5765 static int __check_buffer_access(struct bpf_verifier_env *env,
5766                                  const char *buf_info,
5767                                  const struct bpf_reg_state *reg,
5768                                  int regno, int off, int size)
5769 {
5770         if (off < 0) {
5771                 verbose(env,
5772                         "R%d invalid %s buffer access: off=%d, size=%d\n",
5773                         regno, buf_info, off, size);
5774                 return -EACCES;
5775         }
5776         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
5777                 char tn_buf[48];
5778
5779                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
5780                 verbose(env,
5781                         "R%d invalid variable buffer offset: off=%d, var_off=%s\n",
5782                         regno, off, tn_buf);
5783                 return -EACCES;
5784         }
5785
5786         return 0;
5787 }
5788
5789 static int check_tp_buffer_access(struct bpf_verifier_env *env,
5790                                   const struct bpf_reg_state *reg,
5791                                   int regno, int off, int size)
5792 {
5793         int err;
5794
5795         err = __check_buffer_access(env, "tracepoint", reg, regno, off, size);
5796         if (err)
5797                 return err;
5798
5799         if (off + size > env->prog->aux->max_tp_access)
5800                 env->prog->aux->max_tp_access = off + size;
5801
5802         return 0;
5803 }
5804
5805 static int check_buffer_access(struct bpf_verifier_env *env,
5806                                const struct bpf_reg_state *reg,
5807                                int regno, int off, int size,
5808                                bool zero_size_allowed,
5809                                u32 *max_access)
5810 {
5811         const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr";
5812         int err;
5813
5814         err = __check_buffer_access(env, buf_info, reg, regno, off, size);
5815         if (err)
5816                 return err;
5817
5818         if (off + size > *max_access)
5819                 *max_access = off + size;
5820
5821         return 0;
5822 }
5823
5824 /* BPF architecture zero extends alu32 ops into 64-bit registesr */
5825 static void zext_32_to_64(struct bpf_reg_state *reg)
5826 {
5827         reg->var_off = tnum_subreg(reg->var_off);
5828         __reg_assign_32_into_64(reg);
5829 }
5830
5831 /* truncate register to smaller size (in bytes)
5832  * must be called with size < BPF_REG_SIZE
5833  */
5834 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size)
5835 {
5836         u64 mask;
5837
5838         /* clear high bits in bit representation */
5839         reg->var_off = tnum_cast(reg->var_off, size);
5840
5841         /* fix arithmetic bounds */
5842         mask = ((u64)1 << (size * 8)) - 1;
5843         if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) {
5844                 reg->umin_value &= mask;
5845                 reg->umax_value &= mask;
5846         } else {
5847                 reg->umin_value = 0;
5848                 reg->umax_value = mask;
5849         }
5850         reg->smin_value = reg->umin_value;
5851         reg->smax_value = reg->umax_value;
5852
5853         /* If size is smaller than 32bit register the 32bit register
5854          * values are also truncated so we push 64-bit bounds into
5855          * 32-bit bounds. Above were truncated < 32-bits already.
5856          */
5857         if (size >= 4)
5858                 return;
5859         __reg_combine_64_into_32(reg);
5860 }
5861
5862 static void set_sext64_default_val(struct bpf_reg_state *reg, int size)
5863 {
5864         if (size == 1) {
5865                 reg->smin_value = reg->s32_min_value = S8_MIN;
5866                 reg->smax_value = reg->s32_max_value = S8_MAX;
5867         } else if (size == 2) {
5868                 reg->smin_value = reg->s32_min_value = S16_MIN;
5869                 reg->smax_value = reg->s32_max_value = S16_MAX;
5870         } else {
5871                 /* size == 4 */
5872                 reg->smin_value = reg->s32_min_value = S32_MIN;
5873                 reg->smax_value = reg->s32_max_value = S32_MAX;
5874         }
5875         reg->umin_value = reg->u32_min_value = 0;
5876         reg->umax_value = U64_MAX;
5877         reg->u32_max_value = U32_MAX;
5878         reg->var_off = tnum_unknown;
5879 }
5880
5881 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size)
5882 {
5883         s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval;
5884         u64 top_smax_value, top_smin_value;
5885         u64 num_bits = size * 8;
5886
5887         if (tnum_is_const(reg->var_off)) {
5888                 u64_cval = reg->var_off.value;
5889                 if (size == 1)
5890                         reg->var_off = tnum_const((s8)u64_cval);
5891                 else if (size == 2)
5892                         reg->var_off = tnum_const((s16)u64_cval);
5893                 else
5894                         /* size == 4 */
5895                         reg->var_off = tnum_const((s32)u64_cval);
5896
5897                 u64_cval = reg->var_off.value;
5898                 reg->smax_value = reg->smin_value = u64_cval;
5899                 reg->umax_value = reg->umin_value = u64_cval;
5900                 reg->s32_max_value = reg->s32_min_value = u64_cval;
5901                 reg->u32_max_value = reg->u32_min_value = u64_cval;
5902                 return;
5903         }
5904
5905         top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits;
5906         top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits;
5907
5908         if (top_smax_value != top_smin_value)
5909                 goto out;
5910
5911         /* find the s64_min and s64_min after sign extension */
5912         if (size == 1) {
5913                 init_s64_max = (s8)reg->smax_value;
5914                 init_s64_min = (s8)reg->smin_value;
5915         } else if (size == 2) {
5916                 init_s64_max = (s16)reg->smax_value;
5917                 init_s64_min = (s16)reg->smin_value;
5918         } else {
5919                 init_s64_max = (s32)reg->smax_value;
5920                 init_s64_min = (s32)reg->smin_value;
5921         }
5922
5923         s64_max = max(init_s64_max, init_s64_min);
5924         s64_min = min(init_s64_max, init_s64_min);
5925
5926         /* both of s64_max/s64_min positive or negative */
5927         if ((s64_max >= 0) == (s64_min >= 0)) {
5928                 reg->smin_value = reg->s32_min_value = s64_min;
5929                 reg->smax_value = reg->s32_max_value = s64_max;
5930                 reg->umin_value = reg->u32_min_value = s64_min;
5931                 reg->umax_value = reg->u32_max_value = s64_max;
5932                 reg->var_off = tnum_range(s64_min, s64_max);
5933                 return;
5934         }
5935
5936 out:
5937         set_sext64_default_val(reg, size);
5938 }
5939
5940 static void set_sext32_default_val(struct bpf_reg_state *reg, int size)
5941 {
5942         if (size == 1) {
5943                 reg->s32_min_value = S8_MIN;
5944                 reg->s32_max_value = S8_MAX;
5945         } else {
5946                 /* size == 2 */
5947                 reg->s32_min_value = S16_MIN;
5948                 reg->s32_max_value = S16_MAX;
5949         }
5950         reg->u32_min_value = 0;
5951         reg->u32_max_value = U32_MAX;
5952 }
5953
5954 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size)
5955 {
5956         s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val;
5957         u32 top_smax_value, top_smin_value;
5958         u32 num_bits = size * 8;
5959
5960         if (tnum_is_const(reg->var_off)) {
5961                 u32_val = reg->var_off.value;
5962                 if (size == 1)
5963                         reg->var_off = tnum_const((s8)u32_val);
5964                 else
5965                         reg->var_off = tnum_const((s16)u32_val);
5966
5967                 u32_val = reg->var_off.value;
5968                 reg->s32_min_value = reg->s32_max_value = u32_val;
5969                 reg->u32_min_value = reg->u32_max_value = u32_val;
5970                 return;
5971         }
5972
5973         top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits;
5974         top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits;
5975
5976         if (top_smax_value != top_smin_value)
5977                 goto out;
5978
5979         /* find the s32_min and s32_min after sign extension */
5980         if (size == 1) {
5981                 init_s32_max = (s8)reg->s32_max_value;
5982                 init_s32_min = (s8)reg->s32_min_value;
5983         } else {
5984                 /* size == 2 */
5985                 init_s32_max = (s16)reg->s32_max_value;
5986                 init_s32_min = (s16)reg->s32_min_value;
5987         }
5988         s32_max = max(init_s32_max, init_s32_min);
5989         s32_min = min(init_s32_max, init_s32_min);
5990
5991         if ((s32_min >= 0) == (s32_max >= 0)) {
5992                 reg->s32_min_value = s32_min;
5993                 reg->s32_max_value = s32_max;
5994                 reg->u32_min_value = (u32)s32_min;
5995                 reg->u32_max_value = (u32)s32_max;
5996                 return;
5997         }
5998
5999 out:
6000         set_sext32_default_val(reg, size);
6001 }
6002
6003 static bool bpf_map_is_rdonly(const struct bpf_map *map)
6004 {
6005         /* A map is considered read-only if the following condition are true:
6006          *
6007          * 1) BPF program side cannot change any of the map content. The
6008          *    BPF_F_RDONLY_PROG flag is throughout the lifetime of a map
6009          *    and was set at map creation time.
6010          * 2) The map value(s) have been initialized from user space by a
6011          *    loader and then "frozen", such that no new map update/delete
6012          *    operations from syscall side are possible for the rest of
6013          *    the map's lifetime from that point onwards.
6014          * 3) Any parallel/pending map update/delete operations from syscall
6015          *    side have been completed. Only after that point, it's safe to
6016          *    assume that map value(s) are immutable.
6017          */
6018         return (map->map_flags & BPF_F_RDONLY_PROG) &&
6019                READ_ONCE(map->frozen) &&
6020                !bpf_map_write_active(map);
6021 }
6022
6023 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val,
6024                                bool is_ldsx)
6025 {
6026         void *ptr;
6027         u64 addr;
6028         int err;
6029
6030         err = map->ops->map_direct_value_addr(map, &addr, off);
6031         if (err)
6032                 return err;
6033         ptr = (void *)(long)addr + off;
6034
6035         switch (size) {
6036         case sizeof(u8):
6037                 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr;
6038                 break;
6039         case sizeof(u16):
6040                 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr;
6041                 break;
6042         case sizeof(u32):
6043                 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr;
6044                 break;
6045         case sizeof(u64):
6046                 *val = *(u64 *)ptr;
6047                 break;
6048         default:
6049                 return -EINVAL;
6050         }
6051         return 0;
6052 }
6053
6054 #define BTF_TYPE_SAFE_RCU(__type)  __PASTE(__type, __safe_rcu)
6055 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type)  __PASTE(__type, __safe_rcu_or_null)
6056 #define BTF_TYPE_SAFE_TRUSTED(__type)  __PASTE(__type, __safe_trusted)
6057
6058 /*
6059  * Allow list few fields as RCU trusted or full trusted.
6060  * This logic doesn't allow mix tagging and will be removed once GCC supports
6061  * btf_type_tag.
6062  */
6063
6064 /* RCU trusted: these fields are trusted in RCU CS and never NULL */
6065 BTF_TYPE_SAFE_RCU(struct task_struct) {
6066         const cpumask_t *cpus_ptr;
6067         struct css_set __rcu *cgroups;
6068         struct task_struct __rcu *real_parent;
6069         struct task_struct *group_leader;
6070 };
6071
6072 BTF_TYPE_SAFE_RCU(struct cgroup) {
6073         /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */
6074         struct kernfs_node *kn;
6075 };
6076
6077 BTF_TYPE_SAFE_RCU(struct css_set) {
6078         struct cgroup *dfl_cgrp;
6079 };
6080
6081 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */
6082 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) {
6083         struct file __rcu *exe_file;
6084 };
6085
6086 /* skb->sk, req->sk are not RCU protected, but we mark them as such
6087  * because bpf prog accessible sockets are SOCK_RCU_FREE.
6088  */
6089 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) {
6090         struct sock *sk;
6091 };
6092
6093 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) {
6094         struct sock *sk;
6095 };
6096
6097 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */
6098 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) {
6099         struct seq_file *seq;
6100 };
6101
6102 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) {
6103         struct bpf_iter_meta *meta;
6104         struct task_struct *task;
6105 };
6106
6107 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) {
6108         struct file *file;
6109 };
6110
6111 BTF_TYPE_SAFE_TRUSTED(struct file) {
6112         struct inode *f_inode;
6113 };
6114
6115 BTF_TYPE_SAFE_TRUSTED(struct dentry) {
6116         /* no negative dentry-s in places where bpf can see it */
6117         struct inode *d_inode;
6118 };
6119
6120 BTF_TYPE_SAFE_TRUSTED(struct socket) {
6121         struct sock *sk;
6122 };
6123
6124 static bool type_is_rcu(struct bpf_verifier_env *env,
6125                         struct bpf_reg_state *reg,
6126                         const char *field_name, u32 btf_id)
6127 {
6128         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct));
6129         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup));
6130         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set));
6131
6132         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu");
6133 }
6134
6135 static bool type_is_rcu_or_null(struct bpf_verifier_env *env,
6136                                 struct bpf_reg_state *reg,
6137                                 const char *field_name, u32 btf_id)
6138 {
6139         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct));
6140         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff));
6141         BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock));
6142
6143         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null");
6144 }
6145
6146 static bool type_is_trusted(struct bpf_verifier_env *env,
6147                             struct bpf_reg_state *reg,
6148                             const char *field_name, u32 btf_id)
6149 {
6150         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta));
6151         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
6152         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
6153         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
6154         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry));
6155         BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
6156
6157         return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
6158 }
6159
6160 static int check_ptr_to_btf_access(struct bpf_verifier_env *env,
6161                                    struct bpf_reg_state *regs,
6162                                    int regno, int off, int size,
6163                                    enum bpf_access_type atype,
6164                                    int value_regno)
6165 {
6166         struct bpf_reg_state *reg = regs + regno;
6167         const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id);
6168         const char *tname = btf_name_by_offset(reg->btf, t->name_off);
6169         const char *field_name = NULL;
6170         enum bpf_type_flag flag = 0;
6171         u32 btf_id = 0;
6172         int ret;
6173
6174         if (!env->allow_ptr_leaks) {
6175                 verbose(env,
6176                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6177                         tname);
6178                 return -EPERM;
6179         }
6180         if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) {
6181                 verbose(env,
6182                         "Cannot access kernel 'struct %s' from non-GPL compatible program\n",
6183                         tname);
6184                 return -EINVAL;
6185         }
6186         if (off < 0) {
6187                 verbose(env,
6188                         "R%d is ptr_%s invalid negative access: off=%d\n",
6189                         regno, tname, off);
6190                 return -EACCES;
6191         }
6192         if (!tnum_is_const(reg->var_off) || reg->var_off.value) {
6193                 char tn_buf[48];
6194
6195                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6196                 verbose(env,
6197                         "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n",
6198                         regno, tname, off, tn_buf);
6199                 return -EACCES;
6200         }
6201
6202         if (reg->type & MEM_USER) {
6203                 verbose(env,
6204                         "R%d is ptr_%s access user memory: off=%d\n",
6205                         regno, tname, off);
6206                 return -EACCES;
6207         }
6208
6209         if (reg->type & MEM_PERCPU) {
6210                 verbose(env,
6211                         "R%d is ptr_%s access percpu memory: off=%d\n",
6212                         regno, tname, off);
6213                 return -EACCES;
6214         }
6215
6216         if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) {
6217                 if (!btf_is_kernel(reg->btf)) {
6218                         verbose(env, "verifier internal error: reg->btf must be kernel btf\n");
6219                         return -EFAULT;
6220                 }
6221                 ret = env->ops->btf_struct_access(&env->log, reg, off, size);
6222         } else {
6223                 /* Writes are permitted with default btf_struct_access for
6224                  * program allocated objects (which always have ref_obj_id > 0),
6225                  * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC.
6226                  */
6227                 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) {
6228                         verbose(env, "only read is supported\n");
6229                         return -EACCES;
6230                 }
6231
6232                 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) &&
6233                     !reg->ref_obj_id) {
6234                         verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n");
6235                         return -EFAULT;
6236                 }
6237
6238                 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name);
6239         }
6240
6241         if (ret < 0)
6242                 return ret;
6243
6244         if (ret != PTR_TO_BTF_ID) {
6245                 /* just mark; */
6246
6247         } else if (type_flag(reg->type) & PTR_UNTRUSTED) {
6248                 /* If this is an untrusted pointer, all pointers formed by walking it
6249                  * also inherit the untrusted flag.
6250                  */
6251                 flag = PTR_UNTRUSTED;
6252
6253         } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
6254                 /* By default any pointer obtained from walking a trusted pointer is no
6255                  * longer trusted, unless the field being accessed has explicitly been
6256                  * marked as inheriting its parent's state of trust (either full or RCU).
6257                  * For example:
6258                  * 'cgroups' pointer is untrusted if task->cgroups dereference
6259                  * happened in a sleepable program outside of bpf_rcu_read_lock()
6260                  * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU).
6261                  * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED.
6262                  *
6263                  * A regular RCU-protected pointer with __rcu tag can also be deemed
6264                  * trusted if we are in an RCU CS. Such pointer can be NULL.
6265                  */
6266                 if (type_is_trusted(env, reg, field_name, btf_id)) {
6267                         flag |= PTR_TRUSTED;
6268                 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) {
6269                         if (type_is_rcu(env, reg, field_name, btf_id)) {
6270                                 /* ignore __rcu tag and mark it MEM_RCU */
6271                                 flag |= MEM_RCU;
6272                         } else if (flag & MEM_RCU ||
6273                                    type_is_rcu_or_null(env, reg, field_name, btf_id)) {
6274                                 /* __rcu tagged pointers can be NULL */
6275                                 flag |= MEM_RCU | PTR_MAYBE_NULL;
6276
6277                                 /* We always trust them */
6278                                 if (type_is_rcu_or_null(env, reg, field_name, btf_id) &&
6279                                     flag & PTR_UNTRUSTED)
6280                                         flag &= ~PTR_UNTRUSTED;
6281                         } else if (flag & (MEM_PERCPU | MEM_USER)) {
6282                                 /* keep as-is */
6283                         } else {
6284                                 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */
6285                                 clear_trusted_flags(&flag);
6286                         }
6287                 } else {
6288                         /*
6289                          * If not in RCU CS or MEM_RCU pointer can be NULL then
6290                          * aggressively mark as untrusted otherwise such
6291                          * pointers will be plain PTR_TO_BTF_ID without flags
6292                          * and will be allowed to be passed into helpers for
6293                          * compat reasons.
6294                          */
6295                         flag = PTR_UNTRUSTED;
6296                 }
6297         } else {
6298                 /* Old compat. Deprecated */
6299                 clear_trusted_flags(&flag);
6300         }
6301
6302         if (atype == BPF_READ && value_regno >= 0)
6303                 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag);
6304
6305         return 0;
6306 }
6307
6308 static int check_ptr_to_map_access(struct bpf_verifier_env *env,
6309                                    struct bpf_reg_state *regs,
6310                                    int regno, int off, int size,
6311                                    enum bpf_access_type atype,
6312                                    int value_regno)
6313 {
6314         struct bpf_reg_state *reg = regs + regno;
6315         struct bpf_map *map = reg->map_ptr;
6316         struct bpf_reg_state map_reg;
6317         enum bpf_type_flag flag = 0;
6318         const struct btf_type *t;
6319         const char *tname;
6320         u32 btf_id;
6321         int ret;
6322
6323         if (!btf_vmlinux) {
6324                 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n");
6325                 return -ENOTSUPP;
6326         }
6327
6328         if (!map->ops->map_btf_id || !*map->ops->map_btf_id) {
6329                 verbose(env, "map_ptr access not supported for map type %d\n",
6330                         map->map_type);
6331                 return -ENOTSUPP;
6332         }
6333
6334         t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id);
6335         tname = btf_name_by_offset(btf_vmlinux, t->name_off);
6336
6337         if (!env->allow_ptr_leaks) {
6338                 verbose(env,
6339                         "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n",
6340                         tname);
6341                 return -EPERM;
6342         }
6343
6344         if (off < 0) {
6345                 verbose(env, "R%d is %s invalid negative access: off=%d\n",
6346                         regno, tname, off);
6347                 return -EACCES;
6348         }
6349
6350         if (atype != BPF_READ) {
6351                 verbose(env, "only read from %s is supported\n", tname);
6352                 return -EACCES;
6353         }
6354
6355         /* Simulate access to a PTR_TO_BTF_ID */
6356         memset(&map_reg, 0, sizeof(map_reg));
6357         mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0);
6358         ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL);
6359         if (ret < 0)
6360                 return ret;
6361
6362         if (value_regno >= 0)
6363                 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag);
6364
6365         return 0;
6366 }
6367
6368 /* Check that the stack access at the given offset is within bounds. The
6369  * maximum valid offset is -1.
6370  *
6371  * The minimum valid offset is -MAX_BPF_STACK for writes, and
6372  * -state->allocated_stack for reads.
6373  */
6374 static int check_stack_slot_within_bounds(int off,
6375                                           struct bpf_func_state *state,
6376                                           enum bpf_access_type t)
6377 {
6378         int min_valid_off;
6379
6380         if (t == BPF_WRITE)
6381                 min_valid_off = -MAX_BPF_STACK;
6382         else
6383                 min_valid_off = -state->allocated_stack;
6384
6385         if (off < min_valid_off || off > -1)
6386                 return -EACCES;
6387         return 0;
6388 }
6389
6390 /* Check that the stack access at 'regno + off' falls within the maximum stack
6391  * bounds.
6392  *
6393  * 'off' includes `regno->offset`, but not its dynamic part (if any).
6394  */
6395 static int check_stack_access_within_bounds(
6396                 struct bpf_verifier_env *env,
6397                 int regno, int off, int access_size,
6398                 enum bpf_access_src src, enum bpf_access_type type)
6399 {
6400         struct bpf_reg_state *regs = cur_regs(env);
6401         struct bpf_reg_state *reg = regs + regno;
6402         struct bpf_func_state *state = func(env, reg);
6403         int min_off, max_off;
6404         int err;
6405         char *err_extra;
6406
6407         if (src == ACCESS_HELPER)
6408                 /* We don't know if helpers are reading or writing (or both). */
6409                 err_extra = " indirect access to";
6410         else if (type == BPF_READ)
6411                 err_extra = " read from";
6412         else
6413                 err_extra = " write to";
6414
6415         if (tnum_is_const(reg->var_off)) {
6416                 min_off = reg->var_off.value + off;
6417                 if (access_size > 0)
6418                         max_off = min_off + access_size - 1;
6419                 else
6420                         max_off = min_off;
6421         } else {
6422                 if (reg->smax_value >= BPF_MAX_VAR_OFF ||
6423                     reg->smin_value <= -BPF_MAX_VAR_OFF) {
6424                         verbose(env, "invalid unbounded variable-offset%s stack R%d\n",
6425                                 err_extra, regno);
6426                         return -EACCES;
6427                 }
6428                 min_off = reg->smin_value + off;
6429                 if (access_size > 0)
6430                         max_off = reg->smax_value + off + access_size - 1;
6431                 else
6432                         max_off = min_off;
6433         }
6434
6435         err = check_stack_slot_within_bounds(min_off, state, type);
6436         if (!err)
6437                 err = check_stack_slot_within_bounds(max_off, state, type);
6438
6439         if (err) {
6440                 if (tnum_is_const(reg->var_off)) {
6441                         verbose(env, "invalid%s stack R%d off=%d size=%d\n",
6442                                 err_extra, regno, off, access_size);
6443                 } else {
6444                         char tn_buf[48];
6445
6446                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6447                         verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n",
6448                                 err_extra, regno, tn_buf, access_size);
6449                 }
6450         }
6451         return err;
6452 }
6453
6454 /* check whether memory at (regno + off) is accessible for t = (read | write)
6455  * if t==write, value_regno is a register which value is stored into memory
6456  * if t==read, value_regno is a register which will receive the value from memory
6457  * if t==write && value_regno==-1, some unknown value is stored into memory
6458  * if t==read && value_regno==-1, don't care what we read from memory
6459  */
6460 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno,
6461                             int off, int bpf_size, enum bpf_access_type t,
6462                             int value_regno, bool strict_alignment_once, bool is_ldsx)
6463 {
6464         struct bpf_reg_state *regs = cur_regs(env);
6465         struct bpf_reg_state *reg = regs + regno;
6466         struct bpf_func_state *state;
6467         int size, err = 0;
6468
6469         size = bpf_size_to_bytes(bpf_size);
6470         if (size < 0)
6471                 return size;
6472
6473         /* alignment checks will add in reg->off themselves */
6474         err = check_ptr_alignment(env, reg, off, size, strict_alignment_once);
6475         if (err)
6476                 return err;
6477
6478         /* for access checks, reg->off is just part of off */
6479         off += reg->off;
6480
6481         if (reg->type == PTR_TO_MAP_KEY) {
6482                 if (t == BPF_WRITE) {
6483                         verbose(env, "write to change key R%d not allowed\n", regno);
6484                         return -EACCES;
6485                 }
6486
6487                 err = check_mem_region_access(env, regno, off, size,
6488                                               reg->map_ptr->key_size, false);
6489                 if (err)
6490                         return err;
6491                 if (value_regno >= 0)
6492                         mark_reg_unknown(env, regs, value_regno);
6493         } else if (reg->type == PTR_TO_MAP_VALUE) {
6494                 struct btf_field *kptr_field = NULL;
6495
6496                 if (t == BPF_WRITE && value_regno >= 0 &&
6497                     is_pointer_value(env, value_regno)) {
6498                         verbose(env, "R%d leaks addr into map\n", value_regno);
6499                         return -EACCES;
6500                 }
6501                 err = check_map_access_type(env, regno, off, size, t);
6502                 if (err)
6503                         return err;
6504                 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT);
6505                 if (err)
6506                         return err;
6507                 if (tnum_is_const(reg->var_off))
6508                         kptr_field = btf_record_find(reg->map_ptr->record,
6509                                                      off + reg->var_off.value, BPF_KPTR);
6510                 if (kptr_field) {
6511                         err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field);
6512                 } else if (t == BPF_READ && value_regno >= 0) {
6513                         struct bpf_map *map = reg->map_ptr;
6514
6515                         /* if map is read-only, track its contents as scalars */
6516                         if (tnum_is_const(reg->var_off) &&
6517                             bpf_map_is_rdonly(map) &&
6518                             map->ops->map_direct_value_addr) {
6519                                 int map_off = off + reg->var_off.value;
6520                                 u64 val = 0;
6521
6522                                 err = bpf_map_direct_read(map, map_off, size,
6523                                                           &val, is_ldsx);
6524                                 if (err)
6525                                         return err;
6526
6527                                 regs[value_regno].type = SCALAR_VALUE;
6528                                 __mark_reg_known(&regs[value_regno], val);
6529                         } else {
6530                                 mark_reg_unknown(env, regs, value_regno);
6531                         }
6532                 }
6533         } else if (base_type(reg->type) == PTR_TO_MEM) {
6534                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6535
6536                 if (type_may_be_null(reg->type)) {
6537                         verbose(env, "R%d invalid mem access '%s'\n", regno,
6538                                 reg_type_str(env, reg->type));
6539                         return -EACCES;
6540                 }
6541
6542                 if (t == BPF_WRITE && rdonly_mem) {
6543                         verbose(env, "R%d cannot write into %s\n",
6544                                 regno, reg_type_str(env, reg->type));
6545                         return -EACCES;
6546                 }
6547
6548                 if (t == BPF_WRITE && value_regno >= 0 &&
6549                     is_pointer_value(env, value_regno)) {
6550                         verbose(env, "R%d leaks addr into mem\n", value_regno);
6551                         return -EACCES;
6552                 }
6553
6554                 err = check_mem_region_access(env, regno, off, size,
6555                                               reg->mem_size, false);
6556                 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem))
6557                         mark_reg_unknown(env, regs, value_regno);
6558         } else if (reg->type == PTR_TO_CTX) {
6559                 enum bpf_reg_type reg_type = SCALAR_VALUE;
6560                 struct btf *btf = NULL;
6561                 u32 btf_id = 0;
6562
6563                 if (t == BPF_WRITE && value_regno >= 0 &&
6564                     is_pointer_value(env, value_regno)) {
6565                         verbose(env, "R%d leaks addr into ctx\n", value_regno);
6566                         return -EACCES;
6567                 }
6568
6569                 err = check_ptr_off_reg(env, reg, regno);
6570                 if (err < 0)
6571                         return err;
6572
6573                 err = check_ctx_access(env, insn_idx, off, size, t, &reg_type, &btf,
6574                                        &btf_id);
6575                 if (err)
6576                         verbose_linfo(env, insn_idx, "; ");
6577                 if (!err && t == BPF_READ && value_regno >= 0) {
6578                         /* ctx access returns either a scalar, or a
6579                          * PTR_TO_PACKET[_META,_END]. In the latter
6580                          * case, we know the offset is zero.
6581                          */
6582                         if (reg_type == SCALAR_VALUE) {
6583                                 mark_reg_unknown(env, regs, value_regno);
6584                         } else {
6585                                 mark_reg_known_zero(env, regs,
6586                                                     value_regno);
6587                                 if (type_may_be_null(reg_type))
6588                                         regs[value_regno].id = ++env->id_gen;
6589                                 /* A load of ctx field could have different
6590                                  * actual load size with the one encoded in the
6591                                  * insn. When the dst is PTR, it is for sure not
6592                                  * a sub-register.
6593                                  */
6594                                 regs[value_regno].subreg_def = DEF_NOT_SUBREG;
6595                                 if (base_type(reg_type) == PTR_TO_BTF_ID) {
6596                                         regs[value_regno].btf = btf;
6597                                         regs[value_regno].btf_id = btf_id;
6598                                 }
6599                         }
6600                         regs[value_regno].type = reg_type;
6601                 }
6602
6603         } else if (reg->type == PTR_TO_STACK) {
6604                 /* Basic bounds checks. */
6605                 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t);
6606                 if (err)
6607                         return err;
6608
6609                 state = func(env, reg);
6610                 err = update_stack_depth(env, state, off);
6611                 if (err)
6612                         return err;
6613
6614                 if (t == BPF_READ)
6615                         err = check_stack_read(env, regno, off, size,
6616                                                value_regno);
6617                 else
6618                         err = check_stack_write(env, regno, off, size,
6619                                                 value_regno, insn_idx);
6620         } else if (reg_is_pkt_pointer(reg)) {
6621                 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) {
6622                         verbose(env, "cannot write into packet\n");
6623                         return -EACCES;
6624                 }
6625                 if (t == BPF_WRITE && value_regno >= 0 &&
6626                     is_pointer_value(env, value_regno)) {
6627                         verbose(env, "R%d leaks addr into packet\n",
6628                                 value_regno);
6629                         return -EACCES;
6630                 }
6631                 err = check_packet_access(env, regno, off, size, false);
6632                 if (!err && t == BPF_READ && value_regno >= 0)
6633                         mark_reg_unknown(env, regs, value_regno);
6634         } else if (reg->type == PTR_TO_FLOW_KEYS) {
6635                 if (t == BPF_WRITE && value_regno >= 0 &&
6636                     is_pointer_value(env, value_regno)) {
6637                         verbose(env, "R%d leaks addr into flow keys\n",
6638                                 value_regno);
6639                         return -EACCES;
6640                 }
6641
6642                 err = check_flow_keys_access(env, off, size);
6643                 if (!err && t == BPF_READ && value_regno >= 0)
6644                         mark_reg_unknown(env, regs, value_regno);
6645         } else if (type_is_sk_pointer(reg->type)) {
6646                 if (t == BPF_WRITE) {
6647                         verbose(env, "R%d cannot write into %s\n",
6648                                 regno, reg_type_str(env, reg->type));
6649                         return -EACCES;
6650                 }
6651                 err = check_sock_access(env, insn_idx, regno, off, size, t);
6652                 if (!err && value_regno >= 0)
6653                         mark_reg_unknown(env, regs, value_regno);
6654         } else if (reg->type == PTR_TO_TP_BUFFER) {
6655                 err = check_tp_buffer_access(env, reg, regno, off, size);
6656                 if (!err && t == BPF_READ && value_regno >= 0)
6657                         mark_reg_unknown(env, regs, value_regno);
6658         } else if (base_type(reg->type) == PTR_TO_BTF_ID &&
6659                    !type_may_be_null(reg->type)) {
6660                 err = check_ptr_to_btf_access(env, regs, regno, off, size, t,
6661                                               value_regno);
6662         } else if (reg->type == CONST_PTR_TO_MAP) {
6663                 err = check_ptr_to_map_access(env, regs, regno, off, size, t,
6664                                               value_regno);
6665         } else if (base_type(reg->type) == PTR_TO_BUF) {
6666                 bool rdonly_mem = type_is_rdonly_mem(reg->type);
6667                 u32 *max_access;
6668
6669                 if (rdonly_mem) {
6670                         if (t == BPF_WRITE) {
6671                                 verbose(env, "R%d cannot write into %s\n",
6672                                         regno, reg_type_str(env, reg->type));
6673                                 return -EACCES;
6674                         }
6675                         max_access = &env->prog->aux->max_rdonly_access;
6676                 } else {
6677                         max_access = &env->prog->aux->max_rdwr_access;
6678                 }
6679
6680                 err = check_buffer_access(env, reg, regno, off, size, false,
6681                                           max_access);
6682
6683                 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ))
6684                         mark_reg_unknown(env, regs, value_regno);
6685         } else {
6686                 verbose(env, "R%d invalid mem access '%s'\n", regno,
6687                         reg_type_str(env, reg->type));
6688                 return -EACCES;
6689         }
6690
6691         if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ &&
6692             regs[value_regno].type == SCALAR_VALUE) {
6693                 if (!is_ldsx)
6694                         /* b/h/w load zero-extends, mark upper bits as known 0 */
6695                         coerce_reg_to_size(&regs[value_regno], size);
6696                 else
6697                         coerce_reg_to_size_sx(&regs[value_regno], size);
6698         }
6699         return err;
6700 }
6701
6702 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn)
6703 {
6704         int load_reg;
6705         int err;
6706
6707         switch (insn->imm) {
6708         case BPF_ADD:
6709         case BPF_ADD | BPF_FETCH:
6710         case BPF_AND:
6711         case BPF_AND | BPF_FETCH:
6712         case BPF_OR:
6713         case BPF_OR | BPF_FETCH:
6714         case BPF_XOR:
6715         case BPF_XOR | BPF_FETCH:
6716         case BPF_XCHG:
6717         case BPF_CMPXCHG:
6718                 break;
6719         default:
6720                 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm);
6721                 return -EINVAL;
6722         }
6723
6724         if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) {
6725                 verbose(env, "invalid atomic operand size\n");
6726                 return -EINVAL;
6727         }
6728
6729         /* check src1 operand */
6730         err = check_reg_arg(env, insn->src_reg, SRC_OP);
6731         if (err)
6732                 return err;
6733
6734         /* check src2 operand */
6735         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
6736         if (err)
6737                 return err;
6738
6739         if (insn->imm == BPF_CMPXCHG) {
6740                 /* Check comparison of R0 with memory location */
6741                 const u32 aux_reg = BPF_REG_0;
6742
6743                 err = check_reg_arg(env, aux_reg, SRC_OP);
6744                 if (err)
6745                         return err;
6746
6747                 if (is_pointer_value(env, aux_reg)) {
6748                         verbose(env, "R%d leaks addr into mem\n", aux_reg);
6749                         return -EACCES;
6750                 }
6751         }
6752
6753         if (is_pointer_value(env, insn->src_reg)) {
6754                 verbose(env, "R%d leaks addr into mem\n", insn->src_reg);
6755                 return -EACCES;
6756         }
6757
6758         if (is_ctx_reg(env, insn->dst_reg) ||
6759             is_pkt_reg(env, insn->dst_reg) ||
6760             is_flow_key_reg(env, insn->dst_reg) ||
6761             is_sk_reg(env, insn->dst_reg)) {
6762                 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n",
6763                         insn->dst_reg,
6764                         reg_type_str(env, reg_state(env, insn->dst_reg)->type));
6765                 return -EACCES;
6766         }
6767
6768         if (insn->imm & BPF_FETCH) {
6769                 if (insn->imm == BPF_CMPXCHG)
6770                         load_reg = BPF_REG_0;
6771                 else
6772                         load_reg = insn->src_reg;
6773
6774                 /* check and record load of old value */
6775                 err = check_reg_arg(env, load_reg, DST_OP);
6776                 if (err)
6777                         return err;
6778         } else {
6779                 /* This instruction accesses a memory location but doesn't
6780                  * actually load it into a register.
6781                  */
6782                 load_reg = -1;
6783         }
6784
6785         /* Check whether we can read the memory, with second call for fetch
6786          * case to simulate the register fill.
6787          */
6788         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6789                                BPF_SIZE(insn->code), BPF_READ, -1, true, false);
6790         if (!err && load_reg >= 0)
6791                 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6792                                        BPF_SIZE(insn->code), BPF_READ, load_reg,
6793                                        true, false);
6794         if (err)
6795                 return err;
6796
6797         /* Check whether we can write into the same memory. */
6798         err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off,
6799                                BPF_SIZE(insn->code), BPF_WRITE, -1, true, false);
6800         if (err)
6801                 return err;
6802
6803         return 0;
6804 }
6805
6806 /* When register 'regno' is used to read the stack (either directly or through
6807  * a helper function) make sure that it's within stack boundary and, depending
6808  * on the access type, that all elements of the stack are initialized.
6809  *
6810  * 'off' includes 'regno->off', but not its dynamic part (if any).
6811  *
6812  * All registers that have been spilled on the stack in the slots within the
6813  * read offsets are marked as read.
6814  */
6815 static int check_stack_range_initialized(
6816                 struct bpf_verifier_env *env, int regno, int off,
6817                 int access_size, bool zero_size_allowed,
6818                 enum bpf_access_src type, struct bpf_call_arg_meta *meta)
6819 {
6820         struct bpf_reg_state *reg = reg_state(env, regno);
6821         struct bpf_func_state *state = func(env, reg);
6822         int err, min_off, max_off, i, j, slot, spi;
6823         char *err_extra = type == ACCESS_HELPER ? " indirect" : "";
6824         enum bpf_access_type bounds_check_type;
6825         /* Some accesses can write anything into the stack, others are
6826          * read-only.
6827          */
6828         bool clobber = false;
6829
6830         if (access_size == 0 && !zero_size_allowed) {
6831                 verbose(env, "invalid zero-sized read\n");
6832                 return -EACCES;
6833         }
6834
6835         if (type == ACCESS_HELPER) {
6836                 /* The bounds checks for writes are more permissive than for
6837                  * reads. However, if raw_mode is not set, we'll do extra
6838                  * checks below.
6839                  */
6840                 bounds_check_type = BPF_WRITE;
6841                 clobber = true;
6842         } else {
6843                 bounds_check_type = BPF_READ;
6844         }
6845         err = check_stack_access_within_bounds(env, regno, off, access_size,
6846                                                type, bounds_check_type);
6847         if (err)
6848                 return err;
6849
6850
6851         if (tnum_is_const(reg->var_off)) {
6852                 min_off = max_off = reg->var_off.value + off;
6853         } else {
6854                 /* Variable offset is prohibited for unprivileged mode for
6855                  * simplicity since it requires corresponding support in
6856                  * Spectre masking for stack ALU.
6857                  * See also retrieve_ptr_limit().
6858                  */
6859                 if (!env->bypass_spec_v1) {
6860                         char tn_buf[48];
6861
6862                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6863                         verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n",
6864                                 regno, err_extra, tn_buf);
6865                         return -EACCES;
6866                 }
6867                 /* Only initialized buffer on stack is allowed to be accessed
6868                  * with variable offset. With uninitialized buffer it's hard to
6869                  * guarantee that whole memory is marked as initialized on
6870                  * helper return since specific bounds are unknown what may
6871                  * cause uninitialized stack leaking.
6872                  */
6873                 if (meta && meta->raw_mode)
6874                         meta = NULL;
6875
6876                 min_off = reg->smin_value + off;
6877                 max_off = reg->smax_value + off;
6878         }
6879
6880         if (meta && meta->raw_mode) {
6881                 /* Ensure we won't be overwriting dynptrs when simulating byte
6882                  * by byte access in check_helper_call using meta.access_size.
6883                  * This would be a problem if we have a helper in the future
6884                  * which takes:
6885                  *
6886                  *      helper(uninit_mem, len, dynptr)
6887                  *
6888                  * Now, uninint_mem may overlap with dynptr pointer. Hence, it
6889                  * may end up writing to dynptr itself when touching memory from
6890                  * arg 1. This can be relaxed on a case by case basis for known
6891                  * safe cases, but reject due to the possibilitiy of aliasing by
6892                  * default.
6893                  */
6894                 for (i = min_off; i < max_off + access_size; i++) {
6895                         int stack_off = -i - 1;
6896
6897                         spi = __get_spi(i);
6898                         /* raw_mode may write past allocated_stack */
6899                         if (state->allocated_stack <= stack_off)
6900                                 continue;
6901                         if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) {
6902                                 verbose(env, "potential write to dynptr at off=%d disallowed\n", i);
6903                                 return -EACCES;
6904                         }
6905                 }
6906                 meta->access_size = access_size;
6907                 meta->regno = regno;
6908                 return 0;
6909         }
6910
6911         for (i = min_off; i < max_off + access_size; i++) {
6912                 u8 *stype;
6913
6914                 slot = -i - 1;
6915                 spi = slot / BPF_REG_SIZE;
6916                 if (state->allocated_stack <= slot)
6917                         goto err;
6918                 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE];
6919                 if (*stype == STACK_MISC)
6920                         goto mark;
6921                 if ((*stype == STACK_ZERO) ||
6922                     (*stype == STACK_INVALID && env->allow_uninit_stack)) {
6923                         if (clobber) {
6924                                 /* helper can write anything into the stack */
6925                                 *stype = STACK_MISC;
6926                         }
6927                         goto mark;
6928                 }
6929
6930                 if (is_spilled_reg(&state->stack[spi]) &&
6931                     (state->stack[spi].spilled_ptr.type == SCALAR_VALUE ||
6932                      env->allow_ptr_leaks)) {
6933                         if (clobber) {
6934                                 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr);
6935                                 for (j = 0; j < BPF_REG_SIZE; j++)
6936                                         scrub_spilled_slot(&state->stack[spi].slot_type[j]);
6937                         }
6938                         goto mark;
6939                 }
6940
6941 err:
6942                 if (tnum_is_const(reg->var_off)) {
6943                         verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n",
6944                                 err_extra, regno, min_off, i - min_off, access_size);
6945                 } else {
6946                         char tn_buf[48];
6947
6948                         tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
6949                         verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n",
6950                                 err_extra, regno, tn_buf, i - min_off, access_size);
6951                 }
6952                 return -EACCES;
6953 mark:
6954                 /* reading any byte out of 8-byte 'spill_slot' will cause
6955                  * the whole slot to be marked as 'read'
6956                  */
6957                 mark_reg_read(env, &state->stack[spi].spilled_ptr,
6958                               state->stack[spi].spilled_ptr.parent,
6959                               REG_LIVE_READ64);
6960                 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not
6961                  * be sure that whether stack slot is written to or not. Hence,
6962                  * we must still conservatively propagate reads upwards even if
6963                  * helper may write to the entire memory range.
6964                  */
6965         }
6966         return update_stack_depth(env, state, min_off);
6967 }
6968
6969 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno,
6970                                    int access_size, bool zero_size_allowed,
6971                                    struct bpf_call_arg_meta *meta)
6972 {
6973         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
6974         u32 *max_access;
6975
6976         switch (base_type(reg->type)) {
6977         case PTR_TO_PACKET:
6978         case PTR_TO_PACKET_META:
6979                 return check_packet_access(env, regno, reg->off, access_size,
6980                                            zero_size_allowed);
6981         case PTR_TO_MAP_KEY:
6982                 if (meta && meta->raw_mode) {
6983                         verbose(env, "R%d cannot write into %s\n", regno,
6984                                 reg_type_str(env, reg->type));
6985                         return -EACCES;
6986                 }
6987                 return check_mem_region_access(env, regno, reg->off, access_size,
6988                                                reg->map_ptr->key_size, false);
6989         case PTR_TO_MAP_VALUE:
6990                 if (check_map_access_type(env, regno, reg->off, access_size,
6991                                           meta && meta->raw_mode ? BPF_WRITE :
6992                                           BPF_READ))
6993                         return -EACCES;
6994                 return check_map_access(env, regno, reg->off, access_size,
6995                                         zero_size_allowed, ACCESS_HELPER);
6996         case PTR_TO_MEM:
6997                 if (type_is_rdonly_mem(reg->type)) {
6998                         if (meta && meta->raw_mode) {
6999                                 verbose(env, "R%d cannot write into %s\n", regno,
7000                                         reg_type_str(env, reg->type));
7001                                 return -EACCES;
7002                         }
7003                 }
7004                 return check_mem_region_access(env, regno, reg->off,
7005                                                access_size, reg->mem_size,
7006                                                zero_size_allowed);
7007         case PTR_TO_BUF:
7008                 if (type_is_rdonly_mem(reg->type)) {
7009                         if (meta && meta->raw_mode) {
7010                                 verbose(env, "R%d cannot write into %s\n", regno,
7011                                         reg_type_str(env, reg->type));
7012                                 return -EACCES;
7013                         }
7014
7015                         max_access = &env->prog->aux->max_rdonly_access;
7016                 } else {
7017                         max_access = &env->prog->aux->max_rdwr_access;
7018                 }
7019                 return check_buffer_access(env, reg, regno, reg->off,
7020                                            access_size, zero_size_allowed,
7021                                            max_access);
7022         case PTR_TO_STACK:
7023                 return check_stack_range_initialized(
7024                                 env,
7025                                 regno, reg->off, access_size,
7026                                 zero_size_allowed, ACCESS_HELPER, meta);
7027         case PTR_TO_BTF_ID:
7028                 return check_ptr_to_btf_access(env, regs, regno, reg->off,
7029                                                access_size, BPF_READ, -1);
7030         case PTR_TO_CTX:
7031                 /* in case the function doesn't know how to access the context,
7032                  * (because we are in a program of type SYSCALL for example), we
7033                  * can not statically check its size.
7034                  * Dynamically check it now.
7035                  */
7036                 if (!env->ops->convert_ctx_access) {
7037                         enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ;
7038                         int offset = access_size - 1;
7039
7040                         /* Allow zero-byte read from PTR_TO_CTX */
7041                         if (access_size == 0)
7042                                 return zero_size_allowed ? 0 : -EACCES;
7043
7044                         return check_mem_access(env, env->insn_idx, regno, offset, BPF_B,
7045                                                 atype, -1, false, false);
7046                 }
7047
7048                 fallthrough;
7049         default: /* scalar_value or invalid ptr */
7050                 /* Allow zero-byte read from NULL, regardless of pointer type */
7051                 if (zero_size_allowed && access_size == 0 &&
7052                     register_is_null(reg))
7053                         return 0;
7054
7055                 verbose(env, "R%d type=%s ", regno,
7056                         reg_type_str(env, reg->type));
7057                 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK));
7058                 return -EACCES;
7059         }
7060 }
7061
7062 static int check_mem_size_reg(struct bpf_verifier_env *env,
7063                               struct bpf_reg_state *reg, u32 regno,
7064                               bool zero_size_allowed,
7065                               struct bpf_call_arg_meta *meta)
7066 {
7067         int err;
7068
7069         /* This is used to refine r0 return value bounds for helpers
7070          * that enforce this value as an upper bound on return values.
7071          * See do_refine_retval_range() for helpers that can refine
7072          * the return value. C type of helper is u32 so we pull register
7073          * bound from umax_value however, if negative verifier errors
7074          * out. Only upper bounds can be learned because retval is an
7075          * int type and negative retvals are allowed.
7076          */
7077         meta->msize_max_value = reg->umax_value;
7078
7079         /* The register is SCALAR_VALUE; the access check
7080          * happens using its boundaries.
7081          */
7082         if (!tnum_is_const(reg->var_off))
7083                 /* For unprivileged variable accesses, disable raw
7084                  * mode so that the program is required to
7085                  * initialize all the memory that the helper could
7086                  * just partially fill up.
7087                  */
7088                 meta = NULL;
7089
7090         if (reg->smin_value < 0) {
7091                 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n",
7092                         regno);
7093                 return -EACCES;
7094         }
7095
7096         if (reg->umin_value == 0) {
7097                 err = check_helper_mem_access(env, regno - 1, 0,
7098                                               zero_size_allowed,
7099                                               meta);
7100                 if (err)
7101                         return err;
7102         }
7103
7104         if (reg->umax_value >= BPF_MAX_VAR_SIZ) {
7105                 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n",
7106                         regno);
7107                 return -EACCES;
7108         }
7109         err = check_helper_mem_access(env, regno - 1,
7110                                       reg->umax_value,
7111                                       zero_size_allowed, meta);
7112         if (!err)
7113                 err = mark_chain_precision(env, regno);
7114         return err;
7115 }
7116
7117 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7118                    u32 regno, u32 mem_size)
7119 {
7120         bool may_be_null = type_may_be_null(reg->type);
7121         struct bpf_reg_state saved_reg;
7122         struct bpf_call_arg_meta meta;
7123         int err;
7124
7125         if (register_is_null(reg))
7126                 return 0;
7127
7128         memset(&meta, 0, sizeof(meta));
7129         /* Assuming that the register contains a value check if the memory
7130          * access is safe. Temporarily save and restore the register's state as
7131          * the conversion shouldn't be visible to a caller.
7132          */
7133         if (may_be_null) {
7134                 saved_reg = *reg;
7135                 mark_ptr_not_null_reg(reg);
7136         }
7137
7138         err = check_helper_mem_access(env, regno, mem_size, true, &meta);
7139         /* Check access for BPF_WRITE */
7140         meta.raw_mode = true;
7141         err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta);
7142
7143         if (may_be_null)
7144                 *reg = saved_reg;
7145
7146         return err;
7147 }
7148
7149 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
7150                                     u32 regno)
7151 {
7152         struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1];
7153         bool may_be_null = type_may_be_null(mem_reg->type);
7154         struct bpf_reg_state saved_reg;
7155         struct bpf_call_arg_meta meta;
7156         int err;
7157
7158         WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5);
7159
7160         memset(&meta, 0, sizeof(meta));
7161
7162         if (may_be_null) {
7163                 saved_reg = *mem_reg;
7164                 mark_ptr_not_null_reg(mem_reg);
7165         }
7166
7167         err = check_mem_size_reg(env, reg, regno, true, &meta);
7168         /* Check access for BPF_WRITE */
7169         meta.raw_mode = true;
7170         err = err ?: check_mem_size_reg(env, reg, regno, true, &meta);
7171
7172         if (may_be_null)
7173                 *mem_reg = saved_reg;
7174         return err;
7175 }
7176
7177 /* Implementation details:
7178  * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL.
7179  * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL.
7180  * Two bpf_map_lookups (even with the same key) will have different reg->id.
7181  * Two separate bpf_obj_new will also have different reg->id.
7182  * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier
7183  * clears reg->id after value_or_null->value transition, since the verifier only
7184  * cares about the range of access to valid map value pointer and doesn't care
7185  * about actual address of the map element.
7186  * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps
7187  * reg->id > 0 after value_or_null->value transition. By doing so
7188  * two bpf_map_lookups will be considered two different pointers that
7189  * point to different bpf_spin_locks. Likewise for pointers to allocated objects
7190  * returned from bpf_obj_new.
7191  * The verifier allows taking only one bpf_spin_lock at a time to avoid
7192  * dead-locks.
7193  * Since only one bpf_spin_lock is allowed the checks are simpler than
7194  * reg_is_refcounted() logic. The verifier needs to remember only
7195  * one spin_lock instead of array of acquired_refs.
7196  * cur_state->active_lock remembers which map value element or allocated
7197  * object got locked and clears it after bpf_spin_unlock.
7198  */
7199 static int process_spin_lock(struct bpf_verifier_env *env, int regno,
7200                              bool is_lock)
7201 {
7202         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7203         struct bpf_verifier_state *cur = env->cur_state;
7204         bool is_const = tnum_is_const(reg->var_off);
7205         u64 val = reg->var_off.value;
7206         struct bpf_map *map = NULL;
7207         struct btf *btf = NULL;
7208         struct btf_record *rec;
7209
7210         if (!is_const) {
7211                 verbose(env,
7212                         "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n",
7213                         regno);
7214                 return -EINVAL;
7215         }
7216         if (reg->type == PTR_TO_MAP_VALUE) {
7217                 map = reg->map_ptr;
7218                 if (!map->btf) {
7219                         verbose(env,
7220                                 "map '%s' has to have BTF in order to use bpf_spin_lock\n",
7221                                 map->name);
7222                         return -EINVAL;
7223                 }
7224         } else {
7225                 btf = reg->btf;
7226         }
7227
7228         rec = reg_btf_record(reg);
7229         if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) {
7230                 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local",
7231                         map ? map->name : "kptr");
7232                 return -EINVAL;
7233         }
7234         if (rec->spin_lock_off != val + reg->off) {
7235                 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n",
7236                         val + reg->off, rec->spin_lock_off);
7237                 return -EINVAL;
7238         }
7239         if (is_lock) {
7240                 if (cur->active_lock.ptr) {
7241                         verbose(env,
7242                                 "Locking two bpf_spin_locks are not allowed\n");
7243                         return -EINVAL;
7244                 }
7245                 if (map)
7246                         cur->active_lock.ptr = map;
7247                 else
7248                         cur->active_lock.ptr = btf;
7249                 cur->active_lock.id = reg->id;
7250         } else {
7251                 void *ptr;
7252
7253                 if (map)
7254                         ptr = map;
7255                 else
7256                         ptr = btf;
7257
7258                 if (!cur->active_lock.ptr) {
7259                         verbose(env, "bpf_spin_unlock without taking a lock\n");
7260                         return -EINVAL;
7261                 }
7262                 if (cur->active_lock.ptr != ptr ||
7263                     cur->active_lock.id != reg->id) {
7264                         verbose(env, "bpf_spin_unlock of different lock\n");
7265                         return -EINVAL;
7266                 }
7267
7268                 invalidate_non_owning_refs(env);
7269
7270                 cur->active_lock.ptr = NULL;
7271                 cur->active_lock.id = 0;
7272         }
7273         return 0;
7274 }
7275
7276 static int process_timer_func(struct bpf_verifier_env *env, int regno,
7277                               struct bpf_call_arg_meta *meta)
7278 {
7279         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7280         bool is_const = tnum_is_const(reg->var_off);
7281         struct bpf_map *map = reg->map_ptr;
7282         u64 val = reg->var_off.value;
7283
7284         if (!is_const) {
7285                 verbose(env,
7286                         "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n",
7287                         regno);
7288                 return -EINVAL;
7289         }
7290         if (!map->btf) {
7291                 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n",
7292                         map->name);
7293                 return -EINVAL;
7294         }
7295         if (!btf_record_has_field(map->record, BPF_TIMER)) {
7296                 verbose(env, "map '%s' has no valid bpf_timer\n", map->name);
7297                 return -EINVAL;
7298         }
7299         if (map->record->timer_off != val + reg->off) {
7300                 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n",
7301                         val + reg->off, map->record->timer_off);
7302                 return -EINVAL;
7303         }
7304         if (meta->map_ptr) {
7305                 verbose(env, "verifier bug. Two map pointers in a timer helper\n");
7306                 return -EFAULT;
7307         }
7308         meta->map_uid = reg->map_uid;
7309         meta->map_ptr = map;
7310         return 0;
7311 }
7312
7313 static int process_kptr_func(struct bpf_verifier_env *env, int regno,
7314                              struct bpf_call_arg_meta *meta)
7315 {
7316         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7317         struct bpf_map *map_ptr = reg->map_ptr;
7318         struct btf_field *kptr_field;
7319         u32 kptr_off;
7320
7321         if (!tnum_is_const(reg->var_off)) {
7322                 verbose(env,
7323                         "R%d doesn't have constant offset. kptr has to be at the constant offset\n",
7324                         regno);
7325                 return -EINVAL;
7326         }
7327         if (!map_ptr->btf) {
7328                 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n",
7329                         map_ptr->name);
7330                 return -EINVAL;
7331         }
7332         if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) {
7333                 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name);
7334                 return -EINVAL;
7335         }
7336
7337         meta->map_ptr = map_ptr;
7338         kptr_off = reg->off + reg->var_off.value;
7339         kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR);
7340         if (!kptr_field) {
7341                 verbose(env, "off=%d doesn't point to kptr\n", kptr_off);
7342                 return -EACCES;
7343         }
7344         if (kptr_field->type != BPF_KPTR_REF) {
7345                 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off);
7346                 return -EACCES;
7347         }
7348         meta->kptr_field = kptr_field;
7349         return 0;
7350 }
7351
7352 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK
7353  * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR.
7354  *
7355  * In both cases we deal with the first 8 bytes, but need to mark the next 8
7356  * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of
7357  * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object.
7358  *
7359  * Mutability of bpf_dynptr is at two levels, one is at the level of struct
7360  * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct
7361  * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can
7362  * mutate the view of the dynptr and also possibly destroy it. In the latter
7363  * case, it cannot mutate the bpf_dynptr itself but it can still mutate the
7364  * memory that dynptr points to.
7365  *
7366  * The verifier will keep track both levels of mutation (bpf_dynptr's in
7367  * reg->type and the memory's in reg->dynptr.type), but there is no support for
7368  * readonly dynptr view yet, hence only the first case is tracked and checked.
7369  *
7370  * This is consistent with how C applies the const modifier to a struct object,
7371  * where the pointer itself inside bpf_dynptr becomes const but not what it
7372  * points to.
7373  *
7374  * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument
7375  * type, and declare it as 'const struct bpf_dynptr *' in their prototype.
7376  */
7377 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx,
7378                                enum bpf_arg_type arg_type, int clone_ref_obj_id)
7379 {
7380         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7381         int err;
7382
7383         /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an
7384          * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*):
7385          */
7386         if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) {
7387                 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n");
7388                 return -EFAULT;
7389         }
7390
7391         /*  MEM_UNINIT - Points to memory that is an appropriate candidate for
7392          *               constructing a mutable bpf_dynptr object.
7393          *
7394          *               Currently, this is only possible with PTR_TO_STACK
7395          *               pointing to a region of at least 16 bytes which doesn't
7396          *               contain an existing bpf_dynptr.
7397          *
7398          *  MEM_RDONLY - Points to a initialized bpf_dynptr that will not be
7399          *               mutated or destroyed. However, the memory it points to
7400          *               may be mutated.
7401          *
7402          *  None       - Points to a initialized dynptr that can be mutated and
7403          *               destroyed, including mutation of the memory it points
7404          *               to.
7405          */
7406         if (arg_type & MEM_UNINIT) {
7407                 int i;
7408
7409                 if (!is_dynptr_reg_valid_uninit(env, reg)) {
7410                         verbose(env, "Dynptr has to be an uninitialized dynptr\n");
7411                         return -EINVAL;
7412                 }
7413
7414                 /* we write BPF_DW bits (8 bytes) at a time */
7415                 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) {
7416                         err = check_mem_access(env, insn_idx, regno,
7417                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7418                         if (err)
7419                                 return err;
7420                 }
7421
7422                 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id);
7423         } else /* MEM_RDONLY and None case from above */ {
7424                 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */
7425                 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) {
7426                         verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n");
7427                         return -EINVAL;
7428                 }
7429
7430                 if (!is_dynptr_reg_valid_init(env, reg)) {
7431                         verbose(env,
7432                                 "Expected an initialized dynptr as arg #%d\n",
7433                                 regno);
7434                         return -EINVAL;
7435                 }
7436
7437                 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */
7438                 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) {
7439                         verbose(env,
7440                                 "Expected a dynptr of type %s as arg #%d\n",
7441                                 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno);
7442                         return -EINVAL;
7443                 }
7444
7445                 err = mark_dynptr_read(env, reg);
7446         }
7447         return err;
7448 }
7449
7450 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi)
7451 {
7452         struct bpf_func_state *state = func(env, reg);
7453
7454         return state->stack[spi].spilled_ptr.ref_obj_id;
7455 }
7456
7457 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7458 {
7459         return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7460 }
7461
7462 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7463 {
7464         return meta->kfunc_flags & KF_ITER_NEW;
7465 }
7466
7467 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7468 {
7469         return meta->kfunc_flags & KF_ITER_NEXT;
7470 }
7471
7472 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta)
7473 {
7474         return meta->kfunc_flags & KF_ITER_DESTROY;
7475 }
7476
7477 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg)
7478 {
7479         /* btf_check_iter_kfuncs() guarantees that first argument of any iter
7480          * kfunc is iter state pointer
7481          */
7482         return arg == 0 && is_iter_kfunc(meta);
7483 }
7484
7485 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx,
7486                             struct bpf_kfunc_call_arg_meta *meta)
7487 {
7488         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7489         const struct btf_type *t;
7490         const struct btf_param *arg;
7491         int spi, err, i, nr_slots;
7492         u32 btf_id;
7493
7494         /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */
7495         arg = &btf_params(meta->func_proto)[0];
7496         t = btf_type_skip_modifiers(meta->btf, arg->type, NULL);        /* PTR */
7497         t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id);       /* STRUCT */
7498         nr_slots = t->size / BPF_REG_SIZE;
7499
7500         if (is_iter_new_kfunc(meta)) {
7501                 /* bpf_iter_<type>_new() expects pointer to uninit iter state */
7502                 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) {
7503                         verbose(env, "expected uninitialized iter_%s as arg #%d\n",
7504                                 iter_type_str(meta->btf, btf_id), regno);
7505                         return -EINVAL;
7506                 }
7507
7508                 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) {
7509                         err = check_mem_access(env, insn_idx, regno,
7510                                                i, BPF_DW, BPF_WRITE, -1, false, false);
7511                         if (err)
7512                                 return err;
7513                 }
7514
7515                 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots);
7516                 if (err)
7517                         return err;
7518         } else {
7519                 /* iter_next() or iter_destroy() expect initialized iter state*/
7520                 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) {
7521                         verbose(env, "expected an initialized iter_%s as arg #%d\n",
7522                                 iter_type_str(meta->btf, btf_id), regno);
7523                         return -EINVAL;
7524                 }
7525
7526                 spi = iter_get_spi(env, reg, nr_slots);
7527                 if (spi < 0)
7528                         return spi;
7529
7530                 err = mark_iter_read(env, reg, spi, nr_slots);
7531                 if (err)
7532                         return err;
7533
7534                 /* remember meta->iter info for process_iter_next_call() */
7535                 meta->iter.spi = spi;
7536                 meta->iter.frameno = reg->frameno;
7537                 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi);
7538
7539                 if (is_iter_destroy_kfunc(meta)) {
7540                         err = unmark_stack_slots_iter(env, reg, nr_slots);
7541                         if (err)
7542                                 return err;
7543                 }
7544         }
7545
7546         return 0;
7547 }
7548
7549 /* process_iter_next_call() is called when verifier gets to iterator's next
7550  * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer
7551  * to it as just "iter_next()" in comments below.
7552  *
7553  * BPF verifier relies on a crucial contract for any iter_next()
7554  * implementation: it should *eventually* return NULL, and once that happens
7555  * it should keep returning NULL. That is, once iterator exhausts elements to
7556  * iterate, it should never reset or spuriously return new elements.
7557  *
7558  * With the assumption of such contract, process_iter_next_call() simulates
7559  * a fork in the verifier state to validate loop logic correctness and safety
7560  * without having to simulate infinite amount of iterations.
7561  *
7562  * In current state, we first assume that iter_next() returned NULL and
7563  * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such
7564  * conditions we should not form an infinite loop and should eventually reach
7565  * exit.
7566  *
7567  * Besides that, we also fork current state and enqueue it for later
7568  * verification. In a forked state we keep iterator state as ACTIVE
7569  * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We
7570  * also bump iteration depth to prevent erroneous infinite loop detection
7571  * later on (see iter_active_depths_differ() comment for details). In this
7572  * state we assume that we'll eventually loop back to another iter_next()
7573  * calls (it could be in exactly same location or in some other instruction,
7574  * it doesn't matter, we don't make any unnecessary assumptions about this,
7575  * everything revolves around iterator state in a stack slot, not which
7576  * instruction is calling iter_next()). When that happens, we either will come
7577  * to iter_next() with equivalent state and can conclude that next iteration
7578  * will proceed in exactly the same way as we just verified, so it's safe to
7579  * assume that loop converges. If not, we'll go on another iteration
7580  * simulation with a different input state, until all possible starting states
7581  * are validated or we reach maximum number of instructions limit.
7582  *
7583  * This way, we will either exhaustively discover all possible input states
7584  * that iterator loop can start with and eventually will converge, or we'll
7585  * effectively regress into bounded loop simulation logic and either reach
7586  * maximum number of instructions if loop is not provably convergent, or there
7587  * is some statically known limit on number of iterations (e.g., if there is
7588  * an explicit `if n > 100 then break;` statement somewhere in the loop).
7589  *
7590  * One very subtle but very important aspect is that we *always* simulate NULL
7591  * condition first (as the current state) before we simulate non-NULL case.
7592  * This has to do with intricacies of scalar precision tracking. By simulating
7593  * "exit condition" of iter_next() returning NULL first, we make sure all the
7594  * relevant precision marks *that will be set **after** we exit iterator loop*
7595  * are propagated backwards to common parent state of NULL and non-NULL
7596  * branches. Thanks to that, state equivalence checks done later in forked
7597  * state, when reaching iter_next() for ACTIVE iterator, can assume that
7598  * precision marks are finalized and won't change. Because simulating another
7599  * ACTIVE iterator iteration won't change them (because given same input
7600  * states we'll end up with exactly same output states which we are currently
7601  * comparing; and verification after the loop already propagated back what
7602  * needs to be **additionally** tracked as precise). It's subtle, grok
7603  * precision tracking for more intuitive understanding.
7604  */
7605 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx,
7606                                   struct bpf_kfunc_call_arg_meta *meta)
7607 {
7608         struct bpf_verifier_state *cur_st = env->cur_state, *queued_st;
7609         struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr;
7610         struct bpf_reg_state *cur_iter, *queued_iter;
7611         int iter_frameno = meta->iter.frameno;
7612         int iter_spi = meta->iter.spi;
7613
7614         BTF_TYPE_EMIT(struct bpf_iter);
7615
7616         cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7617
7618         if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE &&
7619             cur_iter->iter.state != BPF_ITER_STATE_DRAINED) {
7620                 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n",
7621                         cur_iter->iter.state, iter_state_str(cur_iter->iter.state));
7622                 return -EFAULT;
7623         }
7624
7625         if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) {
7626                 /* branch out active iter state */
7627                 queued_st = push_stack(env, insn_idx + 1, insn_idx, false);
7628                 if (!queued_st)
7629                         return -ENOMEM;
7630
7631                 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr;
7632                 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE;
7633                 queued_iter->iter.depth++;
7634
7635                 queued_fr = queued_st->frame[queued_st->curframe];
7636                 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]);
7637         }
7638
7639         /* switch to DRAINED state, but keep the depth unchanged */
7640         /* mark current iter state as drained and assume returned NULL */
7641         cur_iter->iter.state = BPF_ITER_STATE_DRAINED;
7642         __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]);
7643
7644         return 0;
7645 }
7646
7647 static bool arg_type_is_mem_size(enum bpf_arg_type type)
7648 {
7649         return type == ARG_CONST_SIZE ||
7650                type == ARG_CONST_SIZE_OR_ZERO;
7651 }
7652
7653 static bool arg_type_is_release(enum bpf_arg_type type)
7654 {
7655         return type & OBJ_RELEASE;
7656 }
7657
7658 static bool arg_type_is_dynptr(enum bpf_arg_type type)
7659 {
7660         return base_type(type) == ARG_PTR_TO_DYNPTR;
7661 }
7662
7663 static int int_ptr_type_to_size(enum bpf_arg_type type)
7664 {
7665         if (type == ARG_PTR_TO_INT)
7666                 return sizeof(u32);
7667         else if (type == ARG_PTR_TO_LONG)
7668                 return sizeof(u64);
7669
7670         return -EINVAL;
7671 }
7672
7673 static int resolve_map_arg_type(struct bpf_verifier_env *env,
7674                                  const struct bpf_call_arg_meta *meta,
7675                                  enum bpf_arg_type *arg_type)
7676 {
7677         if (!meta->map_ptr) {
7678                 /* kernel subsystem misconfigured verifier */
7679                 verbose(env, "invalid map_ptr to access map->type\n");
7680                 return -EACCES;
7681         }
7682
7683         switch (meta->map_ptr->map_type) {
7684         case BPF_MAP_TYPE_SOCKMAP:
7685         case BPF_MAP_TYPE_SOCKHASH:
7686                 if (*arg_type == ARG_PTR_TO_MAP_VALUE) {
7687                         *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON;
7688                 } else {
7689                         verbose(env, "invalid arg_type for sockmap/sockhash\n");
7690                         return -EINVAL;
7691                 }
7692                 break;
7693         case BPF_MAP_TYPE_BLOOM_FILTER:
7694                 if (meta->func_id == BPF_FUNC_map_peek_elem)
7695                         *arg_type = ARG_PTR_TO_MAP_VALUE;
7696                 break;
7697         default:
7698                 break;
7699         }
7700         return 0;
7701 }
7702
7703 struct bpf_reg_types {
7704         const enum bpf_reg_type types[10];
7705         u32 *btf_id;
7706 };
7707
7708 static const struct bpf_reg_types sock_types = {
7709         .types = {
7710                 PTR_TO_SOCK_COMMON,
7711                 PTR_TO_SOCKET,
7712                 PTR_TO_TCP_SOCK,
7713                 PTR_TO_XDP_SOCK,
7714         },
7715 };
7716
7717 #ifdef CONFIG_NET
7718 static const struct bpf_reg_types btf_id_sock_common_types = {
7719         .types = {
7720                 PTR_TO_SOCK_COMMON,
7721                 PTR_TO_SOCKET,
7722                 PTR_TO_TCP_SOCK,
7723                 PTR_TO_XDP_SOCK,
7724                 PTR_TO_BTF_ID,
7725                 PTR_TO_BTF_ID | PTR_TRUSTED,
7726         },
7727         .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON],
7728 };
7729 #endif
7730
7731 static const struct bpf_reg_types mem_types = {
7732         .types = {
7733                 PTR_TO_STACK,
7734                 PTR_TO_PACKET,
7735                 PTR_TO_PACKET_META,
7736                 PTR_TO_MAP_KEY,
7737                 PTR_TO_MAP_VALUE,
7738                 PTR_TO_MEM,
7739                 PTR_TO_MEM | MEM_RINGBUF,
7740                 PTR_TO_BUF,
7741                 PTR_TO_BTF_ID | PTR_TRUSTED,
7742         },
7743 };
7744
7745 static const struct bpf_reg_types int_ptr_types = {
7746         .types = {
7747                 PTR_TO_STACK,
7748                 PTR_TO_PACKET,
7749                 PTR_TO_PACKET_META,
7750                 PTR_TO_MAP_KEY,
7751                 PTR_TO_MAP_VALUE,
7752         },
7753 };
7754
7755 static const struct bpf_reg_types spin_lock_types = {
7756         .types = {
7757                 PTR_TO_MAP_VALUE,
7758                 PTR_TO_BTF_ID | MEM_ALLOC,
7759         }
7760 };
7761
7762 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } };
7763 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } };
7764 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } };
7765 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } };
7766 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } };
7767 static const struct bpf_reg_types btf_ptr_types = {
7768         .types = {
7769                 PTR_TO_BTF_ID,
7770                 PTR_TO_BTF_ID | PTR_TRUSTED,
7771                 PTR_TO_BTF_ID | MEM_RCU,
7772         },
7773 };
7774 static const struct bpf_reg_types percpu_btf_ptr_types = {
7775         .types = {
7776                 PTR_TO_BTF_ID | MEM_PERCPU,
7777                 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED,
7778         }
7779 };
7780 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } };
7781 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } };
7782 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } };
7783 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } };
7784 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } };
7785 static const struct bpf_reg_types dynptr_types = {
7786         .types = {
7787                 PTR_TO_STACK,
7788                 CONST_PTR_TO_DYNPTR,
7789         }
7790 };
7791
7792 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = {
7793         [ARG_PTR_TO_MAP_KEY]            = &mem_types,
7794         [ARG_PTR_TO_MAP_VALUE]          = &mem_types,
7795         [ARG_CONST_SIZE]                = &scalar_types,
7796         [ARG_CONST_SIZE_OR_ZERO]        = &scalar_types,
7797         [ARG_CONST_ALLOC_SIZE_OR_ZERO]  = &scalar_types,
7798         [ARG_CONST_MAP_PTR]             = &const_map_ptr_types,
7799         [ARG_PTR_TO_CTX]                = &context_types,
7800         [ARG_PTR_TO_SOCK_COMMON]        = &sock_types,
7801 #ifdef CONFIG_NET
7802         [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types,
7803 #endif
7804         [ARG_PTR_TO_SOCKET]             = &fullsock_types,
7805         [ARG_PTR_TO_BTF_ID]             = &btf_ptr_types,
7806         [ARG_PTR_TO_SPIN_LOCK]          = &spin_lock_types,
7807         [ARG_PTR_TO_MEM]                = &mem_types,
7808         [ARG_PTR_TO_RINGBUF_MEM]        = &ringbuf_mem_types,
7809         [ARG_PTR_TO_INT]                = &int_ptr_types,
7810         [ARG_PTR_TO_LONG]               = &int_ptr_types,
7811         [ARG_PTR_TO_PERCPU_BTF_ID]      = &percpu_btf_ptr_types,
7812         [ARG_PTR_TO_FUNC]               = &func_ptr_types,
7813         [ARG_PTR_TO_STACK]              = &stack_ptr_types,
7814         [ARG_PTR_TO_CONST_STR]          = &const_str_ptr_types,
7815         [ARG_PTR_TO_TIMER]              = &timer_types,
7816         [ARG_PTR_TO_KPTR]               = &kptr_types,
7817         [ARG_PTR_TO_DYNPTR]             = &dynptr_types,
7818 };
7819
7820 static int check_reg_type(struct bpf_verifier_env *env, u32 regno,
7821                           enum bpf_arg_type arg_type,
7822                           const u32 *arg_btf_id,
7823                           struct bpf_call_arg_meta *meta)
7824 {
7825         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
7826         enum bpf_reg_type expected, type = reg->type;
7827         const struct bpf_reg_types *compatible;
7828         int i, j;
7829
7830         compatible = compatible_reg_types[base_type(arg_type)];
7831         if (!compatible) {
7832                 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type);
7833                 return -EFAULT;
7834         }
7835
7836         /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY,
7837          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY
7838          *
7839          * Same for MAYBE_NULL:
7840          *
7841          * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL,
7842          * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL
7843          *
7844          * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type.
7845          *
7846          * Therefore we fold these flags depending on the arg_type before comparison.
7847          */
7848         if (arg_type & MEM_RDONLY)
7849                 type &= ~MEM_RDONLY;
7850         if (arg_type & PTR_MAYBE_NULL)
7851                 type &= ~PTR_MAYBE_NULL;
7852         if (base_type(arg_type) == ARG_PTR_TO_MEM)
7853                 type &= ~DYNPTR_TYPE_FLAG_MASK;
7854
7855         if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type))
7856                 type &= ~MEM_ALLOC;
7857
7858         for (i = 0; i < ARRAY_SIZE(compatible->types); i++) {
7859                 expected = compatible->types[i];
7860                 if (expected == NOT_INIT)
7861                         break;
7862
7863                 if (type == expected)
7864                         goto found;
7865         }
7866
7867         verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type));
7868         for (j = 0; j + 1 < i; j++)
7869                 verbose(env, "%s, ", reg_type_str(env, compatible->types[j]));
7870         verbose(env, "%s\n", reg_type_str(env, compatible->types[j]));
7871         return -EACCES;
7872
7873 found:
7874         if (base_type(reg->type) != PTR_TO_BTF_ID)
7875                 return 0;
7876
7877         if (compatible == &mem_types) {
7878                 if (!(arg_type & MEM_RDONLY)) {
7879                         verbose(env,
7880                                 "%s() may write into memory pointed by R%d type=%s\n",
7881                                 func_id_name(meta->func_id),
7882                                 regno, reg_type_str(env, reg->type));
7883                         return -EACCES;
7884                 }
7885                 return 0;
7886         }
7887
7888         switch ((int)reg->type) {
7889         case PTR_TO_BTF_ID:
7890         case PTR_TO_BTF_ID | PTR_TRUSTED:
7891         case PTR_TO_BTF_ID | MEM_RCU:
7892         case PTR_TO_BTF_ID | PTR_MAYBE_NULL:
7893         case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU:
7894         {
7895                 /* For bpf_sk_release, it needs to match against first member
7896                  * 'struct sock_common', hence make an exception for it. This
7897                  * allows bpf_sk_release to work for multiple socket types.
7898                  */
7899                 bool strict_type_match = arg_type_is_release(arg_type) &&
7900                                          meta->func_id != BPF_FUNC_sk_release;
7901
7902                 if (type_may_be_null(reg->type) &&
7903                     (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
7904                         verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno);
7905                         return -EACCES;
7906                 }
7907
7908                 if (!arg_btf_id) {
7909                         if (!compatible->btf_id) {
7910                                 verbose(env, "verifier internal error: missing arg compatible BTF ID\n");
7911                                 return -EFAULT;
7912                         }
7913                         arg_btf_id = compatible->btf_id;
7914                 }
7915
7916                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7917                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7918                                 return -EACCES;
7919                 } else {
7920                         if (arg_btf_id == BPF_PTR_POISON) {
7921                                 verbose(env, "verifier internal error:");
7922                                 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n",
7923                                         regno);
7924                                 return -EACCES;
7925                         }
7926
7927                         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off,
7928                                                   btf_vmlinux, *arg_btf_id,
7929                                                   strict_type_match)) {
7930                                 verbose(env, "R%d is of type %s but %s is expected\n",
7931                                         regno, btf_type_name(reg->btf, reg->btf_id),
7932                                         btf_type_name(btf_vmlinux, *arg_btf_id));
7933                                 return -EACCES;
7934                         }
7935                 }
7936                 break;
7937         }
7938         case PTR_TO_BTF_ID | MEM_ALLOC:
7939                 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock &&
7940                     meta->func_id != BPF_FUNC_kptr_xchg) {
7941                         verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n");
7942                         return -EFAULT;
7943                 }
7944                 if (meta->func_id == BPF_FUNC_kptr_xchg) {
7945                         if (map_kptr_match_type(env, meta->kptr_field, reg, regno))
7946                                 return -EACCES;
7947                 }
7948                 break;
7949         case PTR_TO_BTF_ID | MEM_PERCPU:
7950         case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED:
7951                 /* Handled by helper specific checks */
7952                 break;
7953         default:
7954                 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n");
7955                 return -EFAULT;
7956         }
7957         return 0;
7958 }
7959
7960 static struct btf_field *
7961 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields)
7962 {
7963         struct btf_field *field;
7964         struct btf_record *rec;
7965
7966         rec = reg_btf_record(reg);
7967         if (!rec)
7968                 return NULL;
7969
7970         field = btf_record_find(rec, off, fields);
7971         if (!field)
7972                 return NULL;
7973
7974         return field;
7975 }
7976
7977 int check_func_arg_reg_off(struct bpf_verifier_env *env,
7978                            const struct bpf_reg_state *reg, int regno,
7979                            enum bpf_arg_type arg_type)
7980 {
7981         u32 type = reg->type;
7982
7983         /* When referenced register is passed to release function, its fixed
7984          * offset must be 0.
7985          *
7986          * We will check arg_type_is_release reg has ref_obj_id when storing
7987          * meta->release_regno.
7988          */
7989         if (arg_type_is_release(arg_type)) {
7990                 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it
7991                  * may not directly point to the object being released, but to
7992                  * dynptr pointing to such object, which might be at some offset
7993                  * on the stack. In that case, we simply to fallback to the
7994                  * default handling.
7995                  */
7996                 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK)
7997                         return 0;
7998
7999                 /* Doing check_ptr_off_reg check for the offset will catch this
8000                  * because fixed_off_ok is false, but checking here allows us
8001                  * to give the user a better error message.
8002                  */
8003                 if (reg->off) {
8004                         verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n",
8005                                 regno);
8006                         return -EINVAL;
8007                 }
8008                 return __check_ptr_off_reg(env, reg, regno, false);
8009         }
8010
8011         switch (type) {
8012         /* Pointer types where both fixed and variable offset is explicitly allowed: */
8013         case PTR_TO_STACK:
8014         case PTR_TO_PACKET:
8015         case PTR_TO_PACKET_META:
8016         case PTR_TO_MAP_KEY:
8017         case PTR_TO_MAP_VALUE:
8018         case PTR_TO_MEM:
8019         case PTR_TO_MEM | MEM_RDONLY:
8020         case PTR_TO_MEM | MEM_RINGBUF:
8021         case PTR_TO_BUF:
8022         case PTR_TO_BUF | MEM_RDONLY:
8023         case SCALAR_VALUE:
8024                 return 0;
8025         /* All the rest must be rejected, except PTR_TO_BTF_ID which allows
8026          * fixed offset.
8027          */
8028         case PTR_TO_BTF_ID:
8029         case PTR_TO_BTF_ID | MEM_ALLOC:
8030         case PTR_TO_BTF_ID | PTR_TRUSTED:
8031         case PTR_TO_BTF_ID | MEM_RCU:
8032         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF:
8033         case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU:
8034                 /* When referenced PTR_TO_BTF_ID is passed to release function,
8035                  * its fixed offset must be 0. In the other cases, fixed offset
8036                  * can be non-zero. This was already checked above. So pass
8037                  * fixed_off_ok as true to allow fixed offset for all other
8038                  * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we
8039                  * still need to do checks instead of returning.
8040                  */
8041                 return __check_ptr_off_reg(env, reg, regno, true);
8042         default:
8043                 return __check_ptr_off_reg(env, reg, regno, false);
8044         }
8045 }
8046
8047 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env,
8048                                                 const struct bpf_func_proto *fn,
8049                                                 struct bpf_reg_state *regs)
8050 {
8051         struct bpf_reg_state *state = NULL;
8052         int i;
8053
8054         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++)
8055                 if (arg_type_is_dynptr(fn->arg_type[i])) {
8056                         if (state) {
8057                                 verbose(env, "verifier internal error: multiple dynptr args\n");
8058                                 return NULL;
8059                         }
8060                         state = &regs[BPF_REG_1 + i];
8061                 }
8062
8063         if (!state)
8064                 verbose(env, "verifier internal error: no dynptr arg found\n");
8065
8066         return state;
8067 }
8068
8069 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8070 {
8071         struct bpf_func_state *state = func(env, reg);
8072         int spi;
8073
8074         if (reg->type == CONST_PTR_TO_DYNPTR)
8075                 return reg->id;
8076         spi = dynptr_get_spi(env, reg);
8077         if (spi < 0)
8078                 return spi;
8079         return state->stack[spi].spilled_ptr.id;
8080 }
8081
8082 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
8083 {
8084         struct bpf_func_state *state = func(env, reg);
8085         int spi;
8086
8087         if (reg->type == CONST_PTR_TO_DYNPTR)
8088                 return reg->ref_obj_id;
8089         spi = dynptr_get_spi(env, reg);
8090         if (spi < 0)
8091                 return spi;
8092         return state->stack[spi].spilled_ptr.ref_obj_id;
8093 }
8094
8095 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env,
8096                                             struct bpf_reg_state *reg)
8097 {
8098         struct bpf_func_state *state = func(env, reg);
8099         int spi;
8100
8101         if (reg->type == CONST_PTR_TO_DYNPTR)
8102                 return reg->dynptr.type;
8103
8104         spi = __get_spi(reg->off);
8105         if (spi < 0) {
8106                 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n");
8107                 return BPF_DYNPTR_TYPE_INVALID;
8108         }
8109
8110         return state->stack[spi].spilled_ptr.dynptr.type;
8111 }
8112
8113 static int check_func_arg(struct bpf_verifier_env *env, u32 arg,
8114                           struct bpf_call_arg_meta *meta,
8115                           const struct bpf_func_proto *fn,
8116                           int insn_idx)
8117 {
8118         u32 regno = BPF_REG_1 + arg;
8119         struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[regno];
8120         enum bpf_arg_type arg_type = fn->arg_type[arg];
8121         enum bpf_reg_type type = reg->type;
8122         u32 *arg_btf_id = NULL;
8123         int err = 0;
8124
8125         if (arg_type == ARG_DONTCARE)
8126                 return 0;
8127
8128         err = check_reg_arg(env, regno, SRC_OP);
8129         if (err)
8130                 return err;
8131
8132         if (arg_type == ARG_ANYTHING) {
8133                 if (is_pointer_value(env, regno)) {
8134                         verbose(env, "R%d leaks addr into helper function\n",
8135                                 regno);
8136                         return -EACCES;
8137                 }
8138                 return 0;
8139         }
8140
8141         if (type_is_pkt_pointer(type) &&
8142             !may_access_direct_pkt_data(env, meta, BPF_READ)) {
8143                 verbose(env, "helper access to the packet is not allowed\n");
8144                 return -EACCES;
8145         }
8146
8147         if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) {
8148                 err = resolve_map_arg_type(env, meta, &arg_type);
8149                 if (err)
8150                         return err;
8151         }
8152
8153         if (register_is_null(reg) && type_may_be_null(arg_type))
8154                 /* A NULL register has a SCALAR_VALUE type, so skip
8155                  * type checking.
8156                  */
8157                 goto skip_type_check;
8158
8159         /* arg_btf_id and arg_size are in a union. */
8160         if (base_type(arg_type) == ARG_PTR_TO_BTF_ID ||
8161             base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK)
8162                 arg_btf_id = fn->arg_btf_id[arg];
8163
8164         err = check_reg_type(env, regno, arg_type, arg_btf_id, meta);
8165         if (err)
8166                 return err;
8167
8168         err = check_func_arg_reg_off(env, reg, regno, arg_type);
8169         if (err)
8170                 return err;
8171
8172 skip_type_check:
8173         if (arg_type_is_release(arg_type)) {
8174                 if (arg_type_is_dynptr(arg_type)) {
8175                         struct bpf_func_state *state = func(env, reg);
8176                         int spi;
8177
8178                         /* Only dynptr created on stack can be released, thus
8179                          * the get_spi and stack state checks for spilled_ptr
8180                          * should only be done before process_dynptr_func for
8181                          * PTR_TO_STACK.
8182                          */
8183                         if (reg->type == PTR_TO_STACK) {
8184                                 spi = dynptr_get_spi(env, reg);
8185                                 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) {
8186                                         verbose(env, "arg %d is an unacquired reference\n", regno);
8187                                         return -EINVAL;
8188                                 }
8189                         } else {
8190                                 verbose(env, "cannot release unowned const bpf_dynptr\n");
8191                                 return -EINVAL;
8192                         }
8193                 } else if (!reg->ref_obj_id && !register_is_null(reg)) {
8194                         verbose(env, "R%d must be referenced when passed to release function\n",
8195                                 regno);
8196                         return -EINVAL;
8197                 }
8198                 if (meta->release_regno) {
8199                         verbose(env, "verifier internal error: more than one release argument\n");
8200                         return -EFAULT;
8201                 }
8202                 meta->release_regno = regno;
8203         }
8204
8205         if (reg->ref_obj_id) {
8206                 if (meta->ref_obj_id) {
8207                         verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
8208                                 regno, reg->ref_obj_id,
8209                                 meta->ref_obj_id);
8210                         return -EFAULT;
8211                 }
8212                 meta->ref_obj_id = reg->ref_obj_id;
8213         }
8214
8215         switch (base_type(arg_type)) {
8216         case ARG_CONST_MAP_PTR:
8217                 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */
8218                 if (meta->map_ptr) {
8219                         /* Use map_uid (which is unique id of inner map) to reject:
8220                          * inner_map1 = bpf_map_lookup_elem(outer_map, key1)
8221                          * inner_map2 = bpf_map_lookup_elem(outer_map, key2)
8222                          * if (inner_map1 && inner_map2) {
8223                          *     timer = bpf_map_lookup_elem(inner_map1);
8224                          *     if (timer)
8225                          *         // mismatch would have been allowed
8226                          *         bpf_timer_init(timer, inner_map2);
8227                          * }
8228                          *
8229                          * Comparing map_ptr is enough to distinguish normal and outer maps.
8230                          */
8231                         if (meta->map_ptr != reg->map_ptr ||
8232                             meta->map_uid != reg->map_uid) {
8233                                 verbose(env,
8234                                         "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n",
8235                                         meta->map_uid, reg->map_uid);
8236                                 return -EINVAL;
8237                         }
8238                 }
8239                 meta->map_ptr = reg->map_ptr;
8240                 meta->map_uid = reg->map_uid;
8241                 break;
8242         case ARG_PTR_TO_MAP_KEY:
8243                 /* bpf_map_xxx(..., map_ptr, ..., key) call:
8244                  * check that [key, key + map->key_size) are within
8245                  * stack limits and initialized
8246                  */
8247                 if (!meta->map_ptr) {
8248                         /* in function declaration map_ptr must come before
8249                          * map_key, so that it's verified and known before
8250                          * we have to check map_key here. Otherwise it means
8251                          * that kernel subsystem misconfigured verifier
8252                          */
8253                         verbose(env, "invalid map_ptr to access map->key\n");
8254                         return -EACCES;
8255                 }
8256                 err = check_helper_mem_access(env, regno,
8257                                               meta->map_ptr->key_size, false,
8258                                               NULL);
8259                 break;
8260         case ARG_PTR_TO_MAP_VALUE:
8261                 if (type_may_be_null(arg_type) && register_is_null(reg))
8262                         return 0;
8263
8264                 /* bpf_map_xxx(..., map_ptr, ..., value) call:
8265                  * check [value, value + map->value_size) validity
8266                  */
8267                 if (!meta->map_ptr) {
8268                         /* kernel subsystem misconfigured verifier */
8269                         verbose(env, "invalid map_ptr to access map->value\n");
8270                         return -EACCES;
8271                 }
8272                 meta->raw_mode = arg_type & MEM_UNINIT;
8273                 err = check_helper_mem_access(env, regno,
8274                                               meta->map_ptr->value_size, false,
8275                                               meta);
8276                 break;
8277         case ARG_PTR_TO_PERCPU_BTF_ID:
8278                 if (!reg->btf_id) {
8279                         verbose(env, "Helper has invalid btf_id in R%d\n", regno);
8280                         return -EACCES;
8281                 }
8282                 meta->ret_btf = reg->btf;
8283                 meta->ret_btf_id = reg->btf_id;
8284                 break;
8285         case ARG_PTR_TO_SPIN_LOCK:
8286                 if (in_rbtree_lock_required_cb(env)) {
8287                         verbose(env, "can't spin_{lock,unlock} in rbtree cb\n");
8288                         return -EACCES;
8289                 }
8290                 if (meta->func_id == BPF_FUNC_spin_lock) {
8291                         err = process_spin_lock(env, regno, true);
8292                         if (err)
8293                                 return err;
8294                 } else if (meta->func_id == BPF_FUNC_spin_unlock) {
8295                         err = process_spin_lock(env, regno, false);
8296                         if (err)
8297                                 return err;
8298                 } else {
8299                         verbose(env, "verifier internal error\n");
8300                         return -EFAULT;
8301                 }
8302                 break;
8303         case ARG_PTR_TO_TIMER:
8304                 err = process_timer_func(env, regno, meta);
8305                 if (err)
8306                         return err;
8307                 break;
8308         case ARG_PTR_TO_FUNC:
8309                 meta->subprogno = reg->subprogno;
8310                 break;
8311         case ARG_PTR_TO_MEM:
8312                 /* The access to this pointer is only checked when we hit the
8313                  * next is_mem_size argument below.
8314                  */
8315                 meta->raw_mode = arg_type & MEM_UNINIT;
8316                 if (arg_type & MEM_FIXED_SIZE) {
8317                         err = check_helper_mem_access(env, regno,
8318                                                       fn->arg_size[arg], false,
8319                                                       meta);
8320                 }
8321                 break;
8322         case ARG_CONST_SIZE:
8323                 err = check_mem_size_reg(env, reg, regno, false, meta);
8324                 break;
8325         case ARG_CONST_SIZE_OR_ZERO:
8326                 err = check_mem_size_reg(env, reg, regno, true, meta);
8327                 break;
8328         case ARG_PTR_TO_DYNPTR:
8329                 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0);
8330                 if (err)
8331                         return err;
8332                 break;
8333         case ARG_CONST_ALLOC_SIZE_OR_ZERO:
8334                 if (!tnum_is_const(reg->var_off)) {
8335                         verbose(env, "R%d is not a known constant'\n",
8336                                 regno);
8337                         return -EACCES;
8338                 }
8339                 meta->mem_size = reg->var_off.value;
8340                 err = mark_chain_precision(env, regno);
8341                 if (err)
8342                         return err;
8343                 break;
8344         case ARG_PTR_TO_INT:
8345         case ARG_PTR_TO_LONG:
8346         {
8347                 int size = int_ptr_type_to_size(arg_type);
8348
8349                 err = check_helper_mem_access(env, regno, size, false, meta);
8350                 if (err)
8351                         return err;
8352                 err = check_ptr_alignment(env, reg, 0, size, true);
8353                 break;
8354         }
8355         case ARG_PTR_TO_CONST_STR:
8356         {
8357                 struct bpf_map *map = reg->map_ptr;
8358                 int map_off;
8359                 u64 map_addr;
8360                 char *str_ptr;
8361
8362                 if (!bpf_map_is_rdonly(map)) {
8363                         verbose(env, "R%d does not point to a readonly map'\n", regno);
8364                         return -EACCES;
8365                 }
8366
8367                 if (!tnum_is_const(reg->var_off)) {
8368                         verbose(env, "R%d is not a constant address'\n", regno);
8369                         return -EACCES;
8370                 }
8371
8372                 if (!map->ops->map_direct_value_addr) {
8373                         verbose(env, "no direct value access support for this map type\n");
8374                         return -EACCES;
8375                 }
8376
8377                 err = check_map_access(env, regno, reg->off,
8378                                        map->value_size - reg->off, false,
8379                                        ACCESS_HELPER);
8380                 if (err)
8381                         return err;
8382
8383                 map_off = reg->off + reg->var_off.value;
8384                 err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
8385                 if (err) {
8386                         verbose(env, "direct value access on string failed\n");
8387                         return err;
8388                 }
8389
8390                 str_ptr = (char *)(long)(map_addr);
8391                 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) {
8392                         verbose(env, "string is not zero-terminated\n");
8393                         return -EINVAL;
8394                 }
8395                 break;
8396         }
8397         case ARG_PTR_TO_KPTR:
8398                 err = process_kptr_func(env, regno, meta);
8399                 if (err)
8400                         return err;
8401                 break;
8402         }
8403
8404         return err;
8405 }
8406
8407 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id)
8408 {
8409         enum bpf_attach_type eatype = env->prog->expected_attach_type;
8410         enum bpf_prog_type type = resolve_prog_type(env->prog);
8411
8412         if (func_id != BPF_FUNC_map_update_elem)
8413                 return false;
8414
8415         /* It's not possible to get access to a locked struct sock in these
8416          * contexts, so updating is safe.
8417          */
8418         switch (type) {
8419         case BPF_PROG_TYPE_TRACING:
8420                 if (eatype == BPF_TRACE_ITER)
8421                         return true;
8422                 break;
8423         case BPF_PROG_TYPE_SOCKET_FILTER:
8424         case BPF_PROG_TYPE_SCHED_CLS:
8425         case BPF_PROG_TYPE_SCHED_ACT:
8426         case BPF_PROG_TYPE_XDP:
8427         case BPF_PROG_TYPE_SK_REUSEPORT:
8428         case BPF_PROG_TYPE_FLOW_DISSECTOR:
8429         case BPF_PROG_TYPE_SK_LOOKUP:
8430                 return true;
8431         default:
8432                 break;
8433         }
8434
8435         verbose(env, "cannot update sockmap in this context\n");
8436         return false;
8437 }
8438
8439 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env)
8440 {
8441         return env->prog->jit_requested &&
8442                bpf_jit_supports_subprog_tailcalls();
8443 }
8444
8445 static int check_map_func_compatibility(struct bpf_verifier_env *env,
8446                                         struct bpf_map *map, int func_id)
8447 {
8448         if (!map)
8449                 return 0;
8450
8451         /* We need a two way check, first is from map perspective ... */
8452         switch (map->map_type) {
8453         case BPF_MAP_TYPE_PROG_ARRAY:
8454                 if (func_id != BPF_FUNC_tail_call)
8455                         goto error;
8456                 break;
8457         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
8458                 if (func_id != BPF_FUNC_perf_event_read &&
8459                     func_id != BPF_FUNC_perf_event_output &&
8460                     func_id != BPF_FUNC_skb_output &&
8461                     func_id != BPF_FUNC_perf_event_read_value &&
8462                     func_id != BPF_FUNC_xdp_output)
8463                         goto error;
8464                 break;
8465         case BPF_MAP_TYPE_RINGBUF:
8466                 if (func_id != BPF_FUNC_ringbuf_output &&
8467                     func_id != BPF_FUNC_ringbuf_reserve &&
8468                     func_id != BPF_FUNC_ringbuf_query &&
8469                     func_id != BPF_FUNC_ringbuf_reserve_dynptr &&
8470                     func_id != BPF_FUNC_ringbuf_submit_dynptr &&
8471                     func_id != BPF_FUNC_ringbuf_discard_dynptr)
8472                         goto error;
8473                 break;
8474         case BPF_MAP_TYPE_USER_RINGBUF:
8475                 if (func_id != BPF_FUNC_user_ringbuf_drain)
8476                         goto error;
8477                 break;
8478         case BPF_MAP_TYPE_STACK_TRACE:
8479                 if (func_id != BPF_FUNC_get_stackid)
8480                         goto error;
8481                 break;
8482         case BPF_MAP_TYPE_CGROUP_ARRAY:
8483                 if (func_id != BPF_FUNC_skb_under_cgroup &&
8484                     func_id != BPF_FUNC_current_task_under_cgroup)
8485                         goto error;
8486                 break;
8487         case BPF_MAP_TYPE_CGROUP_STORAGE:
8488         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
8489                 if (func_id != BPF_FUNC_get_local_storage)
8490                         goto error;
8491                 break;
8492         case BPF_MAP_TYPE_DEVMAP:
8493         case BPF_MAP_TYPE_DEVMAP_HASH:
8494                 if (func_id != BPF_FUNC_redirect_map &&
8495                     func_id != BPF_FUNC_map_lookup_elem)
8496                         goto error;
8497                 break;
8498         /* Restrict bpf side of cpumap and xskmap, open when use-cases
8499          * appear.
8500          */
8501         case BPF_MAP_TYPE_CPUMAP:
8502                 if (func_id != BPF_FUNC_redirect_map)
8503                         goto error;
8504                 break;
8505         case BPF_MAP_TYPE_XSKMAP:
8506                 if (func_id != BPF_FUNC_redirect_map &&
8507                     func_id != BPF_FUNC_map_lookup_elem)
8508                         goto error;
8509                 break;
8510         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
8511         case BPF_MAP_TYPE_HASH_OF_MAPS:
8512                 if (func_id != BPF_FUNC_map_lookup_elem)
8513                         goto error;
8514                 break;
8515         case BPF_MAP_TYPE_SOCKMAP:
8516                 if (func_id != BPF_FUNC_sk_redirect_map &&
8517                     func_id != BPF_FUNC_sock_map_update &&
8518                     func_id != BPF_FUNC_map_delete_elem &&
8519                     func_id != BPF_FUNC_msg_redirect_map &&
8520                     func_id != BPF_FUNC_sk_select_reuseport &&
8521                     func_id != BPF_FUNC_map_lookup_elem &&
8522                     !may_update_sockmap(env, func_id))
8523                         goto error;
8524                 break;
8525         case BPF_MAP_TYPE_SOCKHASH:
8526                 if (func_id != BPF_FUNC_sk_redirect_hash &&
8527                     func_id != BPF_FUNC_sock_hash_update &&
8528                     func_id != BPF_FUNC_map_delete_elem &&
8529                     func_id != BPF_FUNC_msg_redirect_hash &&
8530                     func_id != BPF_FUNC_sk_select_reuseport &&
8531                     func_id != BPF_FUNC_map_lookup_elem &&
8532                     !may_update_sockmap(env, func_id))
8533                         goto error;
8534                 break;
8535         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
8536                 if (func_id != BPF_FUNC_sk_select_reuseport)
8537                         goto error;
8538                 break;
8539         case BPF_MAP_TYPE_QUEUE:
8540         case BPF_MAP_TYPE_STACK:
8541                 if (func_id != BPF_FUNC_map_peek_elem &&
8542                     func_id != BPF_FUNC_map_pop_elem &&
8543                     func_id != BPF_FUNC_map_push_elem)
8544                         goto error;
8545                 break;
8546         case BPF_MAP_TYPE_SK_STORAGE:
8547                 if (func_id != BPF_FUNC_sk_storage_get &&
8548                     func_id != BPF_FUNC_sk_storage_delete &&
8549                     func_id != BPF_FUNC_kptr_xchg)
8550                         goto error;
8551                 break;
8552         case BPF_MAP_TYPE_INODE_STORAGE:
8553                 if (func_id != BPF_FUNC_inode_storage_get &&
8554                     func_id != BPF_FUNC_inode_storage_delete &&
8555                     func_id != BPF_FUNC_kptr_xchg)
8556                         goto error;
8557                 break;
8558         case BPF_MAP_TYPE_TASK_STORAGE:
8559                 if (func_id != BPF_FUNC_task_storage_get &&
8560                     func_id != BPF_FUNC_task_storage_delete &&
8561                     func_id != BPF_FUNC_kptr_xchg)
8562                         goto error;
8563                 break;
8564         case BPF_MAP_TYPE_CGRP_STORAGE:
8565                 if (func_id != BPF_FUNC_cgrp_storage_get &&
8566                     func_id != BPF_FUNC_cgrp_storage_delete &&
8567                     func_id != BPF_FUNC_kptr_xchg)
8568                         goto error;
8569                 break;
8570         case BPF_MAP_TYPE_BLOOM_FILTER:
8571                 if (func_id != BPF_FUNC_map_peek_elem &&
8572                     func_id != BPF_FUNC_map_push_elem)
8573                         goto error;
8574                 break;
8575         default:
8576                 break;
8577         }
8578
8579         /* ... and second from the function itself. */
8580         switch (func_id) {
8581         case BPF_FUNC_tail_call:
8582                 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
8583                         goto error;
8584                 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) {
8585                         verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
8586                         return -EINVAL;
8587                 }
8588                 break;
8589         case BPF_FUNC_perf_event_read:
8590         case BPF_FUNC_perf_event_output:
8591         case BPF_FUNC_perf_event_read_value:
8592         case BPF_FUNC_skb_output:
8593         case BPF_FUNC_xdp_output:
8594                 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY)
8595                         goto error;
8596                 break;
8597         case BPF_FUNC_ringbuf_output:
8598         case BPF_FUNC_ringbuf_reserve:
8599         case BPF_FUNC_ringbuf_query:
8600         case BPF_FUNC_ringbuf_reserve_dynptr:
8601         case BPF_FUNC_ringbuf_submit_dynptr:
8602         case BPF_FUNC_ringbuf_discard_dynptr:
8603                 if (map->map_type != BPF_MAP_TYPE_RINGBUF)
8604                         goto error;
8605                 break;
8606         case BPF_FUNC_user_ringbuf_drain:
8607                 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF)
8608                         goto error;
8609                 break;
8610         case BPF_FUNC_get_stackid:
8611                 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE)
8612                         goto error;
8613                 break;
8614         case BPF_FUNC_current_task_under_cgroup:
8615         case BPF_FUNC_skb_under_cgroup:
8616                 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY)
8617                         goto error;
8618                 break;
8619         case BPF_FUNC_redirect_map:
8620                 if (map->map_type != BPF_MAP_TYPE_DEVMAP &&
8621                     map->map_type != BPF_MAP_TYPE_DEVMAP_HASH &&
8622                     map->map_type != BPF_MAP_TYPE_CPUMAP &&
8623                     map->map_type != BPF_MAP_TYPE_XSKMAP)
8624                         goto error;
8625                 break;
8626         case BPF_FUNC_sk_redirect_map:
8627         case BPF_FUNC_msg_redirect_map:
8628         case BPF_FUNC_sock_map_update:
8629                 if (map->map_type != BPF_MAP_TYPE_SOCKMAP)
8630                         goto error;
8631                 break;
8632         case BPF_FUNC_sk_redirect_hash:
8633         case BPF_FUNC_msg_redirect_hash:
8634         case BPF_FUNC_sock_hash_update:
8635                 if (map->map_type != BPF_MAP_TYPE_SOCKHASH)
8636                         goto error;
8637                 break;
8638         case BPF_FUNC_get_local_storage:
8639                 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
8640                     map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
8641                         goto error;
8642                 break;
8643         case BPF_FUNC_sk_select_reuseport:
8644                 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY &&
8645                     map->map_type != BPF_MAP_TYPE_SOCKMAP &&
8646                     map->map_type != BPF_MAP_TYPE_SOCKHASH)
8647                         goto error;
8648                 break;
8649         case BPF_FUNC_map_pop_elem:
8650                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8651                     map->map_type != BPF_MAP_TYPE_STACK)
8652                         goto error;
8653                 break;
8654         case BPF_FUNC_map_peek_elem:
8655         case BPF_FUNC_map_push_elem:
8656                 if (map->map_type != BPF_MAP_TYPE_QUEUE &&
8657                     map->map_type != BPF_MAP_TYPE_STACK &&
8658                     map->map_type != BPF_MAP_TYPE_BLOOM_FILTER)
8659                         goto error;
8660                 break;
8661         case BPF_FUNC_map_lookup_percpu_elem:
8662                 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
8663                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
8664                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH)
8665                         goto error;
8666                 break;
8667         case BPF_FUNC_sk_storage_get:
8668         case BPF_FUNC_sk_storage_delete:
8669                 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE)
8670                         goto error;
8671                 break;
8672         case BPF_FUNC_inode_storage_get:
8673         case BPF_FUNC_inode_storage_delete:
8674                 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
8675                         goto error;
8676                 break;
8677         case BPF_FUNC_task_storage_get:
8678         case BPF_FUNC_task_storage_delete:
8679                 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE)
8680                         goto error;
8681                 break;
8682         case BPF_FUNC_cgrp_storage_get:
8683         case BPF_FUNC_cgrp_storage_delete:
8684                 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE)
8685                         goto error;
8686                 break;
8687         default:
8688                 break;
8689         }
8690
8691         return 0;
8692 error:
8693         verbose(env, "cannot pass map_type %d into func %s#%d\n",
8694                 map->map_type, func_id_name(func_id), func_id);
8695         return -EINVAL;
8696 }
8697
8698 static bool check_raw_mode_ok(const struct bpf_func_proto *fn)
8699 {
8700         int count = 0;
8701
8702         if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM)
8703                 count++;
8704         if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM)
8705                 count++;
8706         if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM)
8707                 count++;
8708         if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM)
8709                 count++;
8710         if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM)
8711                 count++;
8712
8713         /* We only support one arg being in raw mode at the moment,
8714          * which is sufficient for the helper functions we have
8715          * right now.
8716          */
8717         return count <= 1;
8718 }
8719
8720 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg)
8721 {
8722         bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE;
8723         bool has_size = fn->arg_size[arg] != 0;
8724         bool is_next_size = false;
8725
8726         if (arg + 1 < ARRAY_SIZE(fn->arg_type))
8727                 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]);
8728
8729         if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM)
8730                 return is_next_size;
8731
8732         return has_size == is_next_size || is_next_size == is_fixed;
8733 }
8734
8735 static bool check_arg_pair_ok(const struct bpf_func_proto *fn)
8736 {
8737         /* bpf_xxx(..., buf, len) call will access 'len'
8738          * bytes from memory 'buf'. Both arg types need
8739          * to be paired, so make sure there's no buggy
8740          * helper function specification.
8741          */
8742         if (arg_type_is_mem_size(fn->arg1_type) ||
8743             check_args_pair_invalid(fn, 0) ||
8744             check_args_pair_invalid(fn, 1) ||
8745             check_args_pair_invalid(fn, 2) ||
8746             check_args_pair_invalid(fn, 3) ||
8747             check_args_pair_invalid(fn, 4))
8748                 return false;
8749
8750         return true;
8751 }
8752
8753 static bool check_btf_id_ok(const struct bpf_func_proto *fn)
8754 {
8755         int i;
8756
8757         for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) {
8758                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID)
8759                         return !!fn->arg_btf_id[i];
8760                 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK)
8761                         return fn->arg_btf_id[i] == BPF_PTR_POISON;
8762                 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] &&
8763                     /* arg_btf_id and arg_size are in a union. */
8764                     (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM ||
8765                      !(fn->arg_type[i] & MEM_FIXED_SIZE)))
8766                         return false;
8767         }
8768
8769         return true;
8770 }
8771
8772 static int check_func_proto(const struct bpf_func_proto *fn, int func_id)
8773 {
8774         return check_raw_mode_ok(fn) &&
8775                check_arg_pair_ok(fn) &&
8776                check_btf_id_ok(fn) ? 0 : -EINVAL;
8777 }
8778
8779 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END]
8780  * are now invalid, so turn them into unknown SCALAR_VALUE.
8781  *
8782  * This also applies to dynptr slices belonging to skb and xdp dynptrs,
8783  * since these slices point to packet data.
8784  */
8785 static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
8786 {
8787         struct bpf_func_state *state;
8788         struct bpf_reg_state *reg;
8789
8790         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8791                 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg))
8792                         mark_reg_invalid(env, reg);
8793         }));
8794 }
8795
8796 enum {
8797         AT_PKT_END = -1,
8798         BEYOND_PKT_END = -2,
8799 };
8800
8801 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open)
8802 {
8803         struct bpf_func_state *state = vstate->frame[vstate->curframe];
8804         struct bpf_reg_state *reg = &state->regs[regn];
8805
8806         if (reg->type != PTR_TO_PACKET)
8807                 /* PTR_TO_PACKET_META is not supported yet */
8808                 return;
8809
8810         /* The 'reg' is pkt > pkt_end or pkt >= pkt_end.
8811          * How far beyond pkt_end it goes is unknown.
8812          * if (!range_open) it's the case of pkt >= pkt_end
8813          * if (range_open) it's the case of pkt > pkt_end
8814          * hence this pointer is at least 1 byte bigger than pkt_end
8815          */
8816         if (range_open)
8817                 reg->range = BEYOND_PKT_END;
8818         else
8819                 reg->range = AT_PKT_END;
8820 }
8821
8822 /* The pointer with the specified id has released its reference to kernel
8823  * resources. Identify all copies of the same pointer and clear the reference.
8824  */
8825 static int release_reference(struct bpf_verifier_env *env,
8826                              int ref_obj_id)
8827 {
8828         struct bpf_func_state *state;
8829         struct bpf_reg_state *reg;
8830         int err;
8831
8832         err = release_reference_state(cur_func(env), ref_obj_id);
8833         if (err)
8834                 return err;
8835
8836         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
8837                 if (reg->ref_obj_id == ref_obj_id)
8838                         mark_reg_invalid(env, reg);
8839         }));
8840
8841         return 0;
8842 }
8843
8844 static void invalidate_non_owning_refs(struct bpf_verifier_env *env)
8845 {
8846         struct bpf_func_state *unused;
8847         struct bpf_reg_state *reg;
8848
8849         bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
8850                 if (type_is_non_owning_ref(reg->type))
8851                         mark_reg_invalid(env, reg);
8852         }));
8853 }
8854
8855 static void clear_caller_saved_regs(struct bpf_verifier_env *env,
8856                                     struct bpf_reg_state *regs)
8857 {
8858         int i;
8859
8860         /* after the call registers r0 - r5 were scratched */
8861         for (i = 0; i < CALLER_SAVED_REGS; i++) {
8862                 mark_reg_not_init(env, regs, caller_saved[i]);
8863                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
8864         }
8865 }
8866
8867 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env,
8868                                    struct bpf_func_state *caller,
8869                                    struct bpf_func_state *callee,
8870                                    int insn_idx);
8871
8872 static int set_callee_state(struct bpf_verifier_env *env,
8873                             struct bpf_func_state *caller,
8874                             struct bpf_func_state *callee, int insn_idx);
8875
8876 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
8877                              int *insn_idx, int subprog,
8878                              set_callee_state_fn set_callee_state_cb)
8879 {
8880         struct bpf_verifier_state *state = env->cur_state;
8881         struct bpf_func_state *caller, *callee;
8882         int err;
8883
8884         if (state->curframe + 1 >= MAX_CALL_FRAMES) {
8885                 verbose(env, "the call stack of %d frames is too deep\n",
8886                         state->curframe + 2);
8887                 return -E2BIG;
8888         }
8889
8890         caller = state->frame[state->curframe];
8891         if (state->frame[state->curframe + 1]) {
8892                 verbose(env, "verifier bug. Frame %d already allocated\n",
8893                         state->curframe + 1);
8894                 return -EFAULT;
8895         }
8896
8897         err = btf_check_subprog_call(env, subprog, caller->regs);
8898         if (err == -EFAULT)
8899                 return err;
8900         if (subprog_is_global(env, subprog)) {
8901                 if (err) {
8902                         verbose(env, "Caller passes invalid args into func#%d\n",
8903                                 subprog);
8904                         return err;
8905                 } else {
8906                         if (env->log.level & BPF_LOG_LEVEL)
8907                                 verbose(env,
8908                                         "Func#%d is global and valid. Skipping.\n",
8909                                         subprog);
8910                         clear_caller_saved_regs(env, caller->regs);
8911
8912                         /* All global functions return a 64-bit SCALAR_VALUE */
8913                         mark_reg_unknown(env, caller->regs, BPF_REG_0);
8914                         caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8915
8916                         /* continue with next insn after call */
8917                         return 0;
8918                 }
8919         }
8920
8921         /* set_callee_state is used for direct subprog calls, but we are
8922          * interested in validating only BPF helpers that can call subprogs as
8923          * callbacks
8924          */
8925         if (set_callee_state_cb != set_callee_state) {
8926                 if (bpf_pseudo_kfunc_call(insn) &&
8927                     !is_callback_calling_kfunc(insn->imm)) {
8928                         verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n",
8929                                 func_id_name(insn->imm), insn->imm);
8930                         return -EFAULT;
8931                 } else if (!bpf_pseudo_kfunc_call(insn) &&
8932                            !is_callback_calling_function(insn->imm)) { /* helper */
8933                         verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n",
8934                                 func_id_name(insn->imm), insn->imm);
8935                         return -EFAULT;
8936                 }
8937         }
8938
8939         if (insn->code == (BPF_JMP | BPF_CALL) &&
8940             insn->src_reg == 0 &&
8941             insn->imm == BPF_FUNC_timer_set_callback) {
8942                 struct bpf_verifier_state *async_cb;
8943
8944                 /* there is no real recursion here. timer callbacks are async */
8945                 env->subprog_info[subprog].is_async_cb = true;
8946                 async_cb = push_async_cb(env, env->subprog_info[subprog].start,
8947                                          *insn_idx, subprog);
8948                 if (!async_cb)
8949                         return -EFAULT;
8950                 callee = async_cb->frame[0];
8951                 callee->async_entry_cnt = caller->async_entry_cnt + 1;
8952
8953                 /* Convert bpf_timer_set_callback() args into timer callback args */
8954                 err = set_callee_state_cb(env, caller, callee, *insn_idx);
8955                 if (err)
8956                         return err;
8957
8958                 clear_caller_saved_regs(env, caller->regs);
8959                 mark_reg_unknown(env, caller->regs, BPF_REG_0);
8960                 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
8961                 /* continue with next insn after call */
8962                 return 0;
8963         }
8964
8965         callee = kzalloc(sizeof(*callee), GFP_KERNEL);
8966         if (!callee)
8967                 return -ENOMEM;
8968         state->frame[state->curframe + 1] = callee;
8969
8970         /* callee cannot access r0, r6 - r9 for reading and has to write
8971          * into its own stack before reading from it.
8972          * callee can read/write into caller's stack
8973          */
8974         init_func_state(env, callee,
8975                         /* remember the callsite, it will be used by bpf_exit */
8976                         *insn_idx /* callsite */,
8977                         state->curframe + 1 /* frameno within this callchain */,
8978                         subprog /* subprog number within this prog */);
8979
8980         /* Transfer references to the callee */
8981         err = copy_reference_state(callee, caller);
8982         if (err)
8983                 goto err_out;
8984
8985         err = set_callee_state_cb(env, caller, callee, *insn_idx);
8986         if (err)
8987                 goto err_out;
8988
8989         clear_caller_saved_regs(env, caller->regs);
8990
8991         /* only increment it after check_reg_arg() finished */
8992         state->curframe++;
8993
8994         /* and go analyze first insn of the callee */
8995         *insn_idx = env->subprog_info[subprog].start - 1;
8996
8997         if (env->log.level & BPF_LOG_LEVEL) {
8998                 verbose(env, "caller:\n");
8999                 print_verifier_state(env, caller, true);
9000                 verbose(env, "callee:\n");
9001                 print_verifier_state(env, callee, true);
9002         }
9003         return 0;
9004
9005 err_out:
9006         free_func_state(callee);
9007         state->frame[state->curframe + 1] = NULL;
9008         return err;
9009 }
9010
9011 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
9012                                    struct bpf_func_state *caller,
9013                                    struct bpf_func_state *callee)
9014 {
9015         /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn,
9016          *      void *callback_ctx, u64 flags);
9017          * callback_fn(struct bpf_map *map, void *key, void *value,
9018          *      void *callback_ctx);
9019          */
9020         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9021
9022         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9023         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9024         callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9025
9026         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9027         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9028         callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr;
9029
9030         /* pointer to stack or null */
9031         callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3];
9032
9033         /* unused */
9034         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9035         return 0;
9036 }
9037
9038 static int set_callee_state(struct bpf_verifier_env *env,
9039                             struct bpf_func_state *caller,
9040                             struct bpf_func_state *callee, int insn_idx)
9041 {
9042         int i;
9043
9044         /* copy r1 - r5 args that callee can access.  The copy includes parent
9045          * pointers, which connects us up to the liveness chain
9046          */
9047         for (i = BPF_REG_1; i <= BPF_REG_5; i++)
9048                 callee->regs[i] = caller->regs[i];
9049         return 0;
9050 }
9051
9052 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9053                            int *insn_idx)
9054 {
9055         int subprog, target_insn;
9056
9057         target_insn = *insn_idx + insn->imm + 1;
9058         subprog = find_subprog(env, target_insn);
9059         if (subprog < 0) {
9060                 verbose(env, "verifier bug. No program starts at insn %d\n",
9061                         target_insn);
9062                 return -EFAULT;
9063         }
9064
9065         return __check_func_call(env, insn, insn_idx, subprog, set_callee_state);
9066 }
9067
9068 static int set_map_elem_callback_state(struct bpf_verifier_env *env,
9069                                        struct bpf_func_state *caller,
9070                                        struct bpf_func_state *callee,
9071                                        int insn_idx)
9072 {
9073         struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx];
9074         struct bpf_map *map;
9075         int err;
9076
9077         if (bpf_map_ptr_poisoned(insn_aux)) {
9078                 verbose(env, "tail_call abusing map_ptr\n");
9079                 return -EINVAL;
9080         }
9081
9082         map = BPF_MAP_PTR(insn_aux->map_ptr_state);
9083         if (!map->ops->map_set_for_each_callback_args ||
9084             !map->ops->map_for_each_callback) {
9085                 verbose(env, "callback function not allowed for map\n");
9086                 return -ENOTSUPP;
9087         }
9088
9089         err = map->ops->map_set_for_each_callback_args(env, caller, callee);
9090         if (err)
9091                 return err;
9092
9093         callee->in_callback_fn = true;
9094         callee->callback_ret_range = tnum_range(0, 1);
9095         return 0;
9096 }
9097
9098 static int set_loop_callback_state(struct bpf_verifier_env *env,
9099                                    struct bpf_func_state *caller,
9100                                    struct bpf_func_state *callee,
9101                                    int insn_idx)
9102 {
9103         /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx,
9104          *          u64 flags);
9105          * callback_fn(u32 index, void *callback_ctx);
9106          */
9107         callee->regs[BPF_REG_1].type = SCALAR_VALUE;
9108         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9109
9110         /* unused */
9111         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9112         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9113         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9114
9115         callee->in_callback_fn = true;
9116         callee->callback_ret_range = tnum_range(0, 1);
9117         return 0;
9118 }
9119
9120 static int set_timer_callback_state(struct bpf_verifier_env *env,
9121                                     struct bpf_func_state *caller,
9122                                     struct bpf_func_state *callee,
9123                                     int insn_idx)
9124 {
9125         struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr;
9126
9127         /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn);
9128          * callback_fn(struct bpf_map *map, void *key, void *value);
9129          */
9130         callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP;
9131         __mark_reg_known_zero(&callee->regs[BPF_REG_1]);
9132         callee->regs[BPF_REG_1].map_ptr = map_ptr;
9133
9134         callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY;
9135         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9136         callee->regs[BPF_REG_2].map_ptr = map_ptr;
9137
9138         callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE;
9139         __mark_reg_known_zero(&callee->regs[BPF_REG_3]);
9140         callee->regs[BPF_REG_3].map_ptr = map_ptr;
9141
9142         /* unused */
9143         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9144         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9145         callee->in_async_callback_fn = true;
9146         callee->callback_ret_range = tnum_range(0, 1);
9147         return 0;
9148 }
9149
9150 static int set_find_vma_callback_state(struct bpf_verifier_env *env,
9151                                        struct bpf_func_state *caller,
9152                                        struct bpf_func_state *callee,
9153                                        int insn_idx)
9154 {
9155         /* bpf_find_vma(struct task_struct *task, u64 addr,
9156          *               void *callback_fn, void *callback_ctx, u64 flags)
9157          * (callback_fn)(struct task_struct *task,
9158          *               struct vm_area_struct *vma, void *callback_ctx);
9159          */
9160         callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
9161
9162         callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
9163         __mark_reg_known_zero(&callee->regs[BPF_REG_2]);
9164         callee->regs[BPF_REG_2].btf =  btf_vmlinux;
9165         callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA],
9166
9167         /* pointer to stack or null */
9168         callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4];
9169
9170         /* unused */
9171         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9172         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9173         callee->in_callback_fn = true;
9174         callee->callback_ret_range = tnum_range(0, 1);
9175         return 0;
9176 }
9177
9178 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env,
9179                                            struct bpf_func_state *caller,
9180                                            struct bpf_func_state *callee,
9181                                            int insn_idx)
9182 {
9183         /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void
9184          *                        callback_ctx, u64 flags);
9185          * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx);
9186          */
9187         __mark_reg_not_init(env, &callee->regs[BPF_REG_0]);
9188         mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL);
9189         callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3];
9190
9191         /* unused */
9192         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9193         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9194         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9195
9196         callee->in_callback_fn = true;
9197         callee->callback_ret_range = tnum_range(0, 1);
9198         return 0;
9199 }
9200
9201 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env,
9202                                          struct bpf_func_state *caller,
9203                                          struct bpf_func_state *callee,
9204                                          int insn_idx)
9205 {
9206         /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node,
9207          *                     bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b));
9208          *
9209          * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset
9210          * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd
9211          * by this point, so look at 'root'
9212          */
9213         struct btf_field *field;
9214
9215         field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off,
9216                                       BPF_RB_ROOT);
9217         if (!field || !field->graph_root.value_btf_id)
9218                 return -EFAULT;
9219
9220         mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root);
9221         ref_set_non_owning(env, &callee->regs[BPF_REG_1]);
9222         mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root);
9223         ref_set_non_owning(env, &callee->regs[BPF_REG_2]);
9224
9225         __mark_reg_not_init(env, &callee->regs[BPF_REG_3]);
9226         __mark_reg_not_init(env, &callee->regs[BPF_REG_4]);
9227         __mark_reg_not_init(env, &callee->regs[BPF_REG_5]);
9228         callee->in_callback_fn = true;
9229         callee->callback_ret_range = tnum_range(0, 1);
9230         return 0;
9231 }
9232
9233 static bool is_rbtree_lock_required_kfunc(u32 btf_id);
9234
9235 /* Are we currently verifying the callback for a rbtree helper that must
9236  * be called with lock held? If so, no need to complain about unreleased
9237  * lock
9238  */
9239 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env)
9240 {
9241         struct bpf_verifier_state *state = env->cur_state;
9242         struct bpf_insn *insn = env->prog->insnsi;
9243         struct bpf_func_state *callee;
9244         int kfunc_btf_id;
9245
9246         if (!state->curframe)
9247                 return false;
9248
9249         callee = state->frame[state->curframe];
9250
9251         if (!callee->in_callback_fn)
9252                 return false;
9253
9254         kfunc_btf_id = insn[callee->callsite].imm;
9255         return is_rbtree_lock_required_kfunc(kfunc_btf_id);
9256 }
9257
9258 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
9259 {
9260         struct bpf_verifier_state *state = env->cur_state;
9261         struct bpf_func_state *caller, *callee;
9262         struct bpf_reg_state *r0;
9263         int err;
9264
9265         callee = state->frame[state->curframe];
9266         r0 = &callee->regs[BPF_REG_0];
9267         if (r0->type == PTR_TO_STACK) {
9268                 /* technically it's ok to return caller's stack pointer
9269                  * (or caller's caller's pointer) back to the caller,
9270                  * since these pointers are valid. Only current stack
9271                  * pointer will be invalid as soon as function exits,
9272                  * but let's be conservative
9273                  */
9274                 verbose(env, "cannot return stack pointer to the caller\n");
9275                 return -EINVAL;
9276         }
9277
9278         caller = state->frame[state->curframe - 1];
9279         if (callee->in_callback_fn) {
9280                 /* enforce R0 return value range [0, 1]. */
9281                 struct tnum range = callee->callback_ret_range;
9282
9283                 if (r0->type != SCALAR_VALUE) {
9284                         verbose(env, "R0 not a scalar value\n");
9285                         return -EACCES;
9286                 }
9287
9288                 /* we are going to rely on register's precise value */
9289                 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64);
9290                 err = err ?: mark_chain_precision(env, BPF_REG_0);
9291                 if (err)
9292                         return err;
9293
9294                 if (!tnum_in(range, r0->var_off)) {
9295                         verbose_invalid_scalar(env, r0, &range, "callback return", "R0");
9296                         return -EINVAL;
9297                 }
9298         } else {
9299                 /* return to the caller whatever r0 had in the callee */
9300                 caller->regs[BPF_REG_0] = *r0;
9301         }
9302
9303         /* callback_fn frame should have released its own additions to parent's
9304          * reference state at this point, or check_reference_leak would
9305          * complain, hence it must be the same as the caller. There is no need
9306          * to copy it back.
9307          */
9308         if (!callee->in_callback_fn) {
9309                 /* Transfer references to the caller */
9310                 err = copy_reference_state(caller, callee);
9311                 if (err)
9312                         return err;
9313         }
9314
9315         *insn_idx = callee->callsite + 1;
9316         if (env->log.level & BPF_LOG_LEVEL) {
9317                 verbose(env, "returning from callee:\n");
9318                 print_verifier_state(env, callee, true);
9319                 verbose(env, "to caller at %d:\n", *insn_idx);
9320                 print_verifier_state(env, caller, true);
9321         }
9322         /* clear everything in the callee */
9323         free_func_state(callee);
9324         state->frame[state->curframe--] = NULL;
9325         return 0;
9326 }
9327
9328 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type,
9329                                    int func_id,
9330                                    struct bpf_call_arg_meta *meta)
9331 {
9332         struct bpf_reg_state *ret_reg = &regs[BPF_REG_0];
9333
9334         if (ret_type != RET_INTEGER)
9335                 return;
9336
9337         switch (func_id) {
9338         case BPF_FUNC_get_stack:
9339         case BPF_FUNC_get_task_stack:
9340         case BPF_FUNC_probe_read_str:
9341         case BPF_FUNC_probe_read_kernel_str:
9342         case BPF_FUNC_probe_read_user_str:
9343                 ret_reg->smax_value = meta->msize_max_value;
9344                 ret_reg->s32_max_value = meta->msize_max_value;
9345                 ret_reg->smin_value = -MAX_ERRNO;
9346                 ret_reg->s32_min_value = -MAX_ERRNO;
9347                 reg_bounds_sync(ret_reg);
9348                 break;
9349         case BPF_FUNC_get_smp_processor_id:
9350                 ret_reg->umax_value = nr_cpu_ids - 1;
9351                 ret_reg->u32_max_value = nr_cpu_ids - 1;
9352                 ret_reg->smax_value = nr_cpu_ids - 1;
9353                 ret_reg->s32_max_value = nr_cpu_ids - 1;
9354                 ret_reg->umin_value = 0;
9355                 ret_reg->u32_min_value = 0;
9356                 ret_reg->smin_value = 0;
9357                 ret_reg->s32_min_value = 0;
9358                 reg_bounds_sync(ret_reg);
9359                 break;
9360         }
9361 }
9362
9363 static int
9364 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9365                 int func_id, int insn_idx)
9366 {
9367         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9368         struct bpf_map *map = meta->map_ptr;
9369
9370         if (func_id != BPF_FUNC_tail_call &&
9371             func_id != BPF_FUNC_map_lookup_elem &&
9372             func_id != BPF_FUNC_map_update_elem &&
9373             func_id != BPF_FUNC_map_delete_elem &&
9374             func_id != BPF_FUNC_map_push_elem &&
9375             func_id != BPF_FUNC_map_pop_elem &&
9376             func_id != BPF_FUNC_map_peek_elem &&
9377             func_id != BPF_FUNC_for_each_map_elem &&
9378             func_id != BPF_FUNC_redirect_map &&
9379             func_id != BPF_FUNC_map_lookup_percpu_elem)
9380                 return 0;
9381
9382         if (map == NULL) {
9383                 verbose(env, "kernel subsystem misconfigured verifier\n");
9384                 return -EINVAL;
9385         }
9386
9387         /* In case of read-only, some additional restrictions
9388          * need to be applied in order to prevent altering the
9389          * state of the map from program side.
9390          */
9391         if ((map->map_flags & BPF_F_RDONLY_PROG) &&
9392             (func_id == BPF_FUNC_map_delete_elem ||
9393              func_id == BPF_FUNC_map_update_elem ||
9394              func_id == BPF_FUNC_map_push_elem ||
9395              func_id == BPF_FUNC_map_pop_elem)) {
9396                 verbose(env, "write into map forbidden\n");
9397                 return -EACCES;
9398         }
9399
9400         if (!BPF_MAP_PTR(aux->map_ptr_state))
9401                 bpf_map_ptr_store(aux, meta->map_ptr,
9402                                   !meta->map_ptr->bypass_spec_v1);
9403         else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr)
9404                 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON,
9405                                   !meta->map_ptr->bypass_spec_v1);
9406         return 0;
9407 }
9408
9409 static int
9410 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta,
9411                 int func_id, int insn_idx)
9412 {
9413         struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
9414         struct bpf_reg_state *regs = cur_regs(env), *reg;
9415         struct bpf_map *map = meta->map_ptr;
9416         u64 val, max;
9417         int err;
9418
9419         if (func_id != BPF_FUNC_tail_call)
9420                 return 0;
9421         if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) {
9422                 verbose(env, "kernel subsystem misconfigured verifier\n");
9423                 return -EINVAL;
9424         }
9425
9426         reg = &regs[BPF_REG_3];
9427         val = reg->var_off.value;
9428         max = map->max_entries;
9429
9430         if (!(register_is_const(reg) && val < max)) {
9431                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9432                 return 0;
9433         }
9434
9435         err = mark_chain_precision(env, BPF_REG_3);
9436         if (err)
9437                 return err;
9438         if (bpf_map_key_unseen(aux))
9439                 bpf_map_key_store(aux, val);
9440         else if (!bpf_map_key_poisoned(aux) &&
9441                   bpf_map_key_immediate(aux) != val)
9442                 bpf_map_key_store(aux, BPF_MAP_KEY_POISON);
9443         return 0;
9444 }
9445
9446 static int check_reference_leak(struct bpf_verifier_env *env)
9447 {
9448         struct bpf_func_state *state = cur_func(env);
9449         bool refs_lingering = false;
9450         int i;
9451
9452         if (state->frameno && !state->in_callback_fn)
9453                 return 0;
9454
9455         for (i = 0; i < state->acquired_refs; i++) {
9456                 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno)
9457                         continue;
9458                 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n",
9459                         state->refs[i].id, state->refs[i].insn_idx);
9460                 refs_lingering = true;
9461         }
9462         return refs_lingering ? -EINVAL : 0;
9463 }
9464
9465 static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
9466                                    struct bpf_reg_state *regs)
9467 {
9468         struct bpf_reg_state *fmt_reg = &regs[BPF_REG_3];
9469         struct bpf_reg_state *data_len_reg = &regs[BPF_REG_5];
9470         struct bpf_map *fmt_map = fmt_reg->map_ptr;
9471         struct bpf_bprintf_data data = {};
9472         int err, fmt_map_off, num_args;
9473         u64 fmt_addr;
9474         char *fmt;
9475
9476         /* data must be an array of u64 */
9477         if (data_len_reg->var_off.value % 8)
9478                 return -EINVAL;
9479         num_args = data_len_reg->var_off.value / 8;
9480
9481         /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
9482          * and map_direct_value_addr is set.
9483          */
9484         fmt_map_off = fmt_reg->off + fmt_reg->var_off.value;
9485         err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
9486                                                   fmt_map_off);
9487         if (err) {
9488                 verbose(env, "verifier bug\n");
9489                 return -EFAULT;
9490         }
9491         fmt = (char *)(long)fmt_addr + fmt_map_off;
9492
9493         /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we
9494          * can focus on validating the format specifiers.
9495          */
9496         err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data);
9497         if (err < 0)
9498                 verbose(env, "Invalid format string\n");
9499
9500         return err;
9501 }
9502
9503 static int check_get_func_ip(struct bpf_verifier_env *env)
9504 {
9505         enum bpf_prog_type type = resolve_prog_type(env->prog);
9506         int func_id = BPF_FUNC_get_func_ip;
9507
9508         if (type == BPF_PROG_TYPE_TRACING) {
9509                 if (!bpf_prog_has_trampoline(env->prog)) {
9510                         verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n",
9511                                 func_id_name(func_id), func_id);
9512                         return -ENOTSUPP;
9513                 }
9514                 return 0;
9515         } else if (type == BPF_PROG_TYPE_KPROBE) {
9516                 return 0;
9517         }
9518
9519         verbose(env, "func %s#%d not supported for program type %d\n",
9520                 func_id_name(func_id), func_id, type);
9521         return -ENOTSUPP;
9522 }
9523
9524 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env)
9525 {
9526         return &env->insn_aux_data[env->insn_idx];
9527 }
9528
9529 static bool loop_flag_is_zero(struct bpf_verifier_env *env)
9530 {
9531         struct bpf_reg_state *regs = cur_regs(env);
9532         struct bpf_reg_state *reg = &regs[BPF_REG_4];
9533         bool reg_is_null = register_is_null(reg);
9534
9535         if (reg_is_null)
9536                 mark_chain_precision(env, BPF_REG_4);
9537
9538         return reg_is_null;
9539 }
9540
9541 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno)
9542 {
9543         struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state;
9544
9545         if (!state->initialized) {
9546                 state->initialized = 1;
9547                 state->fit_for_inline = loop_flag_is_zero(env);
9548                 state->callback_subprogno = subprogno;
9549                 return;
9550         }
9551
9552         if (!state->fit_for_inline)
9553                 return;
9554
9555         state->fit_for_inline = (loop_flag_is_zero(env) &&
9556                                  state->callback_subprogno == subprogno);
9557 }
9558
9559 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
9560                              int *insn_idx_p)
9561 {
9562         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
9563         const struct bpf_func_proto *fn = NULL;
9564         enum bpf_return_type ret_type;
9565         enum bpf_type_flag ret_flag;
9566         struct bpf_reg_state *regs;
9567         struct bpf_call_arg_meta meta;
9568         int insn_idx = *insn_idx_p;
9569         bool changes_data;
9570         int i, err, func_id;
9571
9572         /* find function prototype */
9573         func_id = insn->imm;
9574         if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) {
9575                 verbose(env, "invalid func %s#%d\n", func_id_name(func_id),
9576                         func_id);
9577                 return -EINVAL;
9578         }
9579
9580         if (env->ops->get_func_proto)
9581                 fn = env->ops->get_func_proto(func_id, env->prog);
9582         if (!fn) {
9583                 verbose(env, "unknown func %s#%d\n", func_id_name(func_id),
9584                         func_id);
9585                 return -EINVAL;
9586         }
9587
9588         /* eBPF programs must be GPL compatible to use GPL-ed functions */
9589         if (!env->prog->gpl_compatible && fn->gpl_only) {
9590                 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
9591                 return -EINVAL;
9592         }
9593
9594         if (fn->allowed && !fn->allowed(env->prog)) {
9595                 verbose(env, "helper call is not allowed in probe\n");
9596                 return -EINVAL;
9597         }
9598
9599         if (!env->prog->aux->sleepable && fn->might_sleep) {
9600                 verbose(env, "helper call might sleep in a non-sleepable prog\n");
9601                 return -EINVAL;
9602         }
9603
9604         /* With LD_ABS/IND some JITs save/restore skb from r1. */
9605         changes_data = bpf_helper_changes_pkt_data(fn->func);
9606         if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) {
9607                 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n",
9608                         func_id_name(func_id), func_id);
9609                 return -EINVAL;
9610         }
9611
9612         memset(&meta, 0, sizeof(meta));
9613         meta.pkt_access = fn->pkt_access;
9614
9615         err = check_func_proto(fn, func_id);
9616         if (err) {
9617                 verbose(env, "kernel subsystem misconfigured func %s#%d\n",
9618                         func_id_name(func_id), func_id);
9619                 return err;
9620         }
9621
9622         if (env->cur_state->active_rcu_lock) {
9623                 if (fn->might_sleep) {
9624                         verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n",
9625                                 func_id_name(func_id), func_id);
9626                         return -EINVAL;
9627                 }
9628
9629                 if (env->prog->aux->sleepable && is_storage_get_function(func_id))
9630                         env->insn_aux_data[insn_idx].storage_get_func_atomic = true;
9631         }
9632
9633         meta.func_id = func_id;
9634         /* check args */
9635         for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
9636                 err = check_func_arg(env, i, &meta, fn, insn_idx);
9637                 if (err)
9638                         return err;
9639         }
9640
9641         err = record_func_map(env, &meta, func_id, insn_idx);
9642         if (err)
9643                 return err;
9644
9645         err = record_func_key(env, &meta, func_id, insn_idx);
9646         if (err)
9647                 return err;
9648
9649         /* Mark slots with STACK_MISC in case of raw mode, stack offset
9650          * is inferred from register state.
9651          */
9652         for (i = 0; i < meta.access_size; i++) {
9653                 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B,
9654                                        BPF_WRITE, -1, false, false);
9655                 if (err)
9656                         return err;
9657         }
9658
9659         regs = cur_regs(env);
9660
9661         if (meta.release_regno) {
9662                 err = -EINVAL;
9663                 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
9664                  * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
9665                  * is safe to do directly.
9666                  */
9667                 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
9668                         if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
9669                                 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n");
9670                                 return -EFAULT;
9671                         }
9672                         err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
9673                 } else if (meta.ref_obj_id) {
9674                         err = release_reference(env, meta.ref_obj_id);
9675                 } else if (register_is_null(&regs[meta.release_regno])) {
9676                         /* meta.ref_obj_id can only be 0 if register that is meant to be
9677                          * released is NULL, which must be > R0.
9678                          */
9679                         err = 0;
9680                 }
9681                 if (err) {
9682                         verbose(env, "func %s#%d reference has not been acquired before\n",
9683                                 func_id_name(func_id), func_id);
9684                         return err;
9685                 }
9686         }
9687
9688         switch (func_id) {
9689         case BPF_FUNC_tail_call:
9690                 err = check_reference_leak(env);
9691                 if (err) {
9692                         verbose(env, "tail_call would lead to reference leak\n");
9693                         return err;
9694                 }
9695                 break;
9696         case BPF_FUNC_get_local_storage:
9697                 /* check that flags argument in get_local_storage(map, flags) is 0,
9698                  * this is required because get_local_storage() can't return an error.
9699                  */
9700                 if (!register_is_null(&regs[BPF_REG_2])) {
9701                         verbose(env, "get_local_storage() doesn't support non-zero flags\n");
9702                         return -EINVAL;
9703                 }
9704                 break;
9705         case BPF_FUNC_for_each_map_elem:
9706                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9707                                         set_map_elem_callback_state);
9708                 break;
9709         case BPF_FUNC_timer_set_callback:
9710                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9711                                         set_timer_callback_state);
9712                 break;
9713         case BPF_FUNC_find_vma:
9714                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9715                                         set_find_vma_callback_state);
9716                 break;
9717         case BPF_FUNC_snprintf:
9718                 err = check_bpf_snprintf_call(env, regs);
9719                 break;
9720         case BPF_FUNC_loop:
9721                 update_loop_inline_state(env, meta.subprogno);
9722                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9723                                         set_loop_callback_state);
9724                 break;
9725         case BPF_FUNC_dynptr_from_mem:
9726                 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) {
9727                         verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n",
9728                                 reg_type_str(env, regs[BPF_REG_1].type));
9729                         return -EACCES;
9730                 }
9731                 break;
9732         case BPF_FUNC_set_retval:
9733                 if (prog_type == BPF_PROG_TYPE_LSM &&
9734                     env->prog->expected_attach_type == BPF_LSM_CGROUP) {
9735                         if (!env->prog->aux->attach_func_proto->type) {
9736                                 /* Make sure programs that attach to void
9737                                  * hooks don't try to modify return value.
9738                                  */
9739                                 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
9740                                 return -EINVAL;
9741                         }
9742                 }
9743                 break;
9744         case BPF_FUNC_dynptr_data:
9745         {
9746                 struct bpf_reg_state *reg;
9747                 int id, ref_obj_id;
9748
9749                 reg = get_dynptr_arg_reg(env, fn, regs);
9750                 if (!reg)
9751                         return -EFAULT;
9752
9753
9754                 if (meta.dynptr_id) {
9755                         verbose(env, "verifier internal error: meta.dynptr_id already set\n");
9756                         return -EFAULT;
9757                 }
9758                 if (meta.ref_obj_id) {
9759                         verbose(env, "verifier internal error: meta.ref_obj_id already set\n");
9760                         return -EFAULT;
9761                 }
9762
9763                 id = dynptr_id(env, reg);
9764                 if (id < 0) {
9765                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
9766                         return id;
9767                 }
9768
9769                 ref_obj_id = dynptr_ref_obj_id(env, reg);
9770                 if (ref_obj_id < 0) {
9771                         verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n");
9772                         return ref_obj_id;
9773                 }
9774
9775                 meta.dynptr_id = id;
9776                 meta.ref_obj_id = ref_obj_id;
9777
9778                 break;
9779         }
9780         case BPF_FUNC_dynptr_write:
9781         {
9782                 enum bpf_dynptr_type dynptr_type;
9783                 struct bpf_reg_state *reg;
9784
9785                 reg = get_dynptr_arg_reg(env, fn, regs);
9786                 if (!reg)
9787                         return -EFAULT;
9788
9789                 dynptr_type = dynptr_get_type(env, reg);
9790                 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID)
9791                         return -EFAULT;
9792
9793                 if (dynptr_type == BPF_DYNPTR_TYPE_SKB)
9794                         /* this will trigger clear_all_pkt_pointers(), which will
9795                          * invalidate all dynptr slices associated with the skb
9796                          */
9797                         changes_data = true;
9798
9799                 break;
9800         }
9801         case BPF_FUNC_user_ringbuf_drain:
9802                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
9803                                         set_user_ringbuf_callback_state);
9804                 break;
9805         }
9806
9807         if (err)
9808                 return err;
9809
9810         /* reset caller saved regs */
9811         for (i = 0; i < CALLER_SAVED_REGS; i++) {
9812                 mark_reg_not_init(env, regs, caller_saved[i]);
9813                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
9814         }
9815
9816         /* helper call returns 64-bit value. */
9817         regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG;
9818
9819         /* update return register (already marked as written above) */
9820         ret_type = fn->ret_type;
9821         ret_flag = type_flag(ret_type);
9822
9823         switch (base_type(ret_type)) {
9824         case RET_INTEGER:
9825                 /* sets type to SCALAR_VALUE */
9826                 mark_reg_unknown(env, regs, BPF_REG_0);
9827                 break;
9828         case RET_VOID:
9829                 regs[BPF_REG_0].type = NOT_INIT;
9830                 break;
9831         case RET_PTR_TO_MAP_VALUE:
9832                 /* There is no offset yet applied, variable or fixed */
9833                 mark_reg_known_zero(env, regs, BPF_REG_0);
9834                 /* remember map_ptr, so that check_map_access()
9835                  * can check 'value_size' boundary of memory access
9836                  * to map element returned from bpf_map_lookup_elem()
9837                  */
9838                 if (meta.map_ptr == NULL) {
9839                         verbose(env,
9840                                 "kernel subsystem misconfigured verifier\n");
9841                         return -EINVAL;
9842                 }
9843                 regs[BPF_REG_0].map_ptr = meta.map_ptr;
9844                 regs[BPF_REG_0].map_uid = meta.map_uid;
9845                 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag;
9846                 if (!type_may_be_null(ret_type) &&
9847                     btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) {
9848                         regs[BPF_REG_0].id = ++env->id_gen;
9849                 }
9850                 break;
9851         case RET_PTR_TO_SOCKET:
9852                 mark_reg_known_zero(env, regs, BPF_REG_0);
9853                 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag;
9854                 break;
9855         case RET_PTR_TO_SOCK_COMMON:
9856                 mark_reg_known_zero(env, regs, BPF_REG_0);
9857                 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag;
9858                 break;
9859         case RET_PTR_TO_TCP_SOCK:
9860                 mark_reg_known_zero(env, regs, BPF_REG_0);
9861                 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag;
9862                 break;
9863         case RET_PTR_TO_MEM:
9864                 mark_reg_known_zero(env, regs, BPF_REG_0);
9865                 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9866                 regs[BPF_REG_0].mem_size = meta.mem_size;
9867                 break;
9868         case RET_PTR_TO_MEM_OR_BTF_ID:
9869         {
9870                 const struct btf_type *t;
9871
9872                 mark_reg_known_zero(env, regs, BPF_REG_0);
9873                 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL);
9874                 if (!btf_type_is_struct(t)) {
9875                         u32 tsize;
9876                         const struct btf_type *ret;
9877                         const char *tname;
9878
9879                         /* resolve the type size of ksym. */
9880                         ret = btf_resolve_size(meta.ret_btf, t, &tsize);
9881                         if (IS_ERR(ret)) {
9882                                 tname = btf_name_by_offset(meta.ret_btf, t->name_off);
9883                                 verbose(env, "unable to resolve the size of type '%s': %ld\n",
9884                                         tname, PTR_ERR(ret));
9885                                 return -EINVAL;
9886                         }
9887                         regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag;
9888                         regs[BPF_REG_0].mem_size = tsize;
9889                 } else {
9890                         /* MEM_RDONLY may be carried from ret_flag, but it
9891                          * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise
9892                          * it will confuse the check of PTR_TO_BTF_ID in
9893                          * check_mem_access().
9894                          */
9895                         ret_flag &= ~MEM_RDONLY;
9896
9897                         regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9898                         regs[BPF_REG_0].btf = meta.ret_btf;
9899                         regs[BPF_REG_0].btf_id = meta.ret_btf_id;
9900                 }
9901                 break;
9902         }
9903         case RET_PTR_TO_BTF_ID:
9904         {
9905                 struct btf *ret_btf;
9906                 int ret_btf_id;
9907
9908                 mark_reg_known_zero(env, regs, BPF_REG_0);
9909                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag;
9910                 if (func_id == BPF_FUNC_kptr_xchg) {
9911                         ret_btf = meta.kptr_field->kptr.btf;
9912                         ret_btf_id = meta.kptr_field->kptr.btf_id;
9913                         if (!btf_is_kernel(ret_btf))
9914                                 regs[BPF_REG_0].type |= MEM_ALLOC;
9915                 } else {
9916                         if (fn->ret_btf_id == BPF_PTR_POISON) {
9917                                 verbose(env, "verifier internal error:");
9918                                 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n",
9919                                         func_id_name(func_id));
9920                                 return -EINVAL;
9921                         }
9922                         ret_btf = btf_vmlinux;
9923                         ret_btf_id = *fn->ret_btf_id;
9924                 }
9925                 if (ret_btf_id == 0) {
9926                         verbose(env, "invalid return type %u of func %s#%d\n",
9927                                 base_type(ret_type), func_id_name(func_id),
9928                                 func_id);
9929                         return -EINVAL;
9930                 }
9931                 regs[BPF_REG_0].btf = ret_btf;
9932                 regs[BPF_REG_0].btf_id = ret_btf_id;
9933                 break;
9934         }
9935         default:
9936                 verbose(env, "unknown return type %u of func %s#%d\n",
9937                         base_type(ret_type), func_id_name(func_id), func_id);
9938                 return -EINVAL;
9939         }
9940
9941         if (type_may_be_null(regs[BPF_REG_0].type))
9942                 regs[BPF_REG_0].id = ++env->id_gen;
9943
9944         if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) {
9945                 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n",
9946                         func_id_name(func_id), func_id);
9947                 return -EFAULT;
9948         }
9949
9950         if (is_dynptr_ref_function(func_id))
9951                 regs[BPF_REG_0].dynptr_id = meta.dynptr_id;
9952
9953         if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) {
9954                 /* For release_reference() */
9955                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
9956         } else if (is_acquire_function(func_id, meta.map_ptr)) {
9957                 int id = acquire_reference_state(env, insn_idx);
9958
9959                 if (id < 0)
9960                         return id;
9961                 /* For mark_ptr_or_null_reg() */
9962                 regs[BPF_REG_0].id = id;
9963                 /* For release_reference() */
9964                 regs[BPF_REG_0].ref_obj_id = id;
9965         }
9966
9967         do_refine_retval_range(regs, fn->ret_type, func_id, &meta);
9968
9969         err = check_map_func_compatibility(env, meta.map_ptr, func_id);
9970         if (err)
9971                 return err;
9972
9973         if ((func_id == BPF_FUNC_get_stack ||
9974              func_id == BPF_FUNC_get_task_stack) &&
9975             !env->prog->has_callchain_buf) {
9976                 const char *err_str;
9977
9978 #ifdef CONFIG_PERF_EVENTS
9979                 err = get_callchain_buffers(sysctl_perf_event_max_stack);
9980                 err_str = "cannot get callchain buffer for func %s#%d\n";
9981 #else
9982                 err = -ENOTSUPP;
9983                 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n";
9984 #endif
9985                 if (err) {
9986                         verbose(env, err_str, func_id_name(func_id), func_id);
9987                         return err;
9988                 }
9989
9990                 env->prog->has_callchain_buf = true;
9991         }
9992
9993         if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack)
9994                 env->prog->call_get_stack = true;
9995
9996         if (func_id == BPF_FUNC_get_func_ip) {
9997                 if (check_get_func_ip(env))
9998                         return -ENOTSUPP;
9999                 env->prog->call_get_func_ip = true;
10000         }
10001
10002         if (changes_data)
10003                 clear_all_pkt_pointers(env);
10004         return 0;
10005 }
10006
10007 /* mark_btf_func_reg_size() is used when the reg size is determined by
10008  * the BTF func_proto's return value size and argument.
10009  */
10010 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno,
10011                                    size_t reg_size)
10012 {
10013         struct bpf_reg_state *reg = &cur_regs(env)[regno];
10014
10015         if (regno == BPF_REG_0) {
10016                 /* Function return value */
10017                 reg->live |= REG_LIVE_WRITTEN;
10018                 reg->subreg_def = reg_size == sizeof(u64) ?
10019                         DEF_NOT_SUBREG : env->insn_idx + 1;
10020         } else {
10021                 /* Function argument */
10022                 if (reg_size == sizeof(u64)) {
10023                         mark_insn_zext(env, reg);
10024                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64);
10025                 } else {
10026                         mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32);
10027                 }
10028         }
10029 }
10030
10031 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta)
10032 {
10033         return meta->kfunc_flags & KF_ACQUIRE;
10034 }
10035
10036 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta)
10037 {
10038         return meta->kfunc_flags & KF_RELEASE;
10039 }
10040
10041 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta)
10042 {
10043         return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta);
10044 }
10045
10046 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta)
10047 {
10048         return meta->kfunc_flags & KF_SLEEPABLE;
10049 }
10050
10051 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta)
10052 {
10053         return meta->kfunc_flags & KF_DESTRUCTIVE;
10054 }
10055
10056 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta)
10057 {
10058         return meta->kfunc_flags & KF_RCU;
10059 }
10060
10061 static bool __kfunc_param_match_suffix(const struct btf *btf,
10062                                        const struct btf_param *arg,
10063                                        const char *suffix)
10064 {
10065         int suffix_len = strlen(suffix), len;
10066         const char *param_name;
10067
10068         /* In the future, this can be ported to use BTF tagging */
10069         param_name = btf_name_by_offset(btf, arg->name_off);
10070         if (str_is_empty(param_name))
10071                 return false;
10072         len = strlen(param_name);
10073         if (len < suffix_len)
10074                 return false;
10075         param_name += len - suffix_len;
10076         return !strncmp(param_name, suffix, suffix_len);
10077 }
10078
10079 static bool is_kfunc_arg_mem_size(const struct btf *btf,
10080                                   const struct btf_param *arg,
10081                                   const struct bpf_reg_state *reg)
10082 {
10083         const struct btf_type *t;
10084
10085         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10086         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10087                 return false;
10088
10089         return __kfunc_param_match_suffix(btf, arg, "__sz");
10090 }
10091
10092 static bool is_kfunc_arg_const_mem_size(const struct btf *btf,
10093                                         const struct btf_param *arg,
10094                                         const struct bpf_reg_state *reg)
10095 {
10096         const struct btf_type *t;
10097
10098         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10099         if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE)
10100                 return false;
10101
10102         return __kfunc_param_match_suffix(btf, arg, "__szk");
10103 }
10104
10105 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg)
10106 {
10107         return __kfunc_param_match_suffix(btf, arg, "__opt");
10108 }
10109
10110 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg)
10111 {
10112         return __kfunc_param_match_suffix(btf, arg, "__k");
10113 }
10114
10115 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg)
10116 {
10117         return __kfunc_param_match_suffix(btf, arg, "__ign");
10118 }
10119
10120 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg)
10121 {
10122         return __kfunc_param_match_suffix(btf, arg, "__alloc");
10123 }
10124
10125 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg)
10126 {
10127         return __kfunc_param_match_suffix(btf, arg, "__uninit");
10128 }
10129
10130 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg)
10131 {
10132         return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr");
10133 }
10134
10135 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf,
10136                                           const struct btf_param *arg,
10137                                           const char *name)
10138 {
10139         int len, target_len = strlen(name);
10140         const char *param_name;
10141
10142         param_name = btf_name_by_offset(btf, arg->name_off);
10143         if (str_is_empty(param_name))
10144                 return false;
10145         len = strlen(param_name);
10146         if (len != target_len)
10147                 return false;
10148         if (strcmp(param_name, name))
10149                 return false;
10150
10151         return true;
10152 }
10153
10154 enum {
10155         KF_ARG_DYNPTR_ID,
10156         KF_ARG_LIST_HEAD_ID,
10157         KF_ARG_LIST_NODE_ID,
10158         KF_ARG_RB_ROOT_ID,
10159         KF_ARG_RB_NODE_ID,
10160 };
10161
10162 BTF_ID_LIST(kf_arg_btf_ids)
10163 BTF_ID(struct, bpf_dynptr_kern)
10164 BTF_ID(struct, bpf_list_head)
10165 BTF_ID(struct, bpf_list_node)
10166 BTF_ID(struct, bpf_rb_root)
10167 BTF_ID(struct, bpf_rb_node)
10168
10169 static bool __is_kfunc_ptr_arg_type(const struct btf *btf,
10170                                     const struct btf_param *arg, int type)
10171 {
10172         const struct btf_type *t;
10173         u32 res_id;
10174
10175         t = btf_type_skip_modifiers(btf, arg->type, NULL);
10176         if (!t)
10177                 return false;
10178         if (!btf_type_is_ptr(t))
10179                 return false;
10180         t = btf_type_skip_modifiers(btf, t->type, &res_id);
10181         if (!t)
10182                 return false;
10183         return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]);
10184 }
10185
10186 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg)
10187 {
10188         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID);
10189 }
10190
10191 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg)
10192 {
10193         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID);
10194 }
10195
10196 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg)
10197 {
10198         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID);
10199 }
10200
10201 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg)
10202 {
10203         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID);
10204 }
10205
10206 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg)
10207 {
10208         return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID);
10209 }
10210
10211 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf,
10212                                   const struct btf_param *arg)
10213 {
10214         const struct btf_type *t;
10215
10216         t = btf_type_resolve_func_ptr(btf, arg->type, NULL);
10217         if (!t)
10218                 return false;
10219
10220         return true;
10221 }
10222
10223 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */
10224 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env,
10225                                         const struct btf *btf,
10226                                         const struct btf_type *t, int rec)
10227 {
10228         const struct btf_type *member_type;
10229         const struct btf_member *member;
10230         u32 i;
10231
10232         if (!btf_type_is_struct(t))
10233                 return false;
10234
10235         for_each_member(i, t, member) {
10236                 const struct btf_array *array;
10237
10238                 member_type = btf_type_skip_modifiers(btf, member->type, NULL);
10239                 if (btf_type_is_struct(member_type)) {
10240                         if (rec >= 3) {
10241                                 verbose(env, "max struct nesting depth exceeded\n");
10242                                 return false;
10243                         }
10244                         if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1))
10245                                 return false;
10246                         continue;
10247                 }
10248                 if (btf_type_is_array(member_type)) {
10249                         array = btf_array(member_type);
10250                         if (!array->nelems)
10251                                 return false;
10252                         member_type = btf_type_skip_modifiers(btf, array->type, NULL);
10253                         if (!btf_type_is_scalar(member_type))
10254                                 return false;
10255                         continue;
10256                 }
10257                 if (!btf_type_is_scalar(member_type))
10258                         return false;
10259         }
10260         return true;
10261 }
10262
10263 enum kfunc_ptr_arg_type {
10264         KF_ARG_PTR_TO_CTX,
10265         KF_ARG_PTR_TO_ALLOC_BTF_ID,    /* Allocated object */
10266         KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */
10267         KF_ARG_PTR_TO_DYNPTR,
10268         KF_ARG_PTR_TO_ITER,
10269         KF_ARG_PTR_TO_LIST_HEAD,
10270         KF_ARG_PTR_TO_LIST_NODE,
10271         KF_ARG_PTR_TO_BTF_ID,          /* Also covers reg2btf_ids conversions */
10272         KF_ARG_PTR_TO_MEM,
10273         KF_ARG_PTR_TO_MEM_SIZE,        /* Size derived from next argument, skip it */
10274         KF_ARG_PTR_TO_CALLBACK,
10275         KF_ARG_PTR_TO_RB_ROOT,
10276         KF_ARG_PTR_TO_RB_NODE,
10277 };
10278
10279 enum special_kfunc_type {
10280         KF_bpf_obj_new_impl,
10281         KF_bpf_obj_drop_impl,
10282         KF_bpf_refcount_acquire_impl,
10283         KF_bpf_list_push_front_impl,
10284         KF_bpf_list_push_back_impl,
10285         KF_bpf_list_pop_front,
10286         KF_bpf_list_pop_back,
10287         KF_bpf_cast_to_kern_ctx,
10288         KF_bpf_rdonly_cast,
10289         KF_bpf_rcu_read_lock,
10290         KF_bpf_rcu_read_unlock,
10291         KF_bpf_rbtree_remove,
10292         KF_bpf_rbtree_add_impl,
10293         KF_bpf_rbtree_first,
10294         KF_bpf_dynptr_from_skb,
10295         KF_bpf_dynptr_from_xdp,
10296         KF_bpf_dynptr_slice,
10297         KF_bpf_dynptr_slice_rdwr,
10298         KF_bpf_dynptr_clone,
10299 };
10300
10301 BTF_SET_START(special_kfunc_set)
10302 BTF_ID(func, bpf_obj_new_impl)
10303 BTF_ID(func, bpf_obj_drop_impl)
10304 BTF_ID(func, bpf_refcount_acquire_impl)
10305 BTF_ID(func, bpf_list_push_front_impl)
10306 BTF_ID(func, bpf_list_push_back_impl)
10307 BTF_ID(func, bpf_list_pop_front)
10308 BTF_ID(func, bpf_list_pop_back)
10309 BTF_ID(func, bpf_cast_to_kern_ctx)
10310 BTF_ID(func, bpf_rdonly_cast)
10311 BTF_ID(func, bpf_rbtree_remove)
10312 BTF_ID(func, bpf_rbtree_add_impl)
10313 BTF_ID(func, bpf_rbtree_first)
10314 BTF_ID(func, bpf_dynptr_from_skb)
10315 BTF_ID(func, bpf_dynptr_from_xdp)
10316 BTF_ID(func, bpf_dynptr_slice)
10317 BTF_ID(func, bpf_dynptr_slice_rdwr)
10318 BTF_ID(func, bpf_dynptr_clone)
10319 BTF_SET_END(special_kfunc_set)
10320
10321 BTF_ID_LIST(special_kfunc_list)
10322 BTF_ID(func, bpf_obj_new_impl)
10323 BTF_ID(func, bpf_obj_drop_impl)
10324 BTF_ID(func, bpf_refcount_acquire_impl)
10325 BTF_ID(func, bpf_list_push_front_impl)
10326 BTF_ID(func, bpf_list_push_back_impl)
10327 BTF_ID(func, bpf_list_pop_front)
10328 BTF_ID(func, bpf_list_pop_back)
10329 BTF_ID(func, bpf_cast_to_kern_ctx)
10330 BTF_ID(func, bpf_rdonly_cast)
10331 BTF_ID(func, bpf_rcu_read_lock)
10332 BTF_ID(func, bpf_rcu_read_unlock)
10333 BTF_ID(func, bpf_rbtree_remove)
10334 BTF_ID(func, bpf_rbtree_add_impl)
10335 BTF_ID(func, bpf_rbtree_first)
10336 BTF_ID(func, bpf_dynptr_from_skb)
10337 BTF_ID(func, bpf_dynptr_from_xdp)
10338 BTF_ID(func, bpf_dynptr_slice)
10339 BTF_ID(func, bpf_dynptr_slice_rdwr)
10340 BTF_ID(func, bpf_dynptr_clone)
10341
10342 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta)
10343 {
10344         if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
10345             meta->arg_owning_ref) {
10346                 return false;
10347         }
10348
10349         return meta->kfunc_flags & KF_RET_NULL;
10350 }
10351
10352 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta)
10353 {
10354         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock];
10355 }
10356
10357 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta)
10358 {
10359         return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock];
10360 }
10361
10362 static enum kfunc_ptr_arg_type
10363 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env,
10364                        struct bpf_kfunc_call_arg_meta *meta,
10365                        const struct btf_type *t, const struct btf_type *ref_t,
10366                        const char *ref_tname, const struct btf_param *args,
10367                        int argno, int nargs)
10368 {
10369         u32 regno = argno + 1;
10370         struct bpf_reg_state *regs = cur_regs(env);
10371         struct bpf_reg_state *reg = &regs[regno];
10372         bool arg_mem_size = false;
10373
10374         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx])
10375                 return KF_ARG_PTR_TO_CTX;
10376
10377         /* In this function, we verify the kfunc's BTF as per the argument type,
10378          * leaving the rest of the verification with respect to the register
10379          * type to our caller. When a set of conditions hold in the BTF type of
10380          * arguments, we resolve it to a known kfunc_ptr_arg_type.
10381          */
10382         if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno))
10383                 return KF_ARG_PTR_TO_CTX;
10384
10385         if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno]))
10386                 return KF_ARG_PTR_TO_ALLOC_BTF_ID;
10387
10388         if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno]))
10389                 return KF_ARG_PTR_TO_REFCOUNTED_KPTR;
10390
10391         if (is_kfunc_arg_dynptr(meta->btf, &args[argno]))
10392                 return KF_ARG_PTR_TO_DYNPTR;
10393
10394         if (is_kfunc_arg_iter(meta, argno))
10395                 return KF_ARG_PTR_TO_ITER;
10396
10397         if (is_kfunc_arg_list_head(meta->btf, &args[argno]))
10398                 return KF_ARG_PTR_TO_LIST_HEAD;
10399
10400         if (is_kfunc_arg_list_node(meta->btf, &args[argno]))
10401                 return KF_ARG_PTR_TO_LIST_NODE;
10402
10403         if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno]))
10404                 return KF_ARG_PTR_TO_RB_ROOT;
10405
10406         if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno]))
10407                 return KF_ARG_PTR_TO_RB_NODE;
10408
10409         if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) {
10410                 if (!btf_type_is_struct(ref_t)) {
10411                         verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n",
10412                                 meta->func_name, argno, btf_type_str(ref_t), ref_tname);
10413                         return -EINVAL;
10414                 }
10415                 return KF_ARG_PTR_TO_BTF_ID;
10416         }
10417
10418         if (is_kfunc_arg_callback(env, meta->btf, &args[argno]))
10419                 return KF_ARG_PTR_TO_CALLBACK;
10420
10421
10422         if (argno + 1 < nargs &&
10423             (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1]) ||
10424              is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], &regs[regno + 1])))
10425                 arg_mem_size = true;
10426
10427         /* This is the catch all argument type of register types supported by
10428          * check_helper_mem_access. However, we only allow when argument type is
10429          * pointer to scalar, or struct composed (recursively) of scalars. When
10430          * arg_mem_size is true, the pointer can be void *.
10431          */
10432         if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) &&
10433             (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) {
10434                 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n",
10435                         argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : "");
10436                 return -EINVAL;
10437         }
10438         return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM;
10439 }
10440
10441 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env,
10442                                         struct bpf_reg_state *reg,
10443                                         const struct btf_type *ref_t,
10444                                         const char *ref_tname, u32 ref_id,
10445                                         struct bpf_kfunc_call_arg_meta *meta,
10446                                         int argno)
10447 {
10448         const struct btf_type *reg_ref_t;
10449         bool strict_type_match = false;
10450         const struct btf *reg_btf;
10451         const char *reg_ref_tname;
10452         u32 reg_ref_id;
10453
10454         if (base_type(reg->type) == PTR_TO_BTF_ID) {
10455                 reg_btf = reg->btf;
10456                 reg_ref_id = reg->btf_id;
10457         } else {
10458                 reg_btf = btf_vmlinux;
10459                 reg_ref_id = *reg2btf_ids[base_type(reg->type)];
10460         }
10461
10462         /* Enforce strict type matching for calls to kfuncs that are acquiring
10463          * or releasing a reference, or are no-cast aliases. We do _not_
10464          * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default,
10465          * as we want to enable BPF programs to pass types that are bitwise
10466          * equivalent without forcing them to explicitly cast with something
10467          * like bpf_cast_to_kern_ctx().
10468          *
10469          * For example, say we had a type like the following:
10470          *
10471          * struct bpf_cpumask {
10472          *      cpumask_t cpumask;
10473          *      refcount_t usage;
10474          * };
10475          *
10476          * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed
10477          * to a struct cpumask, so it would be safe to pass a struct
10478          * bpf_cpumask * to a kfunc expecting a struct cpumask *.
10479          *
10480          * The philosophy here is similar to how we allow scalars of different
10481          * types to be passed to kfuncs as long as the size is the same. The
10482          * only difference here is that we're simply allowing
10483          * btf_struct_ids_match() to walk the struct at the 0th offset, and
10484          * resolve types.
10485          */
10486         if (is_kfunc_acquire(meta) ||
10487             (is_kfunc_release(meta) && reg->ref_obj_id) ||
10488             btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id))
10489                 strict_type_match = true;
10490
10491         WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off);
10492
10493         reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, &reg_ref_id);
10494         reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off);
10495         if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) {
10496                 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n",
10497                         meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1,
10498                         btf_type_str(reg_ref_t), reg_ref_tname);
10499                 return -EINVAL;
10500         }
10501         return 0;
10502 }
10503
10504 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10505 {
10506         struct bpf_verifier_state *state = env->cur_state;
10507         struct btf_record *rec = reg_btf_record(reg);
10508
10509         if (!state->active_lock.ptr) {
10510                 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n");
10511                 return -EFAULT;
10512         }
10513
10514         if (type_flag(reg->type) & NON_OWN_REF) {
10515                 verbose(env, "verifier internal error: NON_OWN_REF already set\n");
10516                 return -EFAULT;
10517         }
10518
10519         reg->type |= NON_OWN_REF;
10520         if (rec->refcount_off >= 0)
10521                 reg->type |= MEM_RCU;
10522
10523         return 0;
10524 }
10525
10526 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id)
10527 {
10528         struct bpf_func_state *state, *unused;
10529         struct bpf_reg_state *reg;
10530         int i;
10531
10532         state = cur_func(env);
10533
10534         if (!ref_obj_id) {
10535                 verbose(env, "verifier internal error: ref_obj_id is zero for "
10536                              "owning -> non-owning conversion\n");
10537                 return -EFAULT;
10538         }
10539
10540         for (i = 0; i < state->acquired_refs; i++) {
10541                 if (state->refs[i].id != ref_obj_id)
10542                         continue;
10543
10544                 /* Clear ref_obj_id here so release_reference doesn't clobber
10545                  * the whole reg
10546                  */
10547                 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
10548                         if (reg->ref_obj_id == ref_obj_id) {
10549                                 reg->ref_obj_id = 0;
10550                                 ref_set_non_owning(env, reg);
10551                         }
10552                 }));
10553                 return 0;
10554         }
10555
10556         verbose(env, "verifier internal error: ref state missing for ref_obj_id\n");
10557         return -EFAULT;
10558 }
10559
10560 /* Implementation details:
10561  *
10562  * Each register points to some region of memory, which we define as an
10563  * allocation. Each allocation may embed a bpf_spin_lock which protects any
10564  * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same
10565  * allocation. The lock and the data it protects are colocated in the same
10566  * memory region.
10567  *
10568  * Hence, everytime a register holds a pointer value pointing to such
10569  * allocation, the verifier preserves a unique reg->id for it.
10570  *
10571  * The verifier remembers the lock 'ptr' and the lock 'id' whenever
10572  * bpf_spin_lock is called.
10573  *
10574  * To enable this, lock state in the verifier captures two values:
10575  *      active_lock.ptr = Register's type specific pointer
10576  *      active_lock.id  = A unique ID for each register pointer value
10577  *
10578  * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two
10579  * supported register types.
10580  *
10581  * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of
10582  * allocated objects is the reg->btf pointer.
10583  *
10584  * The active_lock.id is non-unique for maps supporting direct_value_addr, as we
10585  * can establish the provenance of the map value statically for each distinct
10586  * lookup into such maps. They always contain a single map value hence unique
10587  * IDs for each pseudo load pessimizes the algorithm and rejects valid programs.
10588  *
10589  * So, in case of global variables, they use array maps with max_entries = 1,
10590  * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point
10591  * into the same map value as max_entries is 1, as described above).
10592  *
10593  * In case of inner map lookups, the inner map pointer has same map_ptr as the
10594  * outer map pointer (in verifier context), but each lookup into an inner map
10595  * assigns a fresh reg->id to the lookup, so while lookups into distinct inner
10596  * maps from the same outer map share the same map_ptr as active_lock.ptr, they
10597  * will get different reg->id assigned to each lookup, hence different
10598  * active_lock.id.
10599  *
10600  * In case of allocated objects, active_lock.ptr is the reg->btf, and the
10601  * reg->id is a unique ID preserved after the NULL pointer check on the pointer
10602  * returned from bpf_obj_new. Each allocation receives a new reg->id.
10603  */
10604 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg)
10605 {
10606         void *ptr;
10607         u32 id;
10608
10609         switch ((int)reg->type) {
10610         case PTR_TO_MAP_VALUE:
10611                 ptr = reg->map_ptr;
10612                 break;
10613         case PTR_TO_BTF_ID | MEM_ALLOC:
10614                 ptr = reg->btf;
10615                 break;
10616         default:
10617                 verbose(env, "verifier internal error: unknown reg type for lock check\n");
10618                 return -EFAULT;
10619         }
10620         id = reg->id;
10621
10622         if (!env->cur_state->active_lock.ptr)
10623                 return -EINVAL;
10624         if (env->cur_state->active_lock.ptr != ptr ||
10625             env->cur_state->active_lock.id != id) {
10626                 verbose(env, "held lock and object are not in the same allocation\n");
10627                 return -EINVAL;
10628         }
10629         return 0;
10630 }
10631
10632 static bool is_bpf_list_api_kfunc(u32 btf_id)
10633 {
10634         return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10635                btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
10636                btf_id == special_kfunc_list[KF_bpf_list_pop_front] ||
10637                btf_id == special_kfunc_list[KF_bpf_list_pop_back];
10638 }
10639
10640 static bool is_bpf_rbtree_api_kfunc(u32 btf_id)
10641 {
10642         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] ||
10643                btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10644                btf_id == special_kfunc_list[KF_bpf_rbtree_first];
10645 }
10646
10647 static bool is_bpf_graph_api_kfunc(u32 btf_id)
10648 {
10649         return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) ||
10650                btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl];
10651 }
10652
10653 static bool is_callback_calling_kfunc(u32 btf_id)
10654 {
10655         return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl];
10656 }
10657
10658 static bool is_rbtree_lock_required_kfunc(u32 btf_id)
10659 {
10660         return is_bpf_rbtree_api_kfunc(btf_id);
10661 }
10662
10663 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env,
10664                                           enum btf_field_type head_field_type,
10665                                           u32 kfunc_btf_id)
10666 {
10667         bool ret;
10668
10669         switch (head_field_type) {
10670         case BPF_LIST_HEAD:
10671                 ret = is_bpf_list_api_kfunc(kfunc_btf_id);
10672                 break;
10673         case BPF_RB_ROOT:
10674                 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id);
10675                 break;
10676         default:
10677                 verbose(env, "verifier internal error: unexpected graph root argument type %s\n",
10678                         btf_field_type_name(head_field_type));
10679                 return false;
10680         }
10681
10682         if (!ret)
10683                 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n",
10684                         btf_field_type_name(head_field_type));
10685         return ret;
10686 }
10687
10688 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
10689                                           enum btf_field_type node_field_type,
10690                                           u32 kfunc_btf_id)
10691 {
10692         bool ret;
10693
10694         switch (node_field_type) {
10695         case BPF_LIST_NODE:
10696                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
10697                        kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]);
10698                 break;
10699         case BPF_RB_NODE:
10700                 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
10701                        kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]);
10702                 break;
10703         default:
10704                 verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
10705                         btf_field_type_name(node_field_type));
10706                 return false;
10707         }
10708
10709         if (!ret)
10710                 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
10711                         btf_field_type_name(node_field_type));
10712         return ret;
10713 }
10714
10715 static int
10716 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env,
10717                                    struct bpf_reg_state *reg, u32 regno,
10718                                    struct bpf_kfunc_call_arg_meta *meta,
10719                                    enum btf_field_type head_field_type,
10720                                    struct btf_field **head_field)
10721 {
10722         const char *head_type_name;
10723         struct btf_field *field;
10724         struct btf_record *rec;
10725         u32 head_off;
10726
10727         if (meta->btf != btf_vmlinux) {
10728                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10729                 return -EFAULT;
10730         }
10731
10732         if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id))
10733                 return -EFAULT;
10734
10735         head_type_name = btf_field_type_name(head_field_type);
10736         if (!tnum_is_const(reg->var_off)) {
10737                 verbose(env,
10738                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10739                         regno, head_type_name);
10740                 return -EINVAL;
10741         }
10742
10743         rec = reg_btf_record(reg);
10744         head_off = reg->off + reg->var_off.value;
10745         field = btf_record_find(rec, head_off, head_field_type);
10746         if (!field) {
10747                 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off);
10748                 return -EINVAL;
10749         }
10750
10751         /* All functions require bpf_list_head to be protected using a bpf_spin_lock */
10752         if (check_reg_allocation_locked(env, reg)) {
10753                 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n",
10754                         rec->spin_lock_off, head_type_name);
10755                 return -EINVAL;
10756         }
10757
10758         if (*head_field) {
10759                 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name);
10760                 return -EFAULT;
10761         }
10762         *head_field = field;
10763         return 0;
10764 }
10765
10766 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env,
10767                                            struct bpf_reg_state *reg, u32 regno,
10768                                            struct bpf_kfunc_call_arg_meta *meta)
10769 {
10770         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD,
10771                                                           &meta->arg_list_head.field);
10772 }
10773
10774 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env,
10775                                              struct bpf_reg_state *reg, u32 regno,
10776                                              struct bpf_kfunc_call_arg_meta *meta)
10777 {
10778         return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT,
10779                                                           &meta->arg_rbtree_root.field);
10780 }
10781
10782 static int
10783 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env,
10784                                    struct bpf_reg_state *reg, u32 regno,
10785                                    struct bpf_kfunc_call_arg_meta *meta,
10786                                    enum btf_field_type head_field_type,
10787                                    enum btf_field_type node_field_type,
10788                                    struct btf_field **node_field)
10789 {
10790         const char *node_type_name;
10791         const struct btf_type *et, *t;
10792         struct btf_field *field;
10793         u32 node_off;
10794
10795         if (meta->btf != btf_vmlinux) {
10796                 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n");
10797                 return -EFAULT;
10798         }
10799
10800         if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id))
10801                 return -EFAULT;
10802
10803         node_type_name = btf_field_type_name(node_field_type);
10804         if (!tnum_is_const(reg->var_off)) {
10805                 verbose(env,
10806                         "R%d doesn't have constant offset. %s has to be at the constant offset\n",
10807                         regno, node_type_name);
10808                 return -EINVAL;
10809         }
10810
10811         node_off = reg->off + reg->var_off.value;
10812         field = reg_find_field_offset(reg, node_off, node_field_type);
10813         if (!field || field->offset != node_off) {
10814                 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off);
10815                 return -EINVAL;
10816         }
10817
10818         field = *node_field;
10819
10820         et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id);
10821         t = btf_type_by_id(reg->btf, reg->btf_id);
10822         if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf,
10823                                   field->graph_root.value_btf_id, true)) {
10824                 verbose(env, "operation on %s expects arg#1 %s at offset=%d "
10825                         "in struct %s, but arg is at offset=%d in struct %s\n",
10826                         btf_field_type_name(head_field_type),
10827                         btf_field_type_name(node_field_type),
10828                         field->graph_root.node_offset,
10829                         btf_name_by_offset(field->graph_root.btf, et->name_off),
10830                         node_off, btf_name_by_offset(reg->btf, t->name_off));
10831                 return -EINVAL;
10832         }
10833         meta->arg_btf = reg->btf;
10834         meta->arg_btf_id = reg->btf_id;
10835
10836         if (node_off != field->graph_root.node_offset) {
10837                 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n",
10838                         node_off, btf_field_type_name(node_field_type),
10839                         field->graph_root.node_offset,
10840                         btf_name_by_offset(field->graph_root.btf, et->name_off));
10841                 return -EINVAL;
10842         }
10843
10844         return 0;
10845 }
10846
10847 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env,
10848                                            struct bpf_reg_state *reg, u32 regno,
10849                                            struct bpf_kfunc_call_arg_meta *meta)
10850 {
10851         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10852                                                   BPF_LIST_HEAD, BPF_LIST_NODE,
10853                                                   &meta->arg_list_head.field);
10854 }
10855
10856 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env,
10857                                              struct bpf_reg_state *reg, u32 regno,
10858                                              struct bpf_kfunc_call_arg_meta *meta)
10859 {
10860         return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta,
10861                                                   BPF_RB_ROOT, BPF_RB_NODE,
10862                                                   &meta->arg_rbtree_root.field);
10863 }
10864
10865 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta,
10866                             int insn_idx)
10867 {
10868         const char *func_name = meta->func_name, *ref_tname;
10869         const struct btf *btf = meta->btf;
10870         const struct btf_param *args;
10871         struct btf_record *rec;
10872         u32 i, nargs;
10873         int ret;
10874
10875         args = (const struct btf_param *)(meta->func_proto + 1);
10876         nargs = btf_type_vlen(meta->func_proto);
10877         if (nargs > MAX_BPF_FUNC_REG_ARGS) {
10878                 verbose(env, "Function %s has %d > %d args\n", func_name, nargs,
10879                         MAX_BPF_FUNC_REG_ARGS);
10880                 return -EINVAL;
10881         }
10882
10883         /* Check that BTF function arguments match actual types that the
10884          * verifier sees.
10885          */
10886         for (i = 0; i < nargs; i++) {
10887                 struct bpf_reg_state *regs = cur_regs(env), *reg = &regs[i + 1];
10888                 const struct btf_type *t, *ref_t, *resolve_ret;
10889                 enum bpf_arg_type arg_type = ARG_DONTCARE;
10890                 u32 regno = i + 1, ref_id, type_size;
10891                 bool is_ret_buf_sz = false;
10892                 int kf_arg_type;
10893
10894                 t = btf_type_skip_modifiers(btf, args[i].type, NULL);
10895
10896                 if (is_kfunc_arg_ignore(btf, &args[i]))
10897                         continue;
10898
10899                 if (btf_type_is_scalar(t)) {
10900                         if (reg->type != SCALAR_VALUE) {
10901                                 verbose(env, "R%d is not a scalar\n", regno);
10902                                 return -EINVAL;
10903                         }
10904
10905                         if (is_kfunc_arg_constant(meta->btf, &args[i])) {
10906                                 if (meta->arg_constant.found) {
10907                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
10908                                         return -EFAULT;
10909                                 }
10910                                 if (!tnum_is_const(reg->var_off)) {
10911                                         verbose(env, "R%d must be a known constant\n", regno);
10912                                         return -EINVAL;
10913                                 }
10914                                 ret = mark_chain_precision(env, regno);
10915                                 if (ret < 0)
10916                                         return ret;
10917                                 meta->arg_constant.found = true;
10918                                 meta->arg_constant.value = reg->var_off.value;
10919                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) {
10920                                 meta->r0_rdonly = true;
10921                                 is_ret_buf_sz = true;
10922                         } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) {
10923                                 is_ret_buf_sz = true;
10924                         }
10925
10926                         if (is_ret_buf_sz) {
10927                                 if (meta->r0_size) {
10928                                         verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc");
10929                                         return -EINVAL;
10930                                 }
10931
10932                                 if (!tnum_is_const(reg->var_off)) {
10933                                         verbose(env, "R%d is not a const\n", regno);
10934                                         return -EINVAL;
10935                                 }
10936
10937                                 meta->r0_size = reg->var_off.value;
10938                                 ret = mark_chain_precision(env, regno);
10939                                 if (ret)
10940                                         return ret;
10941                         }
10942                         continue;
10943                 }
10944
10945                 if (!btf_type_is_ptr(t)) {
10946                         verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t));
10947                         return -EINVAL;
10948                 }
10949
10950                 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) &&
10951                     (register_is_null(reg) || type_may_be_null(reg->type))) {
10952                         verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i);
10953                         return -EACCES;
10954                 }
10955
10956                 if (reg->ref_obj_id) {
10957                         if (is_kfunc_release(meta) && meta->ref_obj_id) {
10958                                 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n",
10959                                         regno, reg->ref_obj_id,
10960                                         meta->ref_obj_id);
10961                                 return -EFAULT;
10962                         }
10963                         meta->ref_obj_id = reg->ref_obj_id;
10964                         if (is_kfunc_release(meta))
10965                                 meta->release_regno = regno;
10966                 }
10967
10968                 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
10969                 ref_tname = btf_name_by_offset(btf, ref_t->name_off);
10970
10971                 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs);
10972                 if (kf_arg_type < 0)
10973                         return kf_arg_type;
10974
10975                 switch (kf_arg_type) {
10976                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
10977                 case KF_ARG_PTR_TO_BTF_ID:
10978                         if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta))
10979                                 break;
10980
10981                         if (!is_trusted_reg(reg)) {
10982                                 if (!is_kfunc_rcu(meta)) {
10983                                         verbose(env, "R%d must be referenced or trusted\n", regno);
10984                                         return -EINVAL;
10985                                 }
10986                                 if (!is_rcu_reg(reg)) {
10987                                         verbose(env, "R%d must be a rcu pointer\n", regno);
10988                                         return -EINVAL;
10989                                 }
10990                         }
10991
10992                         fallthrough;
10993                 case KF_ARG_PTR_TO_CTX:
10994                         /* Trusted arguments have the same offset checks as release arguments */
10995                         arg_type |= OBJ_RELEASE;
10996                         break;
10997                 case KF_ARG_PTR_TO_DYNPTR:
10998                 case KF_ARG_PTR_TO_ITER:
10999                 case KF_ARG_PTR_TO_LIST_HEAD:
11000                 case KF_ARG_PTR_TO_LIST_NODE:
11001                 case KF_ARG_PTR_TO_RB_ROOT:
11002                 case KF_ARG_PTR_TO_RB_NODE:
11003                 case KF_ARG_PTR_TO_MEM:
11004                 case KF_ARG_PTR_TO_MEM_SIZE:
11005                 case KF_ARG_PTR_TO_CALLBACK:
11006                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11007                         /* Trusted by default */
11008                         break;
11009                 default:
11010                         WARN_ON_ONCE(1);
11011                         return -EFAULT;
11012                 }
11013
11014                 if (is_kfunc_release(meta) && reg->ref_obj_id)
11015                         arg_type |= OBJ_RELEASE;
11016                 ret = check_func_arg_reg_off(env, reg, regno, arg_type);
11017                 if (ret < 0)
11018                         return ret;
11019
11020                 switch (kf_arg_type) {
11021                 case KF_ARG_PTR_TO_CTX:
11022                         if (reg->type != PTR_TO_CTX) {
11023                                 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t));
11024                                 return -EINVAL;
11025                         }
11026
11027                         if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11028                                 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog));
11029                                 if (ret < 0)
11030                                         return -EINVAL;
11031                                 meta->ret_btf_id  = ret;
11032                         }
11033                         break;
11034                 case KF_ARG_PTR_TO_ALLOC_BTF_ID:
11035                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11036                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11037                                 return -EINVAL;
11038                         }
11039                         if (!reg->ref_obj_id) {
11040                                 verbose(env, "allocated object must be referenced\n");
11041                                 return -EINVAL;
11042                         }
11043                         if (meta->btf == btf_vmlinux &&
11044                             meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11045                                 meta->arg_btf = reg->btf;
11046                                 meta->arg_btf_id = reg->btf_id;
11047                         }
11048                         break;
11049                 case KF_ARG_PTR_TO_DYNPTR:
11050                 {
11051                         enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR;
11052                         int clone_ref_obj_id = 0;
11053
11054                         if (reg->type != PTR_TO_STACK &&
11055                             reg->type != CONST_PTR_TO_DYNPTR) {
11056                                 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i);
11057                                 return -EINVAL;
11058                         }
11059
11060                         if (reg->type == CONST_PTR_TO_DYNPTR)
11061                                 dynptr_arg_type |= MEM_RDONLY;
11062
11063                         if (is_kfunc_arg_uninit(btf, &args[i]))
11064                                 dynptr_arg_type |= MEM_UNINIT;
11065
11066                         if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
11067                                 dynptr_arg_type |= DYNPTR_TYPE_SKB;
11068                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) {
11069                                 dynptr_arg_type |= DYNPTR_TYPE_XDP;
11070                         } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
11071                                    (dynptr_arg_type & MEM_UNINIT)) {
11072                                 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
11073
11074                                 if (parent_type == BPF_DYNPTR_TYPE_INVALID) {
11075                                         verbose(env, "verifier internal error: no dynptr type for parent of clone\n");
11076                                         return -EFAULT;
11077                                 }
11078
11079                                 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type);
11080                                 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id;
11081                                 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) {
11082                                         verbose(env, "verifier internal error: missing ref obj id for parent of clone\n");
11083                                         return -EFAULT;
11084                                 }
11085                         }
11086
11087                         ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id);
11088                         if (ret < 0)
11089                                 return ret;
11090
11091                         if (!(dynptr_arg_type & MEM_UNINIT)) {
11092                                 int id = dynptr_id(env, reg);
11093
11094                                 if (id < 0) {
11095                                         verbose(env, "verifier internal error: failed to obtain dynptr id\n");
11096                                         return id;
11097                                 }
11098                                 meta->initialized_dynptr.id = id;
11099                                 meta->initialized_dynptr.type = dynptr_get_type(env, reg);
11100                                 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg);
11101                         }
11102
11103                         break;
11104                 }
11105                 case KF_ARG_PTR_TO_ITER:
11106                         ret = process_iter_arg(env, regno, insn_idx, meta);
11107                         if (ret < 0)
11108                                 return ret;
11109                         break;
11110                 case KF_ARG_PTR_TO_LIST_HEAD:
11111                         if (reg->type != PTR_TO_MAP_VALUE &&
11112                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11113                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11114                                 return -EINVAL;
11115                         }
11116                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11117                                 verbose(env, "allocated object must be referenced\n");
11118                                 return -EINVAL;
11119                         }
11120                         ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta);
11121                         if (ret < 0)
11122                                 return ret;
11123                         break;
11124                 case KF_ARG_PTR_TO_RB_ROOT:
11125                         if (reg->type != PTR_TO_MAP_VALUE &&
11126                             reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11127                                 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i);
11128                                 return -EINVAL;
11129                         }
11130                         if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) {
11131                                 verbose(env, "allocated object must be referenced\n");
11132                                 return -EINVAL;
11133                         }
11134                         ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta);
11135                         if (ret < 0)
11136                                 return ret;
11137                         break;
11138                 case KF_ARG_PTR_TO_LIST_NODE:
11139                         if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11140                                 verbose(env, "arg#%d expected pointer to allocated object\n", i);
11141                                 return -EINVAL;
11142                         }
11143                         if (!reg->ref_obj_id) {
11144                                 verbose(env, "allocated object must be referenced\n");
11145                                 return -EINVAL;
11146                         }
11147                         ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta);
11148                         if (ret < 0)
11149                                 return ret;
11150                         break;
11151                 case KF_ARG_PTR_TO_RB_NODE:
11152                         if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) {
11153                                 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) {
11154                                         verbose(env, "rbtree_remove node input must be non-owning ref\n");
11155                                         return -EINVAL;
11156                                 }
11157                                 if (in_rbtree_lock_required_cb(env)) {
11158                                         verbose(env, "rbtree_remove not allowed in rbtree cb\n");
11159                                         return -EINVAL;
11160                                 }
11161                         } else {
11162                                 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) {
11163                                         verbose(env, "arg#%d expected pointer to allocated object\n", i);
11164                                         return -EINVAL;
11165                                 }
11166                                 if (!reg->ref_obj_id) {
11167                                         verbose(env, "allocated object must be referenced\n");
11168                                         return -EINVAL;
11169                                 }
11170                         }
11171
11172                         ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta);
11173                         if (ret < 0)
11174                                 return ret;
11175                         break;
11176                 case KF_ARG_PTR_TO_BTF_ID:
11177                         /* Only base_type is checked, further checks are done here */
11178                         if ((base_type(reg->type) != PTR_TO_BTF_ID ||
11179                              (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) &&
11180                             !reg2btf_ids[base_type(reg->type)]) {
11181                                 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type));
11182                                 verbose(env, "expected %s or socket\n",
11183                                         reg_type_str(env, base_type(reg->type) |
11184                                                           (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS)));
11185                                 return -EINVAL;
11186                         }
11187                         ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i);
11188                         if (ret < 0)
11189                                 return ret;
11190                         break;
11191                 case KF_ARG_PTR_TO_MEM:
11192                         resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
11193                         if (IS_ERR(resolve_ret)) {
11194                                 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
11195                                         i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret));
11196                                 return -EINVAL;
11197                         }
11198                         ret = check_mem_reg(env, reg, regno, type_size);
11199                         if (ret < 0)
11200                                 return ret;
11201                         break;
11202                 case KF_ARG_PTR_TO_MEM_SIZE:
11203                 {
11204                         struct bpf_reg_state *buff_reg = &regs[regno];
11205                         const struct btf_param *buff_arg = &args[i];
11206                         struct bpf_reg_state *size_reg = &regs[regno + 1];
11207                         const struct btf_param *size_arg = &args[i + 1];
11208
11209                         if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) {
11210                                 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1);
11211                                 if (ret < 0) {
11212                                         verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1);
11213                                         return ret;
11214                                 }
11215                         }
11216
11217                         if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) {
11218                                 if (meta->arg_constant.found) {
11219                                         verbose(env, "verifier internal error: only one constant argument permitted\n");
11220                                         return -EFAULT;
11221                                 }
11222                                 if (!tnum_is_const(size_reg->var_off)) {
11223                                         verbose(env, "R%d must be a known constant\n", regno + 1);
11224                                         return -EINVAL;
11225                                 }
11226                                 meta->arg_constant.found = true;
11227                                 meta->arg_constant.value = size_reg->var_off.value;
11228                         }
11229
11230                         /* Skip next '__sz' or '__szk' argument */
11231                         i++;
11232                         break;
11233                 }
11234                 case KF_ARG_PTR_TO_CALLBACK:
11235                         if (reg->type != PTR_TO_FUNC) {
11236                                 verbose(env, "arg%d expected pointer to func\n", i);
11237                                 return -EINVAL;
11238                         }
11239                         meta->subprogno = reg->subprogno;
11240                         break;
11241                 case KF_ARG_PTR_TO_REFCOUNTED_KPTR:
11242                         if (!type_is_ptr_alloc_obj(reg->type)) {
11243                                 verbose(env, "arg#%d is neither owning or non-owning ref\n", i);
11244                                 return -EINVAL;
11245                         }
11246                         if (!type_is_non_owning_ref(reg->type))
11247                                 meta->arg_owning_ref = true;
11248
11249                         rec = reg_btf_record(reg);
11250                         if (!rec) {
11251                                 verbose(env, "verifier internal error: Couldn't find btf_record\n");
11252                                 return -EFAULT;
11253                         }
11254
11255                         if (rec->refcount_off < 0) {
11256                                 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i);
11257                                 return -EINVAL;
11258                         }
11259
11260                         meta->arg_btf = reg->btf;
11261                         meta->arg_btf_id = reg->btf_id;
11262                         break;
11263                 }
11264         }
11265
11266         if (is_kfunc_release(meta) && !meta->release_regno) {
11267                 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n",
11268                         func_name);
11269                 return -EINVAL;
11270         }
11271
11272         return 0;
11273 }
11274
11275 static int fetch_kfunc_meta(struct bpf_verifier_env *env,
11276                             struct bpf_insn *insn,
11277                             struct bpf_kfunc_call_arg_meta *meta,
11278                             const char **kfunc_name)
11279 {
11280         const struct btf_type *func, *func_proto;
11281         u32 func_id, *kfunc_flags;
11282         const char *func_name;
11283         struct btf *desc_btf;
11284
11285         if (kfunc_name)
11286                 *kfunc_name = NULL;
11287
11288         if (!insn->imm)
11289                 return -EINVAL;
11290
11291         desc_btf = find_kfunc_desc_btf(env, insn->off);
11292         if (IS_ERR(desc_btf))
11293                 return PTR_ERR(desc_btf);
11294
11295         func_id = insn->imm;
11296         func = btf_type_by_id(desc_btf, func_id);
11297         func_name = btf_name_by_offset(desc_btf, func->name_off);
11298         if (kfunc_name)
11299                 *kfunc_name = func_name;
11300         func_proto = btf_type_by_id(desc_btf, func->type);
11301
11302         kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog);
11303         if (!kfunc_flags) {
11304                 return -EACCES;
11305         }
11306
11307         memset(meta, 0, sizeof(*meta));
11308         meta->btf = desc_btf;
11309         meta->func_id = func_id;
11310         meta->kfunc_flags = *kfunc_flags;
11311         meta->func_proto = func_proto;
11312         meta->func_name = func_name;
11313
11314         return 0;
11315 }
11316
11317 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
11318                             int *insn_idx_p)
11319 {
11320         const struct btf_type *t, *ptr_type;
11321         u32 i, nargs, ptr_type_id, release_ref_obj_id;
11322         struct bpf_reg_state *regs = cur_regs(env);
11323         const char *func_name, *ptr_type_name;
11324         bool sleepable, rcu_lock, rcu_unlock;
11325         struct bpf_kfunc_call_arg_meta meta;
11326         struct bpf_insn_aux_data *insn_aux;
11327         int err, insn_idx = *insn_idx_p;
11328         const struct btf_param *args;
11329         const struct btf_type *ret_t;
11330         struct btf *desc_btf;
11331
11332         /* skip for now, but return error when we find this in fixup_kfunc_call */
11333         if (!insn->imm)
11334                 return 0;
11335
11336         err = fetch_kfunc_meta(env, insn, &meta, &func_name);
11337         if (err == -EACCES && func_name)
11338                 verbose(env, "calling kernel function %s is not allowed\n", func_name);
11339         if (err)
11340                 return err;
11341         desc_btf = meta.btf;
11342         insn_aux = &env->insn_aux_data[insn_idx];
11343
11344         insn_aux->is_iter_next = is_iter_next_kfunc(&meta);
11345
11346         if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
11347                 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
11348                 return -EACCES;
11349         }
11350
11351         sleepable = is_kfunc_sleepable(&meta);
11352         if (sleepable && !env->prog->aux->sleepable) {
11353                 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name);
11354                 return -EACCES;
11355         }
11356
11357         rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta);
11358         rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta);
11359
11360         if (env->cur_state->active_rcu_lock) {
11361                 struct bpf_func_state *state;
11362                 struct bpf_reg_state *reg;
11363
11364                 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) {
11365                         verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n");
11366                         return -EACCES;
11367                 }
11368
11369                 if (rcu_lock) {
11370                         verbose(env, "nested rcu read lock (kernel function %s)\n", func_name);
11371                         return -EINVAL;
11372                 } else if (rcu_unlock) {
11373                         bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
11374                                 if (reg->type & MEM_RCU) {
11375                                         reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL);
11376                                         reg->type |= PTR_UNTRUSTED;
11377                                 }
11378                         }));
11379                         env->cur_state->active_rcu_lock = false;
11380                 } else if (sleepable) {
11381                         verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name);
11382                         return -EACCES;
11383                 }
11384         } else if (rcu_lock) {
11385                 env->cur_state->active_rcu_lock = true;
11386         } else if (rcu_unlock) {
11387                 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
11388                 return -EINVAL;
11389         }
11390
11391         /* Check the arguments */
11392         err = check_kfunc_args(env, &meta, insn_idx);
11393         if (err < 0)
11394                 return err;
11395         /* In case of release function, we get register number of refcounted
11396          * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
11397          */
11398         if (meta.release_regno) {
11399                 err = release_reference(env, regs[meta.release_regno].ref_obj_id);
11400                 if (err) {
11401                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11402                                 func_name, meta.func_id);
11403                         return err;
11404                 }
11405         }
11406
11407         if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
11408             meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
11409             meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11410                 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id;
11411                 insn_aux->insert_off = regs[BPF_REG_2].off;
11412                 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
11413                 err = ref_convert_owning_non_owning(env, release_ref_obj_id);
11414                 if (err) {
11415                         verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n",
11416                                 func_name, meta.func_id);
11417                         return err;
11418                 }
11419
11420                 err = release_reference(env, release_ref_obj_id);
11421                 if (err) {
11422                         verbose(env, "kfunc %s#%d reference has not been acquired before\n",
11423                                 func_name, meta.func_id);
11424                         return err;
11425                 }
11426         }
11427
11428         if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
11429                 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno,
11430                                         set_rbtree_add_callback_state);
11431                 if (err) {
11432                         verbose(env, "kfunc %s#%d failed callback verification\n",
11433                                 func_name, meta.func_id);
11434                         return err;
11435                 }
11436         }
11437
11438         for (i = 0; i < CALLER_SAVED_REGS; i++)
11439                 mark_reg_not_init(env, regs, caller_saved[i]);
11440
11441         /* Check return type */
11442         t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
11443
11444         if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) {
11445                 /* Only exception is bpf_obj_new_impl */
11446                 if (meta.btf != btf_vmlinux ||
11447                     (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] &&
11448                      meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) {
11449                         verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n");
11450                         return -EINVAL;
11451                 }
11452         }
11453
11454         if (btf_type_is_scalar(t)) {
11455                 mark_reg_unknown(env, regs, BPF_REG_0);
11456                 mark_btf_func_reg_size(env, BPF_REG_0, t->size);
11457         } else if (btf_type_is_ptr(t)) {
11458                 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id);
11459
11460                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11461                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
11462                                 struct btf *ret_btf;
11463                                 u32 ret_btf_id;
11464
11465                                 if (unlikely(!bpf_global_ma_set))
11466                                         return -ENOMEM;
11467
11468                                 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) {
11469                                         verbose(env, "local type ID argument must be in range [0, U32_MAX]\n");
11470                                         return -EINVAL;
11471                                 }
11472
11473                                 ret_btf = env->prog->aux->btf;
11474                                 ret_btf_id = meta.arg_constant.value;
11475
11476                                 /* This may be NULL due to user not supplying a BTF */
11477                                 if (!ret_btf) {
11478                                         verbose(env, "bpf_obj_new requires prog BTF\n");
11479                                         return -EINVAL;
11480                                 }
11481
11482                                 ret_t = btf_type_by_id(ret_btf, ret_btf_id);
11483                                 if (!ret_t || !__btf_type_is_struct(ret_t)) {
11484                                         verbose(env, "bpf_obj_new type ID argument must be of a struct\n");
11485                                         return -EINVAL;
11486                                 }
11487
11488                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11489                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11490                                 regs[BPF_REG_0].btf = ret_btf;
11491                                 regs[BPF_REG_0].btf_id = ret_btf_id;
11492
11493                                 insn_aux->obj_new_size = ret_t->size;
11494                                 insn_aux->kptr_struct_meta =
11495                                         btf_find_struct_meta(ret_btf, ret_btf_id);
11496                         } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
11497                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11498                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC;
11499                                 regs[BPF_REG_0].btf = meta.arg_btf;
11500                                 regs[BPF_REG_0].btf_id = meta.arg_btf_id;
11501
11502                                 insn_aux->kptr_struct_meta =
11503                                         btf_find_struct_meta(meta.arg_btf,
11504                                                              meta.arg_btf_id);
11505                         } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] ||
11506                                    meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) {
11507                                 struct btf_field *field = meta.arg_list_head.field;
11508
11509                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11510                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] ||
11511                                    meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11512                                 struct btf_field *field = meta.arg_rbtree_root.field;
11513
11514                                 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root);
11515                         } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) {
11516                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11517                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED;
11518                                 regs[BPF_REG_0].btf = desc_btf;
11519                                 regs[BPF_REG_0].btf_id = meta.ret_btf_id;
11520                         } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
11521                                 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value);
11522                                 if (!ret_t || !btf_type_is_struct(ret_t)) {
11523                                         verbose(env,
11524                                                 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n");
11525                                         return -EINVAL;
11526                                 }
11527
11528                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11529                                 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
11530                                 regs[BPF_REG_0].btf = desc_btf;
11531                                 regs[BPF_REG_0].btf_id = meta.arg_constant.value;
11532                         } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] ||
11533                                    meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) {
11534                                 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type);
11535
11536                                 mark_reg_known_zero(env, regs, BPF_REG_0);
11537
11538                                 if (!meta.arg_constant.found) {
11539                                         verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n");
11540                                         return -EFAULT;
11541                                 }
11542
11543                                 regs[BPF_REG_0].mem_size = meta.arg_constant.value;
11544
11545                                 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */
11546                                 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag;
11547
11548                                 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) {
11549                                         regs[BPF_REG_0].type |= MEM_RDONLY;
11550                                 } else {
11551                                         /* this will set env->seen_direct_write to true */
11552                                         if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) {
11553                                                 verbose(env, "the prog does not allow writes to packet data\n");
11554                                                 return -EINVAL;
11555                                         }
11556                                 }
11557
11558                                 if (!meta.initialized_dynptr.id) {
11559                                         verbose(env, "verifier internal error: no dynptr id\n");
11560                                         return -EFAULT;
11561                                 }
11562                                 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id;
11563
11564                                 /* we don't need to set BPF_REG_0's ref obj id
11565                                  * because packet slices are not refcounted (see
11566                                  * dynptr_type_refcounted)
11567                                  */
11568                         } else {
11569                                 verbose(env, "kernel function %s unhandled dynamic return type\n",
11570                                         meta.func_name);
11571                                 return -EFAULT;
11572                         }
11573                 } else if (!__btf_type_is_struct(ptr_type)) {
11574                         if (!meta.r0_size) {
11575                                 __u32 sz;
11576
11577                                 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) {
11578                                         meta.r0_size = sz;
11579                                         meta.r0_rdonly = true;
11580                                 }
11581                         }
11582                         if (!meta.r0_size) {
11583                                 ptr_type_name = btf_name_by_offset(desc_btf,
11584                                                                    ptr_type->name_off);
11585                                 verbose(env,
11586                                         "kernel function %s returns pointer type %s %s is not supported\n",
11587                                         func_name,
11588                                         btf_type_str(ptr_type),
11589                                         ptr_type_name);
11590                                 return -EINVAL;
11591                         }
11592
11593                         mark_reg_known_zero(env, regs, BPF_REG_0);
11594                         regs[BPF_REG_0].type = PTR_TO_MEM;
11595                         regs[BPF_REG_0].mem_size = meta.r0_size;
11596
11597                         if (meta.r0_rdonly)
11598                                 regs[BPF_REG_0].type |= MEM_RDONLY;
11599
11600                         /* Ensures we don't access the memory after a release_reference() */
11601                         if (meta.ref_obj_id)
11602                                 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id;
11603                 } else {
11604                         mark_reg_known_zero(env, regs, BPF_REG_0);
11605                         regs[BPF_REG_0].btf = desc_btf;
11606                         regs[BPF_REG_0].type = PTR_TO_BTF_ID;
11607                         regs[BPF_REG_0].btf_id = ptr_type_id;
11608                 }
11609
11610                 if (is_kfunc_ret_null(&meta)) {
11611                         regs[BPF_REG_0].type |= PTR_MAYBE_NULL;
11612                         /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */
11613                         regs[BPF_REG_0].id = ++env->id_gen;
11614                 }
11615                 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *));
11616                 if (is_kfunc_acquire(&meta)) {
11617                         int id = acquire_reference_state(env, insn_idx);
11618
11619                         if (id < 0)
11620                                 return id;
11621                         if (is_kfunc_ret_null(&meta))
11622                                 regs[BPF_REG_0].id = id;
11623                         regs[BPF_REG_0].ref_obj_id = id;
11624                 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) {
11625                         ref_set_non_owning(env, &regs[BPF_REG_0]);
11626                 }
11627
11628                 if (reg_may_point_to_spin_lock(&regs[BPF_REG_0]) && !regs[BPF_REG_0].id)
11629                         regs[BPF_REG_0].id = ++env->id_gen;
11630         } else if (btf_type_is_void(t)) {
11631                 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) {
11632                         if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) {
11633                                 insn_aux->kptr_struct_meta =
11634                                         btf_find_struct_meta(meta.arg_btf,
11635                                                              meta.arg_btf_id);
11636                         }
11637                 }
11638         }
11639
11640         nargs = btf_type_vlen(meta.func_proto);
11641         args = (const struct btf_param *)(meta.func_proto + 1);
11642         for (i = 0; i < nargs; i++) {
11643                 u32 regno = i + 1;
11644
11645                 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL);
11646                 if (btf_type_is_ptr(t))
11647                         mark_btf_func_reg_size(env, regno, sizeof(void *));
11648                 else
11649                         /* scalar. ensured by btf_check_kfunc_arg_match() */
11650                         mark_btf_func_reg_size(env, regno, t->size);
11651         }
11652
11653         if (is_iter_next_kfunc(&meta)) {
11654                 err = process_iter_next_call(env, insn_idx, &meta);
11655                 if (err)
11656                         return err;
11657         }
11658
11659         return 0;
11660 }
11661
11662 static bool signed_add_overflows(s64 a, s64 b)
11663 {
11664         /* Do the add in u64, where overflow is well-defined */
11665         s64 res = (s64)((u64)a + (u64)b);
11666
11667         if (b < 0)
11668                 return res > a;
11669         return res < a;
11670 }
11671
11672 static bool signed_add32_overflows(s32 a, s32 b)
11673 {
11674         /* Do the add in u32, where overflow is well-defined */
11675         s32 res = (s32)((u32)a + (u32)b);
11676
11677         if (b < 0)
11678                 return res > a;
11679         return res < a;
11680 }
11681
11682 static bool signed_sub_overflows(s64 a, s64 b)
11683 {
11684         /* Do the sub in u64, where overflow is well-defined */
11685         s64 res = (s64)((u64)a - (u64)b);
11686
11687         if (b < 0)
11688                 return res < a;
11689         return res > a;
11690 }
11691
11692 static bool signed_sub32_overflows(s32 a, s32 b)
11693 {
11694         /* Do the sub in u32, where overflow is well-defined */
11695         s32 res = (s32)((u32)a - (u32)b);
11696
11697         if (b < 0)
11698                 return res < a;
11699         return res > a;
11700 }
11701
11702 static bool check_reg_sane_offset(struct bpf_verifier_env *env,
11703                                   const struct bpf_reg_state *reg,
11704                                   enum bpf_reg_type type)
11705 {
11706         bool known = tnum_is_const(reg->var_off);
11707         s64 val = reg->var_off.value;
11708         s64 smin = reg->smin_value;
11709
11710         if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) {
11711                 verbose(env, "math between %s pointer and %lld is not allowed\n",
11712                         reg_type_str(env, type), val);
11713                 return false;
11714         }
11715
11716         if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) {
11717                 verbose(env, "%s pointer offset %d is not allowed\n",
11718                         reg_type_str(env, type), reg->off);
11719                 return false;
11720         }
11721
11722         if (smin == S64_MIN) {
11723                 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n",
11724                         reg_type_str(env, type));
11725                 return false;
11726         }
11727
11728         if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) {
11729                 verbose(env, "value %lld makes %s pointer be out of bounds\n",
11730                         smin, reg_type_str(env, type));
11731                 return false;
11732         }
11733
11734         return true;
11735 }
11736
11737 enum {
11738         REASON_BOUNDS   = -1,
11739         REASON_TYPE     = -2,
11740         REASON_PATHS    = -3,
11741         REASON_LIMIT    = -4,
11742         REASON_STACK    = -5,
11743 };
11744
11745 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg,
11746                               u32 *alu_limit, bool mask_to_left)
11747 {
11748         u32 max = 0, ptr_limit = 0;
11749
11750         switch (ptr_reg->type) {
11751         case PTR_TO_STACK:
11752                 /* Offset 0 is out-of-bounds, but acceptable start for the
11753                  * left direction, see BPF_REG_FP. Also, unknown scalar
11754                  * offset where we would need to deal with min/max bounds is
11755                  * currently prohibited for unprivileged.
11756                  */
11757                 max = MAX_BPF_STACK + mask_to_left;
11758                 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off);
11759                 break;
11760         case PTR_TO_MAP_VALUE:
11761                 max = ptr_reg->map_ptr->value_size;
11762                 ptr_limit = (mask_to_left ?
11763                              ptr_reg->smin_value :
11764                              ptr_reg->umax_value) + ptr_reg->off;
11765                 break;
11766         default:
11767                 return REASON_TYPE;
11768         }
11769
11770         if (ptr_limit >= max)
11771                 return REASON_LIMIT;
11772         *alu_limit = ptr_limit;
11773         return 0;
11774 }
11775
11776 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env,
11777                                     const struct bpf_insn *insn)
11778 {
11779         return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K;
11780 }
11781
11782 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux,
11783                                        u32 alu_state, u32 alu_limit)
11784 {
11785         /* If we arrived here from different branches with different
11786          * state or limits to sanitize, then this won't work.
11787          */
11788         if (aux->alu_state &&
11789             (aux->alu_state != alu_state ||
11790              aux->alu_limit != alu_limit))
11791                 return REASON_PATHS;
11792
11793         /* Corresponding fixup done in do_misc_fixups(). */
11794         aux->alu_state = alu_state;
11795         aux->alu_limit = alu_limit;
11796         return 0;
11797 }
11798
11799 static int sanitize_val_alu(struct bpf_verifier_env *env,
11800                             struct bpf_insn *insn)
11801 {
11802         struct bpf_insn_aux_data *aux = cur_aux(env);
11803
11804         if (can_skip_alu_sanitation(env, insn))
11805                 return 0;
11806
11807         return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0);
11808 }
11809
11810 static bool sanitize_needed(u8 opcode)
11811 {
11812         return opcode == BPF_ADD || opcode == BPF_SUB;
11813 }
11814
11815 struct bpf_sanitize_info {
11816         struct bpf_insn_aux_data aux;
11817         bool mask_to_left;
11818 };
11819
11820 static struct bpf_verifier_state *
11821 sanitize_speculative_path(struct bpf_verifier_env *env,
11822                           const struct bpf_insn *insn,
11823                           u32 next_idx, u32 curr_idx)
11824 {
11825         struct bpf_verifier_state *branch;
11826         struct bpf_reg_state *regs;
11827
11828         branch = push_stack(env, next_idx, curr_idx, true);
11829         if (branch && insn) {
11830                 regs = branch->frame[branch->curframe]->regs;
11831                 if (BPF_SRC(insn->code) == BPF_K) {
11832                         mark_reg_unknown(env, regs, insn->dst_reg);
11833                 } else if (BPF_SRC(insn->code) == BPF_X) {
11834                         mark_reg_unknown(env, regs, insn->dst_reg);
11835                         mark_reg_unknown(env, regs, insn->src_reg);
11836                 }
11837         }
11838         return branch;
11839 }
11840
11841 static int sanitize_ptr_alu(struct bpf_verifier_env *env,
11842                             struct bpf_insn *insn,
11843                             const struct bpf_reg_state *ptr_reg,
11844                             const struct bpf_reg_state *off_reg,
11845                             struct bpf_reg_state *dst_reg,
11846                             struct bpf_sanitize_info *info,
11847                             const bool commit_window)
11848 {
11849         struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux;
11850         struct bpf_verifier_state *vstate = env->cur_state;
11851         bool off_is_imm = tnum_is_const(off_reg->var_off);
11852         bool off_is_neg = off_reg->smin_value < 0;
11853         bool ptr_is_dst_reg = ptr_reg == dst_reg;
11854         u8 opcode = BPF_OP(insn->code);
11855         u32 alu_state, alu_limit;
11856         struct bpf_reg_state tmp;
11857         bool ret;
11858         int err;
11859
11860         if (can_skip_alu_sanitation(env, insn))
11861                 return 0;
11862
11863         /* We already marked aux for masking from non-speculative
11864          * paths, thus we got here in the first place. We only care
11865          * to explore bad access from here.
11866          */
11867         if (vstate->speculative)
11868                 goto do_sim;
11869
11870         if (!commit_window) {
11871                 if (!tnum_is_const(off_reg->var_off) &&
11872                     (off_reg->smin_value < 0) != (off_reg->smax_value < 0))
11873                         return REASON_BOUNDS;
11874
11875                 info->mask_to_left = (opcode == BPF_ADD &&  off_is_neg) ||
11876                                      (opcode == BPF_SUB && !off_is_neg);
11877         }
11878
11879         err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left);
11880         if (err < 0)
11881                 return err;
11882
11883         if (commit_window) {
11884                 /* In commit phase we narrow the masking window based on
11885                  * the observed pointer move after the simulated operation.
11886                  */
11887                 alu_state = info->aux.alu_state;
11888                 alu_limit = abs(info->aux.alu_limit - alu_limit);
11889         } else {
11890                 alu_state  = off_is_neg ? BPF_ALU_NEG_VALUE : 0;
11891                 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0;
11892                 alu_state |= ptr_is_dst_reg ?
11893                              BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST;
11894
11895                 /* Limit pruning on unknown scalars to enable deep search for
11896                  * potential masking differences from other program paths.
11897                  */
11898                 if (!off_is_imm)
11899                         env->explore_alu_limits = true;
11900         }
11901
11902         err = update_alu_sanitation_state(aux, alu_state, alu_limit);
11903         if (err < 0)
11904                 return err;
11905 do_sim:
11906         /* If we're in commit phase, we're done here given we already
11907          * pushed the truncated dst_reg into the speculative verification
11908          * stack.
11909          *
11910          * Also, when register is a known constant, we rewrite register-based
11911          * operation to immediate-based, and thus do not need masking (and as
11912          * a consequence, do not need to simulate the zero-truncation either).
11913          */
11914         if (commit_window || off_is_imm)
11915                 return 0;
11916
11917         /* Simulate and find potential out-of-bounds access under
11918          * speculative execution from truncation as a result of
11919          * masking when off was not within expected range. If off
11920          * sits in dst, then we temporarily need to move ptr there
11921          * to simulate dst (== 0) +/-= ptr. Needed, for example,
11922          * for cases where we use K-based arithmetic in one direction
11923          * and truncated reg-based in the other in order to explore
11924          * bad access.
11925          */
11926         if (!ptr_is_dst_reg) {
11927                 tmp = *dst_reg;
11928                 copy_register_state(dst_reg, ptr_reg);
11929         }
11930         ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1,
11931                                         env->insn_idx);
11932         if (!ptr_is_dst_reg && ret)
11933                 *dst_reg = tmp;
11934         return !ret ? REASON_STACK : 0;
11935 }
11936
11937 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
11938 {
11939         struct bpf_verifier_state *vstate = env->cur_state;
11940
11941         /* If we simulate paths under speculation, we don't update the
11942          * insn as 'seen' such that when we verify unreachable paths in
11943          * the non-speculative domain, sanitize_dead_code() can still
11944          * rewrite/sanitize them.
11945          */
11946         if (!vstate->speculative)
11947                 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt;
11948 }
11949
11950 static int sanitize_err(struct bpf_verifier_env *env,
11951                         const struct bpf_insn *insn, int reason,
11952                         const struct bpf_reg_state *off_reg,
11953                         const struct bpf_reg_state *dst_reg)
11954 {
11955         static const char *err = "pointer arithmetic with it prohibited for !root";
11956         const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub";
11957         u32 dst = insn->dst_reg, src = insn->src_reg;
11958
11959         switch (reason) {
11960         case REASON_BOUNDS:
11961                 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n",
11962                         off_reg == dst_reg ? dst : src, err);
11963                 break;
11964         case REASON_TYPE:
11965                 verbose(env, "R%d has pointer with unsupported alu operation, %s\n",
11966                         off_reg == dst_reg ? src : dst, err);
11967                 break;
11968         case REASON_PATHS:
11969                 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n",
11970                         dst, op, err);
11971                 break;
11972         case REASON_LIMIT:
11973                 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n",
11974                         dst, op, err);
11975                 break;
11976         case REASON_STACK:
11977                 verbose(env, "R%d could not be pushed for speculative verification, %s\n",
11978                         dst, err);
11979                 break;
11980         default:
11981                 verbose(env, "verifier internal error: unknown reason (%d)\n",
11982                         reason);
11983                 break;
11984         }
11985
11986         return -EACCES;
11987 }
11988
11989 /* check that stack access falls within stack limits and that 'reg' doesn't
11990  * have a variable offset.
11991  *
11992  * Variable offset is prohibited for unprivileged mode for simplicity since it
11993  * requires corresponding support in Spectre masking for stack ALU.  See also
11994  * retrieve_ptr_limit().
11995  *
11996  *
11997  * 'off' includes 'reg->off'.
11998  */
11999 static int check_stack_access_for_ptr_arithmetic(
12000                                 struct bpf_verifier_env *env,
12001                                 int regno,
12002                                 const struct bpf_reg_state *reg,
12003                                 int off)
12004 {
12005         if (!tnum_is_const(reg->var_off)) {
12006                 char tn_buf[48];
12007
12008                 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);
12009                 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n",
12010                         regno, tn_buf, off);
12011                 return -EACCES;
12012         }
12013
12014         if (off >= 0 || off < -MAX_BPF_STACK) {
12015                 verbose(env, "R%d stack pointer arithmetic goes out of range, "
12016                         "prohibited for !root; off=%d\n", regno, off);
12017                 return -EACCES;
12018         }
12019
12020         return 0;
12021 }
12022
12023 static int sanitize_check_bounds(struct bpf_verifier_env *env,
12024                                  const struct bpf_insn *insn,
12025                                  const struct bpf_reg_state *dst_reg)
12026 {
12027         u32 dst = insn->dst_reg;
12028
12029         /* For unprivileged we require that resulting offset must be in bounds
12030          * in order to be able to sanitize access later on.
12031          */
12032         if (env->bypass_spec_v1)
12033                 return 0;
12034
12035         switch (dst_reg->type) {
12036         case PTR_TO_STACK:
12037                 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg,
12038                                         dst_reg->off + dst_reg->var_off.value))
12039                         return -EACCES;
12040                 break;
12041         case PTR_TO_MAP_VALUE:
12042                 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) {
12043                         verbose(env, "R%d pointer arithmetic of map value goes out of range, "
12044                                 "prohibited for !root\n", dst);
12045                         return -EACCES;
12046                 }
12047                 break;
12048         default:
12049                 break;
12050         }
12051
12052         return 0;
12053 }
12054
12055 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off.
12056  * Caller should also handle BPF_MOV case separately.
12057  * If we return -EACCES, caller may want to try again treating pointer as a
12058  * scalar.  So we only emit a diagnostic if !env->allow_ptr_leaks.
12059  */
12060 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env,
12061                                    struct bpf_insn *insn,
12062                                    const struct bpf_reg_state *ptr_reg,
12063                                    const struct bpf_reg_state *off_reg)
12064 {
12065         struct bpf_verifier_state *vstate = env->cur_state;
12066         struct bpf_func_state *state = vstate->frame[vstate->curframe];
12067         struct bpf_reg_state *regs = state->regs, *dst_reg;
12068         bool known = tnum_is_const(off_reg->var_off);
12069         s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value,
12070             smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value;
12071         u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value,
12072             umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value;
12073         struct bpf_sanitize_info info = {};
12074         u8 opcode = BPF_OP(insn->code);
12075         u32 dst = insn->dst_reg;
12076         int ret;
12077
12078         dst_reg = &regs[dst];
12079
12080         if ((known && (smin_val != smax_val || umin_val != umax_val)) ||
12081             smin_val > smax_val || umin_val > umax_val) {
12082                 /* Taint dst register if offset had invalid bounds derived from
12083                  * e.g. dead branches.
12084                  */
12085                 __mark_reg_unknown(env, dst_reg);
12086                 return 0;
12087         }
12088
12089         if (BPF_CLASS(insn->code) != BPF_ALU64) {
12090                 /* 32-bit ALU ops on pointers produce (meaningless) scalars */
12091                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
12092                         __mark_reg_unknown(env, dst_reg);
12093                         return 0;
12094                 }
12095
12096                 verbose(env,
12097                         "R%d 32-bit pointer arithmetic prohibited\n",
12098                         dst);
12099                 return -EACCES;
12100         }
12101
12102         if (ptr_reg->type & PTR_MAYBE_NULL) {
12103                 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n",
12104                         dst, reg_type_str(env, ptr_reg->type));
12105                 return -EACCES;
12106         }
12107
12108         switch (base_type(ptr_reg->type)) {
12109         case CONST_PTR_TO_MAP:
12110                 /* smin_val represents the known value */
12111                 if (known && smin_val == 0 && opcode == BPF_ADD)
12112                         break;
12113                 fallthrough;
12114         case PTR_TO_PACKET_END:
12115         case PTR_TO_SOCKET:
12116         case PTR_TO_SOCK_COMMON:
12117         case PTR_TO_TCP_SOCK:
12118         case PTR_TO_XDP_SOCK:
12119                 verbose(env, "R%d pointer arithmetic on %s prohibited\n",
12120                         dst, reg_type_str(env, ptr_reg->type));
12121                 return -EACCES;
12122         default:
12123                 break;
12124         }
12125
12126         /* In case of 'scalar += pointer', dst_reg inherits pointer type and id.
12127          * The id may be overwritten later if we create a new variable offset.
12128          */
12129         dst_reg->type = ptr_reg->type;
12130         dst_reg->id = ptr_reg->id;
12131
12132         if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) ||
12133             !check_reg_sane_offset(env, ptr_reg, ptr_reg->type))
12134                 return -EINVAL;
12135
12136         /* pointer types do not carry 32-bit bounds at the moment. */
12137         __mark_reg32_unbounded(dst_reg);
12138
12139         if (sanitize_needed(opcode)) {
12140                 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg,
12141                                        &info, false);
12142                 if (ret < 0)
12143                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12144         }
12145
12146         switch (opcode) {
12147         case BPF_ADD:
12148                 /* We can take a fixed offset as long as it doesn't overflow
12149                  * the s32 'off' field
12150                  */
12151                 if (known && (ptr_reg->off + smin_val ==
12152                               (s64)(s32)(ptr_reg->off + smin_val))) {
12153                         /* pointer += K.  Accumulate it into fixed offset */
12154                         dst_reg->smin_value = smin_ptr;
12155                         dst_reg->smax_value = smax_ptr;
12156                         dst_reg->umin_value = umin_ptr;
12157                         dst_reg->umax_value = umax_ptr;
12158                         dst_reg->var_off = ptr_reg->var_off;
12159                         dst_reg->off = ptr_reg->off + smin_val;
12160                         dst_reg->raw = ptr_reg->raw;
12161                         break;
12162                 }
12163                 /* A new variable offset is created.  Note that off_reg->off
12164                  * == 0, since it's a scalar.
12165                  * dst_reg gets the pointer type and since some positive
12166                  * integer value was added to the pointer, give it a new 'id'
12167                  * if it's a PTR_TO_PACKET.
12168                  * this creates a new 'base' pointer, off_reg (variable) gets
12169                  * added into the variable offset, and we copy the fixed offset
12170                  * from ptr_reg.
12171                  */
12172                 if (signed_add_overflows(smin_ptr, smin_val) ||
12173                     signed_add_overflows(smax_ptr, smax_val)) {
12174                         dst_reg->smin_value = S64_MIN;
12175                         dst_reg->smax_value = S64_MAX;
12176                 } else {
12177                         dst_reg->smin_value = smin_ptr + smin_val;
12178                         dst_reg->smax_value = smax_ptr + smax_val;
12179                 }
12180                 if (umin_ptr + umin_val < umin_ptr ||
12181                     umax_ptr + umax_val < umax_ptr) {
12182                         dst_reg->umin_value = 0;
12183                         dst_reg->umax_value = U64_MAX;
12184                 } else {
12185                         dst_reg->umin_value = umin_ptr + umin_val;
12186                         dst_reg->umax_value = umax_ptr + umax_val;
12187                 }
12188                 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off);
12189                 dst_reg->off = ptr_reg->off;
12190                 dst_reg->raw = ptr_reg->raw;
12191                 if (reg_is_pkt_pointer(ptr_reg)) {
12192                         dst_reg->id = ++env->id_gen;
12193                         /* something was added to pkt_ptr, set range to zero */
12194                         memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12195                 }
12196                 break;
12197         case BPF_SUB:
12198                 if (dst_reg == off_reg) {
12199                         /* scalar -= pointer.  Creates an unknown scalar */
12200                         verbose(env, "R%d tried to subtract pointer from scalar\n",
12201                                 dst);
12202                         return -EACCES;
12203                 }
12204                 /* We don't allow subtraction from FP, because (according to
12205                  * test_verifier.c test "invalid fp arithmetic", JITs might not
12206                  * be able to deal with it.
12207                  */
12208                 if (ptr_reg->type == PTR_TO_STACK) {
12209                         verbose(env, "R%d subtraction from stack pointer prohibited\n",
12210                                 dst);
12211                         return -EACCES;
12212                 }
12213                 if (known && (ptr_reg->off - smin_val ==
12214                               (s64)(s32)(ptr_reg->off - smin_val))) {
12215                         /* pointer -= K.  Subtract it from fixed offset */
12216                         dst_reg->smin_value = smin_ptr;
12217                         dst_reg->smax_value = smax_ptr;
12218                         dst_reg->umin_value = umin_ptr;
12219                         dst_reg->umax_value = umax_ptr;
12220                         dst_reg->var_off = ptr_reg->var_off;
12221                         dst_reg->id = ptr_reg->id;
12222                         dst_reg->off = ptr_reg->off - smin_val;
12223                         dst_reg->raw = ptr_reg->raw;
12224                         break;
12225                 }
12226                 /* A new variable offset is created.  If the subtrahend is known
12227                  * nonnegative, then any reg->range we had before is still good.
12228                  */
12229                 if (signed_sub_overflows(smin_ptr, smax_val) ||
12230                     signed_sub_overflows(smax_ptr, smin_val)) {
12231                         /* Overflow possible, we know nothing */
12232                         dst_reg->smin_value = S64_MIN;
12233                         dst_reg->smax_value = S64_MAX;
12234                 } else {
12235                         dst_reg->smin_value = smin_ptr - smax_val;
12236                         dst_reg->smax_value = smax_ptr - smin_val;
12237                 }
12238                 if (umin_ptr < umax_val) {
12239                         /* Overflow possible, we know nothing */
12240                         dst_reg->umin_value = 0;
12241                         dst_reg->umax_value = U64_MAX;
12242                 } else {
12243                         /* Cannot overflow (as long as bounds are consistent) */
12244                         dst_reg->umin_value = umin_ptr - umax_val;
12245                         dst_reg->umax_value = umax_ptr - umin_val;
12246                 }
12247                 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off);
12248                 dst_reg->off = ptr_reg->off;
12249                 dst_reg->raw = ptr_reg->raw;
12250                 if (reg_is_pkt_pointer(ptr_reg)) {
12251                         dst_reg->id = ++env->id_gen;
12252                         /* something was added to pkt_ptr, set range to zero */
12253                         if (smin_val < 0)
12254                                 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
12255                 }
12256                 break;
12257         case BPF_AND:
12258         case BPF_OR:
12259         case BPF_XOR:
12260                 /* bitwise ops on pointers are troublesome, prohibit. */
12261                 verbose(env, "R%d bitwise operator %s on pointer prohibited\n",
12262                         dst, bpf_alu_string[opcode >> 4]);
12263                 return -EACCES;
12264         default:
12265                 /* other operators (e.g. MUL,LSH) produce non-pointer results */
12266                 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n",
12267                         dst, bpf_alu_string[opcode >> 4]);
12268                 return -EACCES;
12269         }
12270
12271         if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type))
12272                 return -EINVAL;
12273         reg_bounds_sync(dst_reg);
12274         if (sanitize_check_bounds(env, insn, dst_reg) < 0)
12275                 return -EACCES;
12276         if (sanitize_needed(opcode)) {
12277                 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg,
12278                                        &info, true);
12279                 if (ret < 0)
12280                         return sanitize_err(env, insn, ret, off_reg, dst_reg);
12281         }
12282
12283         return 0;
12284 }
12285
12286 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg,
12287                                  struct bpf_reg_state *src_reg)
12288 {
12289         s32 smin_val = src_reg->s32_min_value;
12290         s32 smax_val = src_reg->s32_max_value;
12291         u32 umin_val = src_reg->u32_min_value;
12292         u32 umax_val = src_reg->u32_max_value;
12293
12294         if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) ||
12295             signed_add32_overflows(dst_reg->s32_max_value, smax_val)) {
12296                 dst_reg->s32_min_value = S32_MIN;
12297                 dst_reg->s32_max_value = S32_MAX;
12298         } else {
12299                 dst_reg->s32_min_value += smin_val;
12300                 dst_reg->s32_max_value += smax_val;
12301         }
12302         if (dst_reg->u32_min_value + umin_val < umin_val ||
12303             dst_reg->u32_max_value + umax_val < umax_val) {
12304                 dst_reg->u32_min_value = 0;
12305                 dst_reg->u32_max_value = U32_MAX;
12306         } else {
12307                 dst_reg->u32_min_value += umin_val;
12308                 dst_reg->u32_max_value += umax_val;
12309         }
12310 }
12311
12312 static void scalar_min_max_add(struct bpf_reg_state *dst_reg,
12313                                struct bpf_reg_state *src_reg)
12314 {
12315         s64 smin_val = src_reg->smin_value;
12316         s64 smax_val = src_reg->smax_value;
12317         u64 umin_val = src_reg->umin_value;
12318         u64 umax_val = src_reg->umax_value;
12319
12320         if (signed_add_overflows(dst_reg->smin_value, smin_val) ||
12321             signed_add_overflows(dst_reg->smax_value, smax_val)) {
12322                 dst_reg->smin_value = S64_MIN;
12323                 dst_reg->smax_value = S64_MAX;
12324         } else {
12325                 dst_reg->smin_value += smin_val;
12326                 dst_reg->smax_value += smax_val;
12327         }
12328         if (dst_reg->umin_value + umin_val < umin_val ||
12329             dst_reg->umax_value + umax_val < umax_val) {
12330                 dst_reg->umin_value = 0;
12331                 dst_reg->umax_value = U64_MAX;
12332         } else {
12333                 dst_reg->umin_value += umin_val;
12334                 dst_reg->umax_value += umax_val;
12335         }
12336 }
12337
12338 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg,
12339                                  struct bpf_reg_state *src_reg)
12340 {
12341         s32 smin_val = src_reg->s32_min_value;
12342         s32 smax_val = src_reg->s32_max_value;
12343         u32 umin_val = src_reg->u32_min_value;
12344         u32 umax_val = src_reg->u32_max_value;
12345
12346         if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) ||
12347             signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) {
12348                 /* Overflow possible, we know nothing */
12349                 dst_reg->s32_min_value = S32_MIN;
12350                 dst_reg->s32_max_value = S32_MAX;
12351         } else {
12352                 dst_reg->s32_min_value -= smax_val;
12353                 dst_reg->s32_max_value -= smin_val;
12354         }
12355         if (dst_reg->u32_min_value < umax_val) {
12356                 /* Overflow possible, we know nothing */
12357                 dst_reg->u32_min_value = 0;
12358                 dst_reg->u32_max_value = U32_MAX;
12359         } else {
12360                 /* Cannot overflow (as long as bounds are consistent) */
12361                 dst_reg->u32_min_value -= umax_val;
12362                 dst_reg->u32_max_value -= umin_val;
12363         }
12364 }
12365
12366 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg,
12367                                struct bpf_reg_state *src_reg)
12368 {
12369         s64 smin_val = src_reg->smin_value;
12370         s64 smax_val = src_reg->smax_value;
12371         u64 umin_val = src_reg->umin_value;
12372         u64 umax_val = src_reg->umax_value;
12373
12374         if (signed_sub_overflows(dst_reg->smin_value, smax_val) ||
12375             signed_sub_overflows(dst_reg->smax_value, smin_val)) {
12376                 /* Overflow possible, we know nothing */
12377                 dst_reg->smin_value = S64_MIN;
12378                 dst_reg->smax_value = S64_MAX;
12379         } else {
12380                 dst_reg->smin_value -= smax_val;
12381                 dst_reg->smax_value -= smin_val;
12382         }
12383         if (dst_reg->umin_value < umax_val) {
12384                 /* Overflow possible, we know nothing */
12385                 dst_reg->umin_value = 0;
12386                 dst_reg->umax_value = U64_MAX;
12387         } else {
12388                 /* Cannot overflow (as long as bounds are consistent) */
12389                 dst_reg->umin_value -= umax_val;
12390                 dst_reg->umax_value -= umin_val;
12391         }
12392 }
12393
12394 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg,
12395                                  struct bpf_reg_state *src_reg)
12396 {
12397         s32 smin_val = src_reg->s32_min_value;
12398         u32 umin_val = src_reg->u32_min_value;
12399         u32 umax_val = src_reg->u32_max_value;
12400
12401         if (smin_val < 0 || dst_reg->s32_min_value < 0) {
12402                 /* Ain't nobody got time to multiply that sign */
12403                 __mark_reg32_unbounded(dst_reg);
12404                 return;
12405         }
12406         /* Both values are positive, so we can work with unsigned and
12407          * copy the result to signed (unless it exceeds S32_MAX).
12408          */
12409         if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) {
12410                 /* Potential overflow, we know nothing */
12411                 __mark_reg32_unbounded(dst_reg);
12412                 return;
12413         }
12414         dst_reg->u32_min_value *= umin_val;
12415         dst_reg->u32_max_value *= umax_val;
12416         if (dst_reg->u32_max_value > S32_MAX) {
12417                 /* Overflow possible, we know nothing */
12418                 dst_reg->s32_min_value = S32_MIN;
12419                 dst_reg->s32_max_value = S32_MAX;
12420         } else {
12421                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12422                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12423         }
12424 }
12425
12426 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg,
12427                                struct bpf_reg_state *src_reg)
12428 {
12429         s64 smin_val = src_reg->smin_value;
12430         u64 umin_val = src_reg->umin_value;
12431         u64 umax_val = src_reg->umax_value;
12432
12433         if (smin_val < 0 || dst_reg->smin_value < 0) {
12434                 /* Ain't nobody got time to multiply that sign */
12435                 __mark_reg64_unbounded(dst_reg);
12436                 return;
12437         }
12438         /* Both values are positive, so we can work with unsigned and
12439          * copy the result to signed (unless it exceeds S64_MAX).
12440          */
12441         if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) {
12442                 /* Potential overflow, we know nothing */
12443                 __mark_reg64_unbounded(dst_reg);
12444                 return;
12445         }
12446         dst_reg->umin_value *= umin_val;
12447         dst_reg->umax_value *= umax_val;
12448         if (dst_reg->umax_value > S64_MAX) {
12449                 /* Overflow possible, we know nothing */
12450                 dst_reg->smin_value = S64_MIN;
12451                 dst_reg->smax_value = S64_MAX;
12452         } else {
12453                 dst_reg->smin_value = dst_reg->umin_value;
12454                 dst_reg->smax_value = dst_reg->umax_value;
12455         }
12456 }
12457
12458 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg,
12459                                  struct bpf_reg_state *src_reg)
12460 {
12461         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12462         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12463         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12464         s32 smin_val = src_reg->s32_min_value;
12465         u32 umax_val = src_reg->u32_max_value;
12466
12467         if (src_known && dst_known) {
12468                 __mark_reg32_known(dst_reg, var32_off.value);
12469                 return;
12470         }
12471
12472         /* We get our minimum from the var_off, since that's inherently
12473          * bitwise.  Our maximum is the minimum of the operands' maxima.
12474          */
12475         dst_reg->u32_min_value = var32_off.value;
12476         dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val);
12477         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12478                 /* Lose signed bounds when ANDing negative numbers,
12479                  * ain't nobody got time for that.
12480                  */
12481                 dst_reg->s32_min_value = S32_MIN;
12482                 dst_reg->s32_max_value = S32_MAX;
12483         } else {
12484                 /* ANDing two positives gives a positive, so safe to
12485                  * cast result into s64.
12486                  */
12487                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12488                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12489         }
12490 }
12491
12492 static void scalar_min_max_and(struct bpf_reg_state *dst_reg,
12493                                struct bpf_reg_state *src_reg)
12494 {
12495         bool src_known = tnum_is_const(src_reg->var_off);
12496         bool dst_known = tnum_is_const(dst_reg->var_off);
12497         s64 smin_val = src_reg->smin_value;
12498         u64 umax_val = src_reg->umax_value;
12499
12500         if (src_known && dst_known) {
12501                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12502                 return;
12503         }
12504
12505         /* We get our minimum from the var_off, since that's inherently
12506          * bitwise.  Our maximum is the minimum of the operands' maxima.
12507          */
12508         dst_reg->umin_value = dst_reg->var_off.value;
12509         dst_reg->umax_value = min(dst_reg->umax_value, umax_val);
12510         if (dst_reg->smin_value < 0 || smin_val < 0) {
12511                 /* Lose signed bounds when ANDing negative numbers,
12512                  * ain't nobody got time for that.
12513                  */
12514                 dst_reg->smin_value = S64_MIN;
12515                 dst_reg->smax_value = S64_MAX;
12516         } else {
12517                 /* ANDing two positives gives a positive, so safe to
12518                  * cast result into s64.
12519                  */
12520                 dst_reg->smin_value = dst_reg->umin_value;
12521                 dst_reg->smax_value = dst_reg->umax_value;
12522         }
12523         /* We may learn something more from the var_off */
12524         __update_reg_bounds(dst_reg);
12525 }
12526
12527 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg,
12528                                 struct bpf_reg_state *src_reg)
12529 {
12530         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12531         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12532         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12533         s32 smin_val = src_reg->s32_min_value;
12534         u32 umin_val = src_reg->u32_min_value;
12535
12536         if (src_known && dst_known) {
12537                 __mark_reg32_known(dst_reg, var32_off.value);
12538                 return;
12539         }
12540
12541         /* We get our maximum from the var_off, and our minimum is the
12542          * maximum of the operands' minima
12543          */
12544         dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val);
12545         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12546         if (dst_reg->s32_min_value < 0 || smin_val < 0) {
12547                 /* Lose signed bounds when ORing negative numbers,
12548                  * ain't nobody got time for that.
12549                  */
12550                 dst_reg->s32_min_value = S32_MIN;
12551                 dst_reg->s32_max_value = S32_MAX;
12552         } else {
12553                 /* ORing two positives gives a positive, so safe to
12554                  * cast result into s64.
12555                  */
12556                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12557                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12558         }
12559 }
12560
12561 static void scalar_min_max_or(struct bpf_reg_state *dst_reg,
12562                               struct bpf_reg_state *src_reg)
12563 {
12564         bool src_known = tnum_is_const(src_reg->var_off);
12565         bool dst_known = tnum_is_const(dst_reg->var_off);
12566         s64 smin_val = src_reg->smin_value;
12567         u64 umin_val = src_reg->umin_value;
12568
12569         if (src_known && dst_known) {
12570                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12571                 return;
12572         }
12573
12574         /* We get our maximum from the var_off, and our minimum is the
12575          * maximum of the operands' minima
12576          */
12577         dst_reg->umin_value = max(dst_reg->umin_value, umin_val);
12578         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12579         if (dst_reg->smin_value < 0 || smin_val < 0) {
12580                 /* Lose signed bounds when ORing negative numbers,
12581                  * ain't nobody got time for that.
12582                  */
12583                 dst_reg->smin_value = S64_MIN;
12584                 dst_reg->smax_value = S64_MAX;
12585         } else {
12586                 /* ORing two positives gives a positive, so safe to
12587                  * cast result into s64.
12588                  */
12589                 dst_reg->smin_value = dst_reg->umin_value;
12590                 dst_reg->smax_value = dst_reg->umax_value;
12591         }
12592         /* We may learn something more from the var_off */
12593         __update_reg_bounds(dst_reg);
12594 }
12595
12596 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg,
12597                                  struct bpf_reg_state *src_reg)
12598 {
12599         bool src_known = tnum_subreg_is_const(src_reg->var_off);
12600         bool dst_known = tnum_subreg_is_const(dst_reg->var_off);
12601         struct tnum var32_off = tnum_subreg(dst_reg->var_off);
12602         s32 smin_val = src_reg->s32_min_value;
12603
12604         if (src_known && dst_known) {
12605                 __mark_reg32_known(dst_reg, var32_off.value);
12606                 return;
12607         }
12608
12609         /* We get both minimum and maximum from the var32_off. */
12610         dst_reg->u32_min_value = var32_off.value;
12611         dst_reg->u32_max_value = var32_off.value | var32_off.mask;
12612
12613         if (dst_reg->s32_min_value >= 0 && smin_val >= 0) {
12614                 /* XORing two positive sign numbers gives a positive,
12615                  * so safe to cast u32 result into s32.
12616                  */
12617                 dst_reg->s32_min_value = dst_reg->u32_min_value;
12618                 dst_reg->s32_max_value = dst_reg->u32_max_value;
12619         } else {
12620                 dst_reg->s32_min_value = S32_MIN;
12621                 dst_reg->s32_max_value = S32_MAX;
12622         }
12623 }
12624
12625 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg,
12626                                struct bpf_reg_state *src_reg)
12627 {
12628         bool src_known = tnum_is_const(src_reg->var_off);
12629         bool dst_known = tnum_is_const(dst_reg->var_off);
12630         s64 smin_val = src_reg->smin_value;
12631
12632         if (src_known && dst_known) {
12633                 /* dst_reg->var_off.value has been updated earlier */
12634                 __mark_reg_known(dst_reg, dst_reg->var_off.value);
12635                 return;
12636         }
12637
12638         /* We get both minimum and maximum from the var_off. */
12639         dst_reg->umin_value = dst_reg->var_off.value;
12640         dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask;
12641
12642         if (dst_reg->smin_value >= 0 && smin_val >= 0) {
12643                 /* XORing two positive sign numbers gives a positive,
12644                  * so safe to cast u64 result into s64.
12645                  */
12646                 dst_reg->smin_value = dst_reg->umin_value;
12647                 dst_reg->smax_value = dst_reg->umax_value;
12648         } else {
12649                 dst_reg->smin_value = S64_MIN;
12650                 dst_reg->smax_value = S64_MAX;
12651         }
12652
12653         __update_reg_bounds(dst_reg);
12654 }
12655
12656 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12657                                    u64 umin_val, u64 umax_val)
12658 {
12659         /* We lose all sign bit information (except what we can pick
12660          * up from var_off)
12661          */
12662         dst_reg->s32_min_value = S32_MIN;
12663         dst_reg->s32_max_value = S32_MAX;
12664         /* If we might shift our top bit out, then we know nothing */
12665         if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) {
12666                 dst_reg->u32_min_value = 0;
12667                 dst_reg->u32_max_value = U32_MAX;
12668         } else {
12669                 dst_reg->u32_min_value <<= umin_val;
12670                 dst_reg->u32_max_value <<= umax_val;
12671         }
12672 }
12673
12674 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg,
12675                                  struct bpf_reg_state *src_reg)
12676 {
12677         u32 umax_val = src_reg->u32_max_value;
12678         u32 umin_val = src_reg->u32_min_value;
12679         /* u32 alu operation will zext upper bits */
12680         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12681
12682         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12683         dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val));
12684         /* Not required but being careful mark reg64 bounds as unknown so
12685          * that we are forced to pick them up from tnum and zext later and
12686          * if some path skips this step we are still safe.
12687          */
12688         __mark_reg64_unbounded(dst_reg);
12689         __update_reg32_bounds(dst_reg);
12690 }
12691
12692 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg,
12693                                    u64 umin_val, u64 umax_val)
12694 {
12695         /* Special case <<32 because it is a common compiler pattern to sign
12696          * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are
12697          * positive we know this shift will also be positive so we can track
12698          * bounds correctly. Otherwise we lose all sign bit information except
12699          * what we can pick up from var_off. Perhaps we can generalize this
12700          * later to shifts of any length.
12701          */
12702         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0)
12703                 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32;
12704         else
12705                 dst_reg->smax_value = S64_MAX;
12706
12707         if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0)
12708                 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32;
12709         else
12710                 dst_reg->smin_value = S64_MIN;
12711
12712         /* If we might shift our top bit out, then we know nothing */
12713         if (dst_reg->umax_value > 1ULL << (63 - umax_val)) {
12714                 dst_reg->umin_value = 0;
12715                 dst_reg->umax_value = U64_MAX;
12716         } else {
12717                 dst_reg->umin_value <<= umin_val;
12718                 dst_reg->umax_value <<= umax_val;
12719         }
12720 }
12721
12722 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg,
12723                                struct bpf_reg_state *src_reg)
12724 {
12725         u64 umax_val = src_reg->umax_value;
12726         u64 umin_val = src_reg->umin_value;
12727
12728         /* scalar64 calc uses 32bit unshifted bounds so must be called first */
12729         __scalar64_min_max_lsh(dst_reg, umin_val, umax_val);
12730         __scalar32_min_max_lsh(dst_reg, umin_val, umax_val);
12731
12732         dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val);
12733         /* We may learn something more from the var_off */
12734         __update_reg_bounds(dst_reg);
12735 }
12736
12737 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg,
12738                                  struct bpf_reg_state *src_reg)
12739 {
12740         struct tnum subreg = tnum_subreg(dst_reg->var_off);
12741         u32 umax_val = src_reg->u32_max_value;
12742         u32 umin_val = src_reg->u32_min_value;
12743
12744         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12745          * be negative, then either:
12746          * 1) src_reg might be zero, so the sign bit of the result is
12747          *    unknown, so we lose our signed bounds
12748          * 2) it's known negative, thus the unsigned bounds capture the
12749          *    signed bounds
12750          * 3) the signed bounds cross zero, so they tell us nothing
12751          *    about the result
12752          * If the value in dst_reg is known nonnegative, then again the
12753          * unsigned bounds capture the signed bounds.
12754          * Thus, in all cases it suffices to blow away our signed bounds
12755          * and rely on inferring new ones from the unsigned bounds and
12756          * var_off of the result.
12757          */
12758         dst_reg->s32_min_value = S32_MIN;
12759         dst_reg->s32_max_value = S32_MAX;
12760
12761         dst_reg->var_off = tnum_rshift(subreg, umin_val);
12762         dst_reg->u32_min_value >>= umax_val;
12763         dst_reg->u32_max_value >>= umin_val;
12764
12765         __mark_reg64_unbounded(dst_reg);
12766         __update_reg32_bounds(dst_reg);
12767 }
12768
12769 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg,
12770                                struct bpf_reg_state *src_reg)
12771 {
12772         u64 umax_val = src_reg->umax_value;
12773         u64 umin_val = src_reg->umin_value;
12774
12775         /* BPF_RSH is an unsigned shift.  If the value in dst_reg might
12776          * be negative, then either:
12777          * 1) src_reg might be zero, so the sign bit of the result is
12778          *    unknown, so we lose our signed bounds
12779          * 2) it's known negative, thus the unsigned bounds capture the
12780          *    signed bounds
12781          * 3) the signed bounds cross zero, so they tell us nothing
12782          *    about the result
12783          * If the value in dst_reg is known nonnegative, then again the
12784          * unsigned bounds capture the signed bounds.
12785          * Thus, in all cases it suffices to blow away our signed bounds
12786          * and rely on inferring new ones from the unsigned bounds and
12787          * var_off of the result.
12788          */
12789         dst_reg->smin_value = S64_MIN;
12790         dst_reg->smax_value = S64_MAX;
12791         dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val);
12792         dst_reg->umin_value >>= umax_val;
12793         dst_reg->umax_value >>= umin_val;
12794
12795         /* Its not easy to operate on alu32 bounds here because it depends
12796          * on bits being shifted in. Take easy way out and mark unbounded
12797          * so we can recalculate later from tnum.
12798          */
12799         __mark_reg32_unbounded(dst_reg);
12800         __update_reg_bounds(dst_reg);
12801 }
12802
12803 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg,
12804                                   struct bpf_reg_state *src_reg)
12805 {
12806         u64 umin_val = src_reg->u32_min_value;
12807
12808         /* Upon reaching here, src_known is true and
12809          * umax_val is equal to umin_val.
12810          */
12811         dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val);
12812         dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val);
12813
12814         dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32);
12815
12816         /* blow away the dst_reg umin_value/umax_value and rely on
12817          * dst_reg var_off to refine the result.
12818          */
12819         dst_reg->u32_min_value = 0;
12820         dst_reg->u32_max_value = U32_MAX;
12821
12822         __mark_reg64_unbounded(dst_reg);
12823         __update_reg32_bounds(dst_reg);
12824 }
12825
12826 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg,
12827                                 struct bpf_reg_state *src_reg)
12828 {
12829         u64 umin_val = src_reg->umin_value;
12830
12831         /* Upon reaching here, src_known is true and umax_val is equal
12832          * to umin_val.
12833          */
12834         dst_reg->smin_value >>= umin_val;
12835         dst_reg->smax_value >>= umin_val;
12836
12837         dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64);
12838
12839         /* blow away the dst_reg umin_value/umax_value and rely on
12840          * dst_reg var_off to refine the result.
12841          */
12842         dst_reg->umin_value = 0;
12843         dst_reg->umax_value = U64_MAX;
12844
12845         /* Its not easy to operate on alu32 bounds here because it depends
12846          * on bits being shifted in from upper 32-bits. Take easy way out
12847          * and mark unbounded so we can recalculate later from tnum.
12848          */
12849         __mark_reg32_unbounded(dst_reg);
12850         __update_reg_bounds(dst_reg);
12851 }
12852
12853 /* WARNING: This function does calculations on 64-bit values, but the actual
12854  * execution may occur on 32-bit values. Therefore, things like bitshifts
12855  * need extra checks in the 32-bit case.
12856  */
12857 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env,
12858                                       struct bpf_insn *insn,
12859                                       struct bpf_reg_state *dst_reg,
12860                                       struct bpf_reg_state src_reg)
12861 {
12862         struct bpf_reg_state *regs = cur_regs(env);
12863         u8 opcode = BPF_OP(insn->code);
12864         bool src_known;
12865         s64 smin_val, smax_val;
12866         u64 umin_val, umax_val;
12867         s32 s32_min_val, s32_max_val;
12868         u32 u32_min_val, u32_max_val;
12869         u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32;
12870         bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64);
12871         int ret;
12872
12873         smin_val = src_reg.smin_value;
12874         smax_val = src_reg.smax_value;
12875         umin_val = src_reg.umin_value;
12876         umax_val = src_reg.umax_value;
12877
12878         s32_min_val = src_reg.s32_min_value;
12879         s32_max_val = src_reg.s32_max_value;
12880         u32_min_val = src_reg.u32_min_value;
12881         u32_max_val = src_reg.u32_max_value;
12882
12883         if (alu32) {
12884                 src_known = tnum_subreg_is_const(src_reg.var_off);
12885                 if ((src_known &&
12886                      (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) ||
12887                     s32_min_val > s32_max_val || u32_min_val > u32_max_val) {
12888                         /* Taint dst register if offset had invalid bounds
12889                          * derived from e.g. dead branches.
12890                          */
12891                         __mark_reg_unknown(env, dst_reg);
12892                         return 0;
12893                 }
12894         } else {
12895                 src_known = tnum_is_const(src_reg.var_off);
12896                 if ((src_known &&
12897                      (smin_val != smax_val || umin_val != umax_val)) ||
12898                     smin_val > smax_val || umin_val > umax_val) {
12899                         /* Taint dst register if offset had invalid bounds
12900                          * derived from e.g. dead branches.
12901                          */
12902                         __mark_reg_unknown(env, dst_reg);
12903                         return 0;
12904                 }
12905         }
12906
12907         if (!src_known &&
12908             opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) {
12909                 __mark_reg_unknown(env, dst_reg);
12910                 return 0;
12911         }
12912
12913         if (sanitize_needed(opcode)) {
12914                 ret = sanitize_val_alu(env, insn);
12915                 if (ret < 0)
12916                         return sanitize_err(env, insn, ret, NULL, NULL);
12917         }
12918
12919         /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops.
12920          * There are two classes of instructions: The first class we track both
12921          * alu32 and alu64 sign/unsigned bounds independently this provides the
12922          * greatest amount of precision when alu operations are mixed with jmp32
12923          * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD,
12924          * and BPF_OR. This is possible because these ops have fairly easy to
12925          * understand and calculate behavior in both 32-bit and 64-bit alu ops.
12926          * See alu32 verifier tests for examples. The second class of
12927          * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy
12928          * with regards to tracking sign/unsigned bounds because the bits may
12929          * cross subreg boundaries in the alu64 case. When this happens we mark
12930          * the reg unbounded in the subreg bound space and use the resulting
12931          * tnum to calculate an approximation of the sign/unsigned bounds.
12932          */
12933         switch (opcode) {
12934         case BPF_ADD:
12935                 scalar32_min_max_add(dst_reg, &src_reg);
12936                 scalar_min_max_add(dst_reg, &src_reg);
12937                 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off);
12938                 break;
12939         case BPF_SUB:
12940                 scalar32_min_max_sub(dst_reg, &src_reg);
12941                 scalar_min_max_sub(dst_reg, &src_reg);
12942                 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off);
12943                 break;
12944         case BPF_MUL:
12945                 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off);
12946                 scalar32_min_max_mul(dst_reg, &src_reg);
12947                 scalar_min_max_mul(dst_reg, &src_reg);
12948                 break;
12949         case BPF_AND:
12950                 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off);
12951                 scalar32_min_max_and(dst_reg, &src_reg);
12952                 scalar_min_max_and(dst_reg, &src_reg);
12953                 break;
12954         case BPF_OR:
12955                 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off);
12956                 scalar32_min_max_or(dst_reg, &src_reg);
12957                 scalar_min_max_or(dst_reg, &src_reg);
12958                 break;
12959         case BPF_XOR:
12960                 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off);
12961                 scalar32_min_max_xor(dst_reg, &src_reg);
12962                 scalar_min_max_xor(dst_reg, &src_reg);
12963                 break;
12964         case BPF_LSH:
12965                 if (umax_val >= insn_bitness) {
12966                         /* Shifts greater than 31 or 63 are undefined.
12967                          * This includes shifts by a negative number.
12968                          */
12969                         mark_reg_unknown(env, regs, insn->dst_reg);
12970                         break;
12971                 }
12972                 if (alu32)
12973                         scalar32_min_max_lsh(dst_reg, &src_reg);
12974                 else
12975                         scalar_min_max_lsh(dst_reg, &src_reg);
12976                 break;
12977         case BPF_RSH:
12978                 if (umax_val >= insn_bitness) {
12979                         /* Shifts greater than 31 or 63 are undefined.
12980                          * This includes shifts by a negative number.
12981                          */
12982                         mark_reg_unknown(env, regs, insn->dst_reg);
12983                         break;
12984                 }
12985                 if (alu32)
12986                         scalar32_min_max_rsh(dst_reg, &src_reg);
12987                 else
12988                         scalar_min_max_rsh(dst_reg, &src_reg);
12989                 break;
12990         case BPF_ARSH:
12991                 if (umax_val >= insn_bitness) {
12992                         /* Shifts greater than 31 or 63 are undefined.
12993                          * This includes shifts by a negative number.
12994                          */
12995                         mark_reg_unknown(env, regs, insn->dst_reg);
12996                         break;
12997                 }
12998                 if (alu32)
12999                         scalar32_min_max_arsh(dst_reg, &src_reg);
13000                 else
13001                         scalar_min_max_arsh(dst_reg, &src_reg);
13002                 break;
13003         default:
13004                 mark_reg_unknown(env, regs, insn->dst_reg);
13005                 break;
13006         }
13007
13008         /* ALU32 ops are zero extended into 64bit register */
13009         if (alu32)
13010                 zext_32_to_64(dst_reg);
13011         reg_bounds_sync(dst_reg);
13012         return 0;
13013 }
13014
13015 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max
13016  * and var_off.
13017  */
13018 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env,
13019                                    struct bpf_insn *insn)
13020 {
13021         struct bpf_verifier_state *vstate = env->cur_state;
13022         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13023         struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg;
13024         struct bpf_reg_state *ptr_reg = NULL, off_reg = {0};
13025         u8 opcode = BPF_OP(insn->code);
13026         int err;
13027
13028         dst_reg = &regs[insn->dst_reg];
13029         src_reg = NULL;
13030         if (dst_reg->type != SCALAR_VALUE)
13031                 ptr_reg = dst_reg;
13032         else
13033                 /* Make sure ID is cleared otherwise dst_reg min/max could be
13034                  * incorrectly propagated into other registers by find_equal_scalars()
13035                  */
13036                 dst_reg->id = 0;
13037         if (BPF_SRC(insn->code) == BPF_X) {
13038                 src_reg = &regs[insn->src_reg];
13039                 if (src_reg->type != SCALAR_VALUE) {
13040                         if (dst_reg->type != SCALAR_VALUE) {
13041                                 /* Combining two pointers by any ALU op yields
13042                                  * an arbitrary scalar. Disallow all math except
13043                                  * pointer subtraction
13044                                  */
13045                                 if (opcode == BPF_SUB && env->allow_ptr_leaks) {
13046                                         mark_reg_unknown(env, regs, insn->dst_reg);
13047                                         return 0;
13048                                 }
13049                                 verbose(env, "R%d pointer %s pointer prohibited\n",
13050                                         insn->dst_reg,
13051                                         bpf_alu_string[opcode >> 4]);
13052                                 return -EACCES;
13053                         } else {
13054                                 /* scalar += pointer
13055                                  * This is legal, but we have to reverse our
13056                                  * src/dest handling in computing the range
13057                                  */
13058                                 err = mark_chain_precision(env, insn->dst_reg);
13059                                 if (err)
13060                                         return err;
13061                                 return adjust_ptr_min_max_vals(env, insn,
13062                                                                src_reg, dst_reg);
13063                         }
13064                 } else if (ptr_reg) {
13065                         /* pointer += scalar */
13066                         err = mark_chain_precision(env, insn->src_reg);
13067                         if (err)
13068                                 return err;
13069                         return adjust_ptr_min_max_vals(env, insn,
13070                                                        dst_reg, src_reg);
13071                 } else if (dst_reg->precise) {
13072                         /* if dst_reg is precise, src_reg should be precise as well */
13073                         err = mark_chain_precision(env, insn->src_reg);
13074                         if (err)
13075                                 return err;
13076                 }
13077         } else {
13078                 /* Pretend the src is a reg with a known value, since we only
13079                  * need to be able to read from this state.
13080                  */
13081                 off_reg.type = SCALAR_VALUE;
13082                 __mark_reg_known(&off_reg, insn->imm);
13083                 src_reg = &off_reg;
13084                 if (ptr_reg) /* pointer += K */
13085                         return adjust_ptr_min_max_vals(env, insn,
13086                                                        ptr_reg, src_reg);
13087         }
13088
13089         /* Got here implies adding two SCALAR_VALUEs */
13090         if (WARN_ON_ONCE(ptr_reg)) {
13091                 print_verifier_state(env, state, true);
13092                 verbose(env, "verifier internal error: unexpected ptr_reg\n");
13093                 return -EINVAL;
13094         }
13095         if (WARN_ON(!src_reg)) {
13096                 print_verifier_state(env, state, true);
13097                 verbose(env, "verifier internal error: no src_reg\n");
13098                 return -EINVAL;
13099         }
13100         return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg);
13101 }
13102
13103 /* check validity of 32-bit and 64-bit arithmetic operations */
13104 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
13105 {
13106         struct bpf_reg_state *regs = cur_regs(env);
13107         u8 opcode = BPF_OP(insn->code);
13108         int err;
13109
13110         if (opcode == BPF_END || opcode == BPF_NEG) {
13111                 if (opcode == BPF_NEG) {
13112                         if (BPF_SRC(insn->code) != BPF_K ||
13113                             insn->src_reg != BPF_REG_0 ||
13114                             insn->off != 0 || insn->imm != 0) {
13115                                 verbose(env, "BPF_NEG uses reserved fields\n");
13116                                 return -EINVAL;
13117                         }
13118                 } else {
13119                         if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
13120                             (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
13121                             (BPF_CLASS(insn->code) == BPF_ALU64 &&
13122                              BPF_SRC(insn->code) != BPF_TO_LE)) {
13123                                 verbose(env, "BPF_END uses reserved fields\n");
13124                                 return -EINVAL;
13125                         }
13126                 }
13127
13128                 /* check src operand */
13129                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13130                 if (err)
13131                         return err;
13132
13133                 if (is_pointer_value(env, insn->dst_reg)) {
13134                         verbose(env, "R%d pointer arithmetic prohibited\n",
13135                                 insn->dst_reg);
13136                         return -EACCES;
13137                 }
13138
13139                 /* check dest operand */
13140                 err = check_reg_arg(env, insn->dst_reg, DST_OP);
13141                 if (err)
13142                         return err;
13143
13144         } else if (opcode == BPF_MOV) {
13145
13146                 if (BPF_SRC(insn->code) == BPF_X) {
13147                         if (insn->imm != 0) {
13148                                 verbose(env, "BPF_MOV uses reserved fields\n");
13149                                 return -EINVAL;
13150                         }
13151
13152                         if (BPF_CLASS(insn->code) == BPF_ALU) {
13153                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16) {
13154                                         verbose(env, "BPF_MOV uses reserved fields\n");
13155                                         return -EINVAL;
13156                                 }
13157                         } else {
13158                                 if (insn->off != 0 && insn->off != 8 && insn->off != 16 &&
13159                                     insn->off != 32) {
13160                                         verbose(env, "BPF_MOV uses reserved fields\n");
13161                                         return -EINVAL;
13162                                 }
13163                         }
13164
13165                         /* check src operand */
13166                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13167                         if (err)
13168                                 return err;
13169                 } else {
13170                         if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
13171                                 verbose(env, "BPF_MOV uses reserved fields\n");
13172                                 return -EINVAL;
13173                         }
13174                 }
13175
13176                 /* check dest operand, mark as required later */
13177                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13178                 if (err)
13179                         return err;
13180
13181                 if (BPF_SRC(insn->code) == BPF_X) {
13182                         struct bpf_reg_state *src_reg = regs + insn->src_reg;
13183                         struct bpf_reg_state *dst_reg = regs + insn->dst_reg;
13184                         bool need_id = src_reg->type == SCALAR_VALUE && !src_reg->id &&
13185                                        !tnum_is_const(src_reg->var_off);
13186
13187                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13188                                 if (insn->off == 0) {
13189                                         /* case: R1 = R2
13190                                          * copy register state to dest reg
13191                                          */
13192                                         if (need_id)
13193                                                 /* Assign src and dst registers the same ID
13194                                                  * that will be used by find_equal_scalars()
13195                                                  * to propagate min/max range.
13196                                                  */
13197                                                 src_reg->id = ++env->id_gen;
13198                                         copy_register_state(dst_reg, src_reg);
13199                                         dst_reg->live |= REG_LIVE_WRITTEN;
13200                                         dst_reg->subreg_def = DEF_NOT_SUBREG;
13201                                 } else {
13202                                         /* case: R1 = (s8, s16 s32)R2 */
13203                                         if (is_pointer_value(env, insn->src_reg)) {
13204                                                 verbose(env,
13205                                                         "R%d sign-extension part of pointer\n",
13206                                                         insn->src_reg);
13207                                                 return -EACCES;
13208                                         } else if (src_reg->type == SCALAR_VALUE) {
13209                                                 bool no_sext;
13210
13211                                                 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13212                                                 if (no_sext && need_id)
13213                                                         src_reg->id = ++env->id_gen;
13214                                                 copy_register_state(dst_reg, src_reg);
13215                                                 if (!no_sext)
13216                                                         dst_reg->id = 0;
13217                                                 coerce_reg_to_size_sx(dst_reg, insn->off >> 3);
13218                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13219                                                 dst_reg->subreg_def = DEF_NOT_SUBREG;
13220                                         } else {
13221                                                 mark_reg_unknown(env, regs, insn->dst_reg);
13222                                         }
13223                                 }
13224                         } else {
13225                                 /* R1 = (u32) R2 */
13226                                 if (is_pointer_value(env, insn->src_reg)) {
13227                                         verbose(env,
13228                                                 "R%d partial copy of pointer\n",
13229                                                 insn->src_reg);
13230                                         return -EACCES;
13231                                 } else if (src_reg->type == SCALAR_VALUE) {
13232                                         if (insn->off == 0) {
13233                                                 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX;
13234
13235                                                 if (is_src_reg_u32 && need_id)
13236                                                         src_reg->id = ++env->id_gen;
13237                                                 copy_register_state(dst_reg, src_reg);
13238                                                 /* Make sure ID is cleared if src_reg is not in u32
13239                                                  * range otherwise dst_reg min/max could be incorrectly
13240                                                  * propagated into src_reg by find_equal_scalars()
13241                                                  */
13242                                                 if (!is_src_reg_u32)
13243                                                         dst_reg->id = 0;
13244                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13245                                                 dst_reg->subreg_def = env->insn_idx + 1;
13246                                         } else {
13247                                                 /* case: W1 = (s8, s16)W2 */
13248                                                 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1));
13249
13250                                                 if (no_sext && need_id)
13251                                                         src_reg->id = ++env->id_gen;
13252                                                 copy_register_state(dst_reg, src_reg);
13253                                                 if (!no_sext)
13254                                                         dst_reg->id = 0;
13255                                                 dst_reg->live |= REG_LIVE_WRITTEN;
13256                                                 dst_reg->subreg_def = env->insn_idx + 1;
13257                                                 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3);
13258                                         }
13259                                 } else {
13260                                         mark_reg_unknown(env, regs,
13261                                                          insn->dst_reg);
13262                                 }
13263                                 zext_32_to_64(dst_reg);
13264                                 reg_bounds_sync(dst_reg);
13265                         }
13266                 } else {
13267                         /* case: R = imm
13268                          * remember the value we stored into this reg
13269                          */
13270                         /* clear any state __mark_reg_known doesn't set */
13271                         mark_reg_unknown(env, regs, insn->dst_reg);
13272                         regs[insn->dst_reg].type = SCALAR_VALUE;
13273                         if (BPF_CLASS(insn->code) == BPF_ALU64) {
13274                                 __mark_reg_known(regs + insn->dst_reg,
13275                                                  insn->imm);
13276                         } else {
13277                                 __mark_reg_known(regs + insn->dst_reg,
13278                                                  (u32)insn->imm);
13279                         }
13280                 }
13281
13282         } else if (opcode > BPF_END) {
13283                 verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
13284                 return -EINVAL;
13285
13286         } else {        /* all other ALU ops: and, sub, xor, add, ... */
13287
13288                 if (BPF_SRC(insn->code) == BPF_X) {
13289                         if (insn->imm != 0 || insn->off > 1 ||
13290                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13291                                 verbose(env, "BPF_ALU uses reserved fields\n");
13292                                 return -EINVAL;
13293                         }
13294                         /* check src1 operand */
13295                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
13296                         if (err)
13297                                 return err;
13298                 } else {
13299                         if (insn->src_reg != BPF_REG_0 || insn->off > 1 ||
13300                             (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) {
13301                                 verbose(env, "BPF_ALU uses reserved fields\n");
13302                                 return -EINVAL;
13303                         }
13304                 }
13305
13306                 /* check src2 operand */
13307                 err = check_reg_arg(env, insn->dst_reg, SRC_OP);
13308                 if (err)
13309                         return err;
13310
13311                 if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
13312                     BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
13313                         verbose(env, "div by zero\n");
13314                         return -EINVAL;
13315                 }
13316
13317                 if ((opcode == BPF_LSH || opcode == BPF_RSH ||
13318                      opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
13319                         int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
13320
13321                         if (insn->imm < 0 || insn->imm >= size) {
13322                                 verbose(env, "invalid shift %d\n", insn->imm);
13323                                 return -EINVAL;
13324                         }
13325                 }
13326
13327                 /* check dest operand */
13328                 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
13329                 if (err)
13330                         return err;
13331
13332                 return adjust_reg_min_max_vals(env, insn);
13333         }
13334
13335         return 0;
13336 }
13337
13338 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate,
13339                                    struct bpf_reg_state *dst_reg,
13340                                    enum bpf_reg_type type,
13341                                    bool range_right_open)
13342 {
13343         struct bpf_func_state *state;
13344         struct bpf_reg_state *reg;
13345         int new_range;
13346
13347         if (dst_reg->off < 0 ||
13348             (dst_reg->off == 0 && range_right_open))
13349                 /* This doesn't give us any range */
13350                 return;
13351
13352         if (dst_reg->umax_value > MAX_PACKET_OFF ||
13353             dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF)
13354                 /* Risk of overflow.  For instance, ptr + (1<<63) may be less
13355                  * than pkt_end, but that's because it's also less than pkt.
13356                  */
13357                 return;
13358
13359         new_range = dst_reg->off;
13360         if (range_right_open)
13361                 new_range++;
13362
13363         /* Examples for register markings:
13364          *
13365          * pkt_data in dst register:
13366          *
13367          *   r2 = r3;
13368          *   r2 += 8;
13369          *   if (r2 > pkt_end) goto <handle exception>
13370          *   <access okay>
13371          *
13372          *   r2 = r3;
13373          *   r2 += 8;
13374          *   if (r2 < pkt_end) goto <access okay>
13375          *   <handle exception>
13376          *
13377          *   Where:
13378          *     r2 == dst_reg, pkt_end == src_reg
13379          *     r2=pkt(id=n,off=8,r=0)
13380          *     r3=pkt(id=n,off=0,r=0)
13381          *
13382          * pkt_data in src register:
13383          *
13384          *   r2 = r3;
13385          *   r2 += 8;
13386          *   if (pkt_end >= r2) goto <access okay>
13387          *   <handle exception>
13388          *
13389          *   r2 = r3;
13390          *   r2 += 8;
13391          *   if (pkt_end <= r2) goto <handle exception>
13392          *   <access okay>
13393          *
13394          *   Where:
13395          *     pkt_end == dst_reg, r2 == src_reg
13396          *     r2=pkt(id=n,off=8,r=0)
13397          *     r3=pkt(id=n,off=0,r=0)
13398          *
13399          * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8)
13400          * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8)
13401          * and [r3, r3 + 8-1) respectively is safe to access depending on
13402          * the check.
13403          */
13404
13405         /* If our ids match, then we must have the same max_value.  And we
13406          * don't care about the other reg's fixed offset, since if it's too big
13407          * the range won't allow anything.
13408          * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16.
13409          */
13410         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13411                 if (reg->type == type && reg->id == dst_reg->id)
13412                         /* keep the maximum range already checked */
13413                         reg->range = max(reg->range, new_range);
13414         }));
13415 }
13416
13417 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode)
13418 {
13419         struct tnum subreg = tnum_subreg(reg->var_off);
13420         s32 sval = (s32)val;
13421
13422         switch (opcode) {
13423         case BPF_JEQ:
13424                 if (tnum_is_const(subreg))
13425                         return !!tnum_equals_const(subreg, val);
13426                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13427                         return 0;
13428                 break;
13429         case BPF_JNE:
13430                 if (tnum_is_const(subreg))
13431                         return !tnum_equals_const(subreg, val);
13432                 else if (val < reg->u32_min_value || val > reg->u32_max_value)
13433                         return 1;
13434                 break;
13435         case BPF_JSET:
13436                 if ((~subreg.mask & subreg.value) & val)
13437                         return 1;
13438                 if (!((subreg.mask | subreg.value) & val))
13439                         return 0;
13440                 break;
13441         case BPF_JGT:
13442                 if (reg->u32_min_value > val)
13443                         return 1;
13444                 else if (reg->u32_max_value <= val)
13445                         return 0;
13446                 break;
13447         case BPF_JSGT:
13448                 if (reg->s32_min_value > sval)
13449                         return 1;
13450                 else if (reg->s32_max_value <= sval)
13451                         return 0;
13452                 break;
13453         case BPF_JLT:
13454                 if (reg->u32_max_value < val)
13455                         return 1;
13456                 else if (reg->u32_min_value >= val)
13457                         return 0;
13458                 break;
13459         case BPF_JSLT:
13460                 if (reg->s32_max_value < sval)
13461                         return 1;
13462                 else if (reg->s32_min_value >= sval)
13463                         return 0;
13464                 break;
13465         case BPF_JGE:
13466                 if (reg->u32_min_value >= val)
13467                         return 1;
13468                 else if (reg->u32_max_value < val)
13469                         return 0;
13470                 break;
13471         case BPF_JSGE:
13472                 if (reg->s32_min_value >= sval)
13473                         return 1;
13474                 else if (reg->s32_max_value < sval)
13475                         return 0;
13476                 break;
13477         case BPF_JLE:
13478                 if (reg->u32_max_value <= val)
13479                         return 1;
13480                 else if (reg->u32_min_value > val)
13481                         return 0;
13482                 break;
13483         case BPF_JSLE:
13484                 if (reg->s32_max_value <= sval)
13485                         return 1;
13486                 else if (reg->s32_min_value > sval)
13487                         return 0;
13488                 break;
13489         }
13490
13491         return -1;
13492 }
13493
13494
13495 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode)
13496 {
13497         s64 sval = (s64)val;
13498
13499         switch (opcode) {
13500         case BPF_JEQ:
13501                 if (tnum_is_const(reg->var_off))
13502                         return !!tnum_equals_const(reg->var_off, val);
13503                 else if (val < reg->umin_value || val > reg->umax_value)
13504                         return 0;
13505                 break;
13506         case BPF_JNE:
13507                 if (tnum_is_const(reg->var_off))
13508                         return !tnum_equals_const(reg->var_off, val);
13509                 else if (val < reg->umin_value || val > reg->umax_value)
13510                         return 1;
13511                 break;
13512         case BPF_JSET:
13513                 if ((~reg->var_off.mask & reg->var_off.value) & val)
13514                         return 1;
13515                 if (!((reg->var_off.mask | reg->var_off.value) & val))
13516                         return 0;
13517                 break;
13518         case BPF_JGT:
13519                 if (reg->umin_value > val)
13520                         return 1;
13521                 else if (reg->umax_value <= val)
13522                         return 0;
13523                 break;
13524         case BPF_JSGT:
13525                 if (reg->smin_value > sval)
13526                         return 1;
13527                 else if (reg->smax_value <= sval)
13528                         return 0;
13529                 break;
13530         case BPF_JLT:
13531                 if (reg->umax_value < val)
13532                         return 1;
13533                 else if (reg->umin_value >= val)
13534                         return 0;
13535                 break;
13536         case BPF_JSLT:
13537                 if (reg->smax_value < sval)
13538                         return 1;
13539                 else if (reg->smin_value >= sval)
13540                         return 0;
13541                 break;
13542         case BPF_JGE:
13543                 if (reg->umin_value >= val)
13544                         return 1;
13545                 else if (reg->umax_value < val)
13546                         return 0;
13547                 break;
13548         case BPF_JSGE:
13549                 if (reg->smin_value >= sval)
13550                         return 1;
13551                 else if (reg->smax_value < sval)
13552                         return 0;
13553                 break;
13554         case BPF_JLE:
13555                 if (reg->umax_value <= val)
13556                         return 1;
13557                 else if (reg->umin_value > val)
13558                         return 0;
13559                 break;
13560         case BPF_JSLE:
13561                 if (reg->smax_value <= sval)
13562                         return 1;
13563                 else if (reg->smin_value > sval)
13564                         return 0;
13565                 break;
13566         }
13567
13568         return -1;
13569 }
13570
13571 /* compute branch direction of the expression "if (reg opcode val) goto target;"
13572  * and return:
13573  *  1 - branch will be taken and "goto target" will be executed
13574  *  0 - branch will not be taken and fall-through to next insn
13575  * -1 - unknown. Example: "if (reg < 5)" is unknown when register value
13576  *      range [0,10]
13577  */
13578 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode,
13579                            bool is_jmp32)
13580 {
13581         if (__is_pointer_value(false, reg)) {
13582                 if (!reg_not_null(reg))
13583                         return -1;
13584
13585                 /* If pointer is valid tests against zero will fail so we can
13586                  * use this to direct branch taken.
13587                  */
13588                 if (val != 0)
13589                         return -1;
13590
13591                 switch (opcode) {
13592                 case BPF_JEQ:
13593                         return 0;
13594                 case BPF_JNE:
13595                         return 1;
13596                 default:
13597                         return -1;
13598                 }
13599         }
13600
13601         if (is_jmp32)
13602                 return is_branch32_taken(reg, val, opcode);
13603         return is_branch64_taken(reg, val, opcode);
13604 }
13605
13606 static int flip_opcode(u32 opcode)
13607 {
13608         /* How can we transform "a <op> b" into "b <op> a"? */
13609         static const u8 opcode_flip[16] = {
13610                 /* these stay the same */
13611                 [BPF_JEQ  >> 4] = BPF_JEQ,
13612                 [BPF_JNE  >> 4] = BPF_JNE,
13613                 [BPF_JSET >> 4] = BPF_JSET,
13614                 /* these swap "lesser" and "greater" (L and G in the opcodes) */
13615                 [BPF_JGE  >> 4] = BPF_JLE,
13616                 [BPF_JGT  >> 4] = BPF_JLT,
13617                 [BPF_JLE  >> 4] = BPF_JGE,
13618                 [BPF_JLT  >> 4] = BPF_JGT,
13619                 [BPF_JSGE >> 4] = BPF_JSLE,
13620                 [BPF_JSGT >> 4] = BPF_JSLT,
13621                 [BPF_JSLE >> 4] = BPF_JSGE,
13622                 [BPF_JSLT >> 4] = BPF_JSGT
13623         };
13624         return opcode_flip[opcode >> 4];
13625 }
13626
13627 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg,
13628                                    struct bpf_reg_state *src_reg,
13629                                    u8 opcode)
13630 {
13631         struct bpf_reg_state *pkt;
13632
13633         if (src_reg->type == PTR_TO_PACKET_END) {
13634                 pkt = dst_reg;
13635         } else if (dst_reg->type == PTR_TO_PACKET_END) {
13636                 pkt = src_reg;
13637                 opcode = flip_opcode(opcode);
13638         } else {
13639                 return -1;
13640         }
13641
13642         if (pkt->range >= 0)
13643                 return -1;
13644
13645         switch (opcode) {
13646         case BPF_JLE:
13647                 /* pkt <= pkt_end */
13648                 fallthrough;
13649         case BPF_JGT:
13650                 /* pkt > pkt_end */
13651                 if (pkt->range == BEYOND_PKT_END)
13652                         /* pkt has at last one extra byte beyond pkt_end */
13653                         return opcode == BPF_JGT;
13654                 break;
13655         case BPF_JLT:
13656                 /* pkt < pkt_end */
13657                 fallthrough;
13658         case BPF_JGE:
13659                 /* pkt >= pkt_end */
13660                 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END)
13661                         return opcode == BPF_JGE;
13662                 break;
13663         }
13664         return -1;
13665 }
13666
13667 /* Adjusts the register min/max values in the case that the dst_reg is the
13668  * variable register that we are working on, and src_reg is a constant or we're
13669  * simply doing a BPF_K check.
13670  * In JEQ/JNE cases we also adjust the var_off values.
13671  */
13672 static void reg_set_min_max(struct bpf_reg_state *true_reg,
13673                             struct bpf_reg_state *false_reg,
13674                             u64 val, u32 val32,
13675                             u8 opcode, bool is_jmp32)
13676 {
13677         struct tnum false_32off = tnum_subreg(false_reg->var_off);
13678         struct tnum false_64off = false_reg->var_off;
13679         struct tnum true_32off = tnum_subreg(true_reg->var_off);
13680         struct tnum true_64off = true_reg->var_off;
13681         s64 sval = (s64)val;
13682         s32 sval32 = (s32)val32;
13683
13684         /* If the dst_reg is a pointer, we can't learn anything about its
13685          * variable offset from the compare (unless src_reg were a pointer into
13686          * the same object, but we don't bother with that.
13687          * Since false_reg and true_reg have the same type by construction, we
13688          * only need to check one of them for pointerness.
13689          */
13690         if (__is_pointer_value(false, false_reg))
13691                 return;
13692
13693         switch (opcode) {
13694         /* JEQ/JNE comparison doesn't change the register equivalence.
13695          *
13696          * r1 = r2;
13697          * if (r1 == 42) goto label;
13698          * ...
13699          * label: // here both r1 and r2 are known to be 42.
13700          *
13701          * Hence when marking register as known preserve it's ID.
13702          */
13703         case BPF_JEQ:
13704                 if (is_jmp32) {
13705                         __mark_reg32_known(true_reg, val32);
13706                         true_32off = tnum_subreg(true_reg->var_off);
13707                 } else {
13708                         ___mark_reg_known(true_reg, val);
13709                         true_64off = true_reg->var_off;
13710                 }
13711                 break;
13712         case BPF_JNE:
13713                 if (is_jmp32) {
13714                         __mark_reg32_known(false_reg, val32);
13715                         false_32off = tnum_subreg(false_reg->var_off);
13716                 } else {
13717                         ___mark_reg_known(false_reg, val);
13718                         false_64off = false_reg->var_off;
13719                 }
13720                 break;
13721         case BPF_JSET:
13722                 if (is_jmp32) {
13723                         false_32off = tnum_and(false_32off, tnum_const(~val32));
13724                         if (is_power_of_2(val32))
13725                                 true_32off = tnum_or(true_32off,
13726                                                      tnum_const(val32));
13727                 } else {
13728                         false_64off = tnum_and(false_64off, tnum_const(~val));
13729                         if (is_power_of_2(val))
13730                                 true_64off = tnum_or(true_64off,
13731                                                      tnum_const(val));
13732                 }
13733                 break;
13734         case BPF_JGE:
13735         case BPF_JGT:
13736         {
13737                 if (is_jmp32) {
13738                         u32 false_umax = opcode == BPF_JGT ? val32  : val32 - 1;
13739                         u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32;
13740
13741                         false_reg->u32_max_value = min(false_reg->u32_max_value,
13742                                                        false_umax);
13743                         true_reg->u32_min_value = max(true_reg->u32_min_value,
13744                                                       true_umin);
13745                 } else {
13746                         u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
13747                         u64 true_umin = opcode == BPF_JGT ? val + 1 : val;
13748
13749                         false_reg->umax_value = min(false_reg->umax_value, false_umax);
13750                         true_reg->umin_value = max(true_reg->umin_value, true_umin);
13751                 }
13752                 break;
13753         }
13754         case BPF_JSGE:
13755         case BPF_JSGT:
13756         {
13757                 if (is_jmp32) {
13758                         s32 false_smax = opcode == BPF_JSGT ? sval32    : sval32 - 1;
13759                         s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32;
13760
13761                         false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax);
13762                         true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin);
13763                 } else {
13764                         s64 false_smax = opcode == BPF_JSGT ? sval    : sval - 1;
13765                         s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval;
13766
13767                         false_reg->smax_value = min(false_reg->smax_value, false_smax);
13768                         true_reg->smin_value = max(true_reg->smin_value, true_smin);
13769                 }
13770                 break;
13771         }
13772         case BPF_JLE:
13773         case BPF_JLT:
13774         {
13775                 if (is_jmp32) {
13776                         u32 false_umin = opcode == BPF_JLT ? val32  : val32 + 1;
13777                         u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32;
13778
13779                         false_reg->u32_min_value = max(false_reg->u32_min_value,
13780                                                        false_umin);
13781                         true_reg->u32_max_value = min(true_reg->u32_max_value,
13782                                                       true_umax);
13783                 } else {
13784                         u64 false_umin = opcode == BPF_JLT ? val    : val + 1;
13785                         u64 true_umax = opcode == BPF_JLT ? val - 1 : val;
13786
13787                         false_reg->umin_value = max(false_reg->umin_value, false_umin);
13788                         true_reg->umax_value = min(true_reg->umax_value, true_umax);
13789                 }
13790                 break;
13791         }
13792         case BPF_JSLE:
13793         case BPF_JSLT:
13794         {
13795                 if (is_jmp32) {
13796                         s32 false_smin = opcode == BPF_JSLT ? sval32    : sval32 + 1;
13797                         s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32;
13798
13799                         false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin);
13800                         true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax);
13801                 } else {
13802                         s64 false_smin = opcode == BPF_JSLT ? sval    : sval + 1;
13803                         s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval;
13804
13805                         false_reg->smin_value = max(false_reg->smin_value, false_smin);
13806                         true_reg->smax_value = min(true_reg->smax_value, true_smax);
13807                 }
13808                 break;
13809         }
13810         default:
13811                 return;
13812         }
13813
13814         if (is_jmp32) {
13815                 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off),
13816                                              tnum_subreg(false_32off));
13817                 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off),
13818                                             tnum_subreg(true_32off));
13819                 __reg_combine_32_into_64(false_reg);
13820                 __reg_combine_32_into_64(true_reg);
13821         } else {
13822                 false_reg->var_off = false_64off;
13823                 true_reg->var_off = true_64off;
13824                 __reg_combine_64_into_32(false_reg);
13825                 __reg_combine_64_into_32(true_reg);
13826         }
13827 }
13828
13829 /* Same as above, but for the case that dst_reg holds a constant and src_reg is
13830  * the variable reg.
13831  */
13832 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg,
13833                                 struct bpf_reg_state *false_reg,
13834                                 u64 val, u32 val32,
13835                                 u8 opcode, bool is_jmp32)
13836 {
13837         opcode = flip_opcode(opcode);
13838         /* This uses zero as "not present in table"; luckily the zero opcode,
13839          * BPF_JA, can't get here.
13840          */
13841         if (opcode)
13842                 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32);
13843 }
13844
13845 /* Regs are known to be equal, so intersect their min/max/var_off */
13846 static void __reg_combine_min_max(struct bpf_reg_state *src_reg,
13847                                   struct bpf_reg_state *dst_reg)
13848 {
13849         src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value,
13850                                                         dst_reg->umin_value);
13851         src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value,
13852                                                         dst_reg->umax_value);
13853         src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value,
13854                                                         dst_reg->smin_value);
13855         src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value,
13856                                                         dst_reg->smax_value);
13857         src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off,
13858                                                              dst_reg->var_off);
13859         reg_bounds_sync(src_reg);
13860         reg_bounds_sync(dst_reg);
13861 }
13862
13863 static void reg_combine_min_max(struct bpf_reg_state *true_src,
13864                                 struct bpf_reg_state *true_dst,
13865                                 struct bpf_reg_state *false_src,
13866                                 struct bpf_reg_state *false_dst,
13867                                 u8 opcode)
13868 {
13869         switch (opcode) {
13870         case BPF_JEQ:
13871                 __reg_combine_min_max(true_src, true_dst);
13872                 break;
13873         case BPF_JNE:
13874                 __reg_combine_min_max(false_src, false_dst);
13875                 break;
13876         }
13877 }
13878
13879 static void mark_ptr_or_null_reg(struct bpf_func_state *state,
13880                                  struct bpf_reg_state *reg, u32 id,
13881                                  bool is_null)
13882 {
13883         if (type_may_be_null(reg->type) && reg->id == id &&
13884             (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) {
13885                 /* Old offset (both fixed and variable parts) should have been
13886                  * known-zero, because we don't allow pointer arithmetic on
13887                  * pointers that might be NULL. If we see this happening, don't
13888                  * convert the register.
13889                  *
13890                  * But in some cases, some helpers that return local kptrs
13891                  * advance offset for the returned pointer. In those cases, it
13892                  * is fine to expect to see reg->off.
13893                  */
13894                 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0)))
13895                         return;
13896                 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) &&
13897                     WARN_ON_ONCE(reg->off))
13898                         return;
13899
13900                 if (is_null) {
13901                         reg->type = SCALAR_VALUE;
13902                         /* We don't need id and ref_obj_id from this point
13903                          * onwards anymore, thus we should better reset it,
13904                          * so that state pruning has chances to take effect.
13905                          */
13906                         reg->id = 0;
13907                         reg->ref_obj_id = 0;
13908
13909                         return;
13910                 }
13911
13912                 mark_ptr_not_null_reg(reg);
13913
13914                 if (!reg_may_point_to_spin_lock(reg)) {
13915                         /* For not-NULL ptr, reg->ref_obj_id will be reset
13916                          * in release_reference().
13917                          *
13918                          * reg->id is still used by spin_lock ptr. Other
13919                          * than spin_lock ptr type, reg->id can be reset.
13920                          */
13921                         reg->id = 0;
13922                 }
13923         }
13924 }
13925
13926 /* The logic is similar to find_good_pkt_pointers(), both could eventually
13927  * be folded together at some point.
13928  */
13929 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
13930                                   bool is_null)
13931 {
13932         struct bpf_func_state *state = vstate->frame[vstate->curframe];
13933         struct bpf_reg_state *regs = state->regs, *reg;
13934         u32 ref_obj_id = regs[regno].ref_obj_id;
13935         u32 id = regs[regno].id;
13936
13937         if (ref_obj_id && ref_obj_id == id && is_null)
13938                 /* regs[regno] is in the " == NULL" branch.
13939                  * No one could have freed the reference state before
13940                  * doing the NULL check.
13941                  */
13942                 WARN_ON_ONCE(release_reference_state(state, id));
13943
13944         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
13945                 mark_ptr_or_null_reg(state, reg, id, is_null);
13946         }));
13947 }
13948
13949 static bool try_match_pkt_pointers(const struct bpf_insn *insn,
13950                                    struct bpf_reg_state *dst_reg,
13951                                    struct bpf_reg_state *src_reg,
13952                                    struct bpf_verifier_state *this_branch,
13953                                    struct bpf_verifier_state *other_branch)
13954 {
13955         if (BPF_SRC(insn->code) != BPF_X)
13956                 return false;
13957
13958         /* Pointers are always 64-bit. */
13959         if (BPF_CLASS(insn->code) == BPF_JMP32)
13960                 return false;
13961
13962         switch (BPF_OP(insn->code)) {
13963         case BPF_JGT:
13964                 if ((dst_reg->type == PTR_TO_PACKET &&
13965                      src_reg->type == PTR_TO_PACKET_END) ||
13966                     (dst_reg->type == PTR_TO_PACKET_META &&
13967                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13968                         /* pkt_data' > pkt_end, pkt_meta' > pkt_data */
13969                         find_good_pkt_pointers(this_branch, dst_reg,
13970                                                dst_reg->type, false);
13971                         mark_pkt_end(other_branch, insn->dst_reg, true);
13972                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13973                             src_reg->type == PTR_TO_PACKET) ||
13974                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13975                             src_reg->type == PTR_TO_PACKET_META)) {
13976                         /* pkt_end > pkt_data', pkt_data > pkt_meta' */
13977                         find_good_pkt_pointers(other_branch, src_reg,
13978                                                src_reg->type, true);
13979                         mark_pkt_end(this_branch, insn->src_reg, false);
13980                 } else {
13981                         return false;
13982                 }
13983                 break;
13984         case BPF_JLT:
13985                 if ((dst_reg->type == PTR_TO_PACKET &&
13986                      src_reg->type == PTR_TO_PACKET_END) ||
13987                     (dst_reg->type == PTR_TO_PACKET_META &&
13988                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
13989                         /* pkt_data' < pkt_end, pkt_meta' < pkt_data */
13990                         find_good_pkt_pointers(other_branch, dst_reg,
13991                                                dst_reg->type, true);
13992                         mark_pkt_end(this_branch, insn->dst_reg, false);
13993                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
13994                             src_reg->type == PTR_TO_PACKET) ||
13995                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
13996                             src_reg->type == PTR_TO_PACKET_META)) {
13997                         /* pkt_end < pkt_data', pkt_data > pkt_meta' */
13998                         find_good_pkt_pointers(this_branch, src_reg,
13999                                                src_reg->type, false);
14000                         mark_pkt_end(other_branch, insn->src_reg, true);
14001                 } else {
14002                         return false;
14003                 }
14004                 break;
14005         case BPF_JGE:
14006                 if ((dst_reg->type == PTR_TO_PACKET &&
14007                      src_reg->type == PTR_TO_PACKET_END) ||
14008                     (dst_reg->type == PTR_TO_PACKET_META &&
14009                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14010                         /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */
14011                         find_good_pkt_pointers(this_branch, dst_reg,
14012                                                dst_reg->type, true);
14013                         mark_pkt_end(other_branch, insn->dst_reg, false);
14014                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14015                             src_reg->type == PTR_TO_PACKET) ||
14016                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14017                             src_reg->type == PTR_TO_PACKET_META)) {
14018                         /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */
14019                         find_good_pkt_pointers(other_branch, src_reg,
14020                                                src_reg->type, false);
14021                         mark_pkt_end(this_branch, insn->src_reg, true);
14022                 } else {
14023                         return false;
14024                 }
14025                 break;
14026         case BPF_JLE:
14027                 if ((dst_reg->type == PTR_TO_PACKET &&
14028                      src_reg->type == PTR_TO_PACKET_END) ||
14029                     (dst_reg->type == PTR_TO_PACKET_META &&
14030                      reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) {
14031                         /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */
14032                         find_good_pkt_pointers(other_branch, dst_reg,
14033                                                dst_reg->type, false);
14034                         mark_pkt_end(this_branch, insn->dst_reg, true);
14035                 } else if ((dst_reg->type == PTR_TO_PACKET_END &&
14036                             src_reg->type == PTR_TO_PACKET) ||
14037                            (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) &&
14038                             src_reg->type == PTR_TO_PACKET_META)) {
14039                         /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */
14040                         find_good_pkt_pointers(this_branch, src_reg,
14041                                                src_reg->type, true);
14042                         mark_pkt_end(other_branch, insn->src_reg, false);
14043                 } else {
14044                         return false;
14045                 }
14046                 break;
14047         default:
14048                 return false;
14049         }
14050
14051         return true;
14052 }
14053
14054 static void find_equal_scalars(struct bpf_verifier_state *vstate,
14055                                struct bpf_reg_state *known_reg)
14056 {
14057         struct bpf_func_state *state;
14058         struct bpf_reg_state *reg;
14059
14060         bpf_for_each_reg_in_vstate(vstate, state, reg, ({
14061                 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id)
14062                         copy_register_state(reg, known_reg);
14063         }));
14064 }
14065
14066 static int check_cond_jmp_op(struct bpf_verifier_env *env,
14067                              struct bpf_insn *insn, int *insn_idx)
14068 {
14069         struct bpf_verifier_state *this_branch = env->cur_state;
14070         struct bpf_verifier_state *other_branch;
14071         struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs;
14072         struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL;
14073         struct bpf_reg_state *eq_branch_regs;
14074         u8 opcode = BPF_OP(insn->code);
14075         bool is_jmp32;
14076         int pred = -1;
14077         int err;
14078
14079         /* Only conditional jumps are expected to reach here. */
14080         if (opcode == BPF_JA || opcode > BPF_JSLE) {
14081                 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode);
14082                 return -EINVAL;
14083         }
14084
14085         /* check src2 operand */
14086         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
14087         if (err)
14088                 return err;
14089
14090         dst_reg = &regs[insn->dst_reg];
14091         if (BPF_SRC(insn->code) == BPF_X) {
14092                 if (insn->imm != 0) {
14093                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14094                         return -EINVAL;
14095                 }
14096
14097                 /* check src1 operand */
14098                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14099                 if (err)
14100                         return err;
14101
14102                 src_reg = &regs[insn->src_reg];
14103                 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) &&
14104                     is_pointer_value(env, insn->src_reg)) {
14105                         verbose(env, "R%d pointer comparison prohibited\n",
14106                                 insn->src_reg);
14107                         return -EACCES;
14108                 }
14109         } else {
14110                 if (insn->src_reg != BPF_REG_0) {
14111                         verbose(env, "BPF_JMP/JMP32 uses reserved fields\n");
14112                         return -EINVAL;
14113                 }
14114         }
14115
14116         is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32;
14117
14118         if (BPF_SRC(insn->code) == BPF_K) {
14119                 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32);
14120         } else if (src_reg->type == SCALAR_VALUE &&
14121                    is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) {
14122                 pred = is_branch_taken(dst_reg,
14123                                        tnum_subreg(src_reg->var_off).value,
14124                                        opcode,
14125                                        is_jmp32);
14126         } else if (src_reg->type == SCALAR_VALUE &&
14127                    !is_jmp32 && tnum_is_const(src_reg->var_off)) {
14128                 pred = is_branch_taken(dst_reg,
14129                                        src_reg->var_off.value,
14130                                        opcode,
14131                                        is_jmp32);
14132         } else if (dst_reg->type == SCALAR_VALUE &&
14133                    is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) {
14134                 pred = is_branch_taken(src_reg,
14135                                        tnum_subreg(dst_reg->var_off).value,
14136                                        flip_opcode(opcode),
14137                                        is_jmp32);
14138         } else if (dst_reg->type == SCALAR_VALUE &&
14139                    !is_jmp32 && tnum_is_const(dst_reg->var_off)) {
14140                 pred = is_branch_taken(src_reg,
14141                                        dst_reg->var_off.value,
14142                                        flip_opcode(opcode),
14143                                        is_jmp32);
14144         } else if (reg_is_pkt_pointer_any(dst_reg) &&
14145                    reg_is_pkt_pointer_any(src_reg) &&
14146                    !is_jmp32) {
14147                 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode);
14148         }
14149
14150         if (pred >= 0) {
14151                 /* If we get here with a dst_reg pointer type it is because
14152                  * above is_branch_taken() special cased the 0 comparison.
14153                  */
14154                 if (!__is_pointer_value(false, dst_reg))
14155                         err = mark_chain_precision(env, insn->dst_reg);
14156                 if (BPF_SRC(insn->code) == BPF_X && !err &&
14157                     !__is_pointer_value(false, src_reg))
14158                         err = mark_chain_precision(env, insn->src_reg);
14159                 if (err)
14160                         return err;
14161         }
14162
14163         if (pred == 1) {
14164                 /* Only follow the goto, ignore fall-through. If needed, push
14165                  * the fall-through branch for simulation under speculative
14166                  * execution.
14167                  */
14168                 if (!env->bypass_spec_v1 &&
14169                     !sanitize_speculative_path(env, insn, *insn_idx + 1,
14170                                                *insn_idx))
14171                         return -EFAULT;
14172                 if (env->log.level & BPF_LOG_LEVEL)
14173                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14174                 *insn_idx += insn->off;
14175                 return 0;
14176         } else if (pred == 0) {
14177                 /* Only follow the fall-through branch, since that's where the
14178                  * program will go. If needed, push the goto branch for
14179                  * simulation under speculative execution.
14180                  */
14181                 if (!env->bypass_spec_v1 &&
14182                     !sanitize_speculative_path(env, insn,
14183                                                *insn_idx + insn->off + 1,
14184                                                *insn_idx))
14185                         return -EFAULT;
14186                 if (env->log.level & BPF_LOG_LEVEL)
14187                         print_insn_state(env, this_branch->frame[this_branch->curframe]);
14188                 return 0;
14189         }
14190
14191         other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx,
14192                                   false);
14193         if (!other_branch)
14194                 return -EFAULT;
14195         other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
14196
14197         /* detect if we are comparing against a constant value so we can adjust
14198          * our min/max values for our dst register.
14199          * this is only legit if both are scalars (or pointers to the same
14200          * object, I suppose, see the PTR_MAYBE_NULL related if block below),
14201          * because otherwise the different base pointers mean the offsets aren't
14202          * comparable.
14203          */
14204         if (BPF_SRC(insn->code) == BPF_X) {
14205                 struct bpf_reg_state *src_reg = &regs[insn->src_reg];
14206
14207                 if (dst_reg->type == SCALAR_VALUE &&
14208                     src_reg->type == SCALAR_VALUE) {
14209                         if (tnum_is_const(src_reg->var_off) ||
14210                             (is_jmp32 &&
14211                              tnum_is_const(tnum_subreg(src_reg->var_off))))
14212                                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14213                                                 dst_reg,
14214                                                 src_reg->var_off.value,
14215                                                 tnum_subreg(src_reg->var_off).value,
14216                                                 opcode, is_jmp32);
14217                         else if (tnum_is_const(dst_reg->var_off) ||
14218                                  (is_jmp32 &&
14219                                   tnum_is_const(tnum_subreg(dst_reg->var_off))))
14220                                 reg_set_min_max_inv(&other_branch_regs[insn->src_reg],
14221                                                     src_reg,
14222                                                     dst_reg->var_off.value,
14223                                                     tnum_subreg(dst_reg->var_off).value,
14224                                                     opcode, is_jmp32);
14225                         else if (!is_jmp32 &&
14226                                  (opcode == BPF_JEQ || opcode == BPF_JNE))
14227                                 /* Comparing for equality, we can combine knowledge */
14228                                 reg_combine_min_max(&other_branch_regs[insn->src_reg],
14229                                                     &other_branch_regs[insn->dst_reg],
14230                                                     src_reg, dst_reg, opcode);
14231                         if (src_reg->id &&
14232                             !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) {
14233                                 find_equal_scalars(this_branch, src_reg);
14234                                 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]);
14235                         }
14236
14237                 }
14238         } else if (dst_reg->type == SCALAR_VALUE) {
14239                 reg_set_min_max(&other_branch_regs[insn->dst_reg],
14240                                         dst_reg, insn->imm, (u32)insn->imm,
14241                                         opcode, is_jmp32);
14242         }
14243
14244         if (dst_reg->type == SCALAR_VALUE && dst_reg->id &&
14245             !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) {
14246                 find_equal_scalars(this_branch, dst_reg);
14247                 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]);
14248         }
14249
14250         /* if one pointer register is compared to another pointer
14251          * register check if PTR_MAYBE_NULL could be lifted.
14252          * E.g. register A - maybe null
14253          *      register B - not null
14254          * for JNE A, B, ... - A is not null in the false branch;
14255          * for JEQ A, B, ... - A is not null in the true branch.
14256          *
14257          * Since PTR_TO_BTF_ID points to a kernel struct that does
14258          * not need to be null checked by the BPF program, i.e.,
14259          * could be null even without PTR_MAYBE_NULL marking, so
14260          * only propagate nullness when neither reg is that type.
14261          */
14262         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X &&
14263             __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) &&
14264             type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) &&
14265             base_type(src_reg->type) != PTR_TO_BTF_ID &&
14266             base_type(dst_reg->type) != PTR_TO_BTF_ID) {
14267                 eq_branch_regs = NULL;
14268                 switch (opcode) {
14269                 case BPF_JEQ:
14270                         eq_branch_regs = other_branch_regs;
14271                         break;
14272                 case BPF_JNE:
14273                         eq_branch_regs = regs;
14274                         break;
14275                 default:
14276                         /* do nothing */
14277                         break;
14278                 }
14279                 if (eq_branch_regs) {
14280                         if (type_may_be_null(src_reg->type))
14281                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]);
14282                         else
14283                                 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]);
14284                 }
14285         }
14286
14287         /* detect if R == 0 where R is returned from bpf_map_lookup_elem().
14288          * NOTE: these optimizations below are related with pointer comparison
14289          *       which will never be JMP32.
14290          */
14291         if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K &&
14292             insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) &&
14293             type_may_be_null(dst_reg->type)) {
14294                 /* Mark all identical registers in each branch as either
14295                  * safe or unknown depending R == 0 or R != 0 conditional.
14296                  */
14297                 mark_ptr_or_null_regs(this_branch, insn->dst_reg,
14298                                       opcode == BPF_JNE);
14299                 mark_ptr_or_null_regs(other_branch, insn->dst_reg,
14300                                       opcode == BPF_JEQ);
14301         } else if (!try_match_pkt_pointers(insn, dst_reg, &regs[insn->src_reg],
14302                                            this_branch, other_branch) &&
14303                    is_pointer_value(env, insn->dst_reg)) {
14304                 verbose(env, "R%d pointer comparison prohibited\n",
14305                         insn->dst_reg);
14306                 return -EACCES;
14307         }
14308         if (env->log.level & BPF_LOG_LEVEL)
14309                 print_insn_state(env, this_branch->frame[this_branch->curframe]);
14310         return 0;
14311 }
14312
14313 /* verify BPF_LD_IMM64 instruction */
14314 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)
14315 {
14316         struct bpf_insn_aux_data *aux = cur_aux(env);
14317         struct bpf_reg_state *regs = cur_regs(env);
14318         struct bpf_reg_state *dst_reg;
14319         struct bpf_map *map;
14320         int err;
14321
14322         if (BPF_SIZE(insn->code) != BPF_DW) {
14323                 verbose(env, "invalid BPF_LD_IMM insn\n");
14324                 return -EINVAL;
14325         }
14326         if (insn->off != 0) {
14327                 verbose(env, "BPF_LD_IMM64 uses reserved fields\n");
14328                 return -EINVAL;
14329         }
14330
14331         err = check_reg_arg(env, insn->dst_reg, DST_OP);
14332         if (err)
14333                 return err;
14334
14335         dst_reg = &regs[insn->dst_reg];
14336         if (insn->src_reg == 0) {
14337                 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;
14338
14339                 dst_reg->type = SCALAR_VALUE;
14340                 __mark_reg_known(&regs[insn->dst_reg], imm);
14341                 return 0;
14342         }
14343
14344         /* All special src_reg cases are listed below. From this point onwards
14345          * we either succeed and assign a corresponding dst_reg->type after
14346          * zeroing the offset, or fail and reject the program.
14347          */
14348         mark_reg_known_zero(env, regs, insn->dst_reg);
14349
14350         if (insn->src_reg == BPF_PSEUDO_BTF_ID) {
14351                 dst_reg->type = aux->btf_var.reg_type;
14352                 switch (base_type(dst_reg->type)) {
14353                 case PTR_TO_MEM:
14354                         dst_reg->mem_size = aux->btf_var.mem_size;
14355                         break;
14356                 case PTR_TO_BTF_ID:
14357                         dst_reg->btf = aux->btf_var.btf;
14358                         dst_reg->btf_id = aux->btf_var.btf_id;
14359                         break;
14360                 default:
14361                         verbose(env, "bpf verifier is misconfigured\n");
14362                         return -EFAULT;
14363                 }
14364                 return 0;
14365         }
14366
14367         if (insn->src_reg == BPF_PSEUDO_FUNC) {
14368                 struct bpf_prog_aux *aux = env->prog->aux;
14369                 u32 subprogno = find_subprog(env,
14370                                              env->insn_idx + insn->imm + 1);
14371
14372                 if (!aux->func_info) {
14373                         verbose(env, "missing btf func_info\n");
14374                         return -EINVAL;
14375                 }
14376                 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {
14377                         verbose(env, "callback function not static\n");
14378                         return -EINVAL;
14379                 }
14380
14381                 dst_reg->type = PTR_TO_FUNC;
14382                 dst_reg->subprogno = subprogno;
14383                 return 0;
14384         }
14385
14386         map = env->used_maps[aux->map_index];
14387         dst_reg->map_ptr = map;
14388
14389         if (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
14390             insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {
14391                 dst_reg->type = PTR_TO_MAP_VALUE;
14392                 dst_reg->off = aux->map_off;
14393                 WARN_ON_ONCE(map->max_entries != 1);
14394                 /* We want reg->id to be same (0) as map_value is not distinct */
14395         } else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||
14396                    insn->src_reg == BPF_PSEUDO_MAP_IDX) {
14397                 dst_reg->type = CONST_PTR_TO_MAP;
14398         } else {
14399                 verbose(env, "bpf verifier is misconfigured\n");
14400                 return -EINVAL;
14401         }
14402
14403         return 0;
14404 }
14405
14406 static bool may_access_skb(enum bpf_prog_type type)
14407 {
14408         switch (type) {
14409         case BPF_PROG_TYPE_SOCKET_FILTER:
14410         case BPF_PROG_TYPE_SCHED_CLS:
14411         case BPF_PROG_TYPE_SCHED_ACT:
14412                 return true;
14413         default:
14414                 return false;
14415         }
14416 }
14417
14418 /* verify safety of LD_ABS|LD_IND instructions:
14419  * - they can only appear in the programs where ctx == skb
14420  * - since they are wrappers of function calls, they scratch R1-R5 registers,
14421  *   preserve R6-R9, and store return value into R0
14422  *
14423  * Implicit input:
14424  *   ctx == skb == R6 == CTX
14425  *
14426  * Explicit input:
14427  *   SRC == any register
14428  *   IMM == 32-bit immediate
14429  *
14430  * Output:
14431  *   R0 - 8/16/32-bit skb data converted to cpu endianness
14432  */
14433 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
14434 {
14435         struct bpf_reg_state *regs = cur_regs(env);
14436         static const int ctx_reg = BPF_REG_6;
14437         u8 mode = BPF_MODE(insn->code);
14438         int i, err;
14439
14440         if (!may_access_skb(resolve_prog_type(env->prog))) {
14441                 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n");
14442                 return -EINVAL;
14443         }
14444
14445         if (!env->ops->gen_ld_abs) {
14446                 verbose(env, "bpf verifier is misconfigured\n");
14447                 return -EINVAL;
14448         }
14449
14450         if (insn->dst_reg != BPF_REG_0 || insn->off != 0 ||
14451             BPF_SIZE(insn->code) == BPF_DW ||
14452             (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) {
14453                 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n");
14454                 return -EINVAL;
14455         }
14456
14457         /* check whether implicit source operand (register R6) is readable */
14458         err = check_reg_arg(env, ctx_reg, SRC_OP);
14459         if (err)
14460                 return err;
14461
14462         /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as
14463          * gen_ld_abs() may terminate the program at runtime, leading to
14464          * reference leak.
14465          */
14466         err = check_reference_leak(env);
14467         if (err) {
14468                 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n");
14469                 return err;
14470         }
14471
14472         if (env->cur_state->active_lock.ptr) {
14473                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n");
14474                 return -EINVAL;
14475         }
14476
14477         if (env->cur_state->active_rcu_lock) {
14478                 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n");
14479                 return -EINVAL;
14480         }
14481
14482         if (regs[ctx_reg].type != PTR_TO_CTX) {
14483                 verbose(env,
14484                         "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n");
14485                 return -EINVAL;
14486         }
14487
14488         if (mode == BPF_IND) {
14489                 /* check explicit source operand */
14490                 err = check_reg_arg(env, insn->src_reg, SRC_OP);
14491                 if (err)
14492                         return err;
14493         }
14494
14495         err = check_ptr_off_reg(env, &regs[ctx_reg], ctx_reg);
14496         if (err < 0)
14497                 return err;
14498
14499         /* reset caller saved regs to unreadable */
14500         for (i = 0; i < CALLER_SAVED_REGS; i++) {
14501                 mark_reg_not_init(env, regs, caller_saved[i]);
14502                 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
14503         }
14504
14505         /* mark destination R0 register as readable, since it contains
14506          * the value fetched from the packet.
14507          * Already marked as written above.
14508          */
14509         mark_reg_unknown(env, regs, BPF_REG_0);
14510         /* ld_abs load up to 32-bit skb data. */
14511         regs[BPF_REG_0].subreg_def = env->insn_idx + 1;
14512         return 0;
14513 }
14514
14515 static int check_return_code(struct bpf_verifier_env *env)
14516 {
14517         struct tnum enforce_attach_type_range = tnum_unknown;
14518         const struct bpf_prog *prog = env->prog;
14519         struct bpf_reg_state *reg;
14520         struct tnum range = tnum_range(0, 1), const_0 = tnum_const(0);
14521         enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
14522         int err;
14523         struct bpf_func_state *frame = env->cur_state->frame[0];
14524         const bool is_subprog = frame->subprogno;
14525
14526         /* LSM and struct_ops func-ptr's return type could be "void" */
14527         if (!is_subprog) {
14528                 switch (prog_type) {
14529                 case BPF_PROG_TYPE_LSM:
14530                         if (prog->expected_attach_type == BPF_LSM_CGROUP)
14531                                 /* See below, can be 0 or 0-1 depending on hook. */
14532                                 break;
14533                         fallthrough;
14534                 case BPF_PROG_TYPE_STRUCT_OPS:
14535                         if (!prog->aux->attach_func_proto->type)
14536                                 return 0;
14537                         break;
14538                 default:
14539                         break;
14540                 }
14541         }
14542
14543         /* eBPF calling convention is such that R0 is used
14544          * to return the value from eBPF program.
14545          * Make sure that it's readable at this time
14546          * of bpf_exit, which means that program wrote
14547          * something into it earlier
14548          */
14549         err = check_reg_arg(env, BPF_REG_0, SRC_OP);
14550         if (err)
14551                 return err;
14552
14553         if (is_pointer_value(env, BPF_REG_0)) {
14554                 verbose(env, "R0 leaks addr as return value\n");
14555                 return -EACCES;
14556         }
14557
14558         reg = cur_regs(env) + BPF_REG_0;
14559
14560         if (frame->in_async_callback_fn) {
14561                 /* enforce return zero from async callbacks like timer */
14562                 if (reg->type != SCALAR_VALUE) {
14563                         verbose(env, "In async callback the register R0 is not a known value (%s)\n",
14564                                 reg_type_str(env, reg->type));
14565                         return -EINVAL;
14566                 }
14567
14568                 if (!tnum_in(const_0, reg->var_off)) {
14569                         verbose_invalid_scalar(env, reg, &const_0, "async callback", "R0");
14570                         return -EINVAL;
14571                 }
14572                 return 0;
14573         }
14574
14575         if (is_subprog) {
14576                 if (reg->type != SCALAR_VALUE) {
14577                         verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n",
14578                                 reg_type_str(env, reg->type));
14579                         return -EINVAL;
14580                 }
14581                 return 0;
14582         }
14583
14584         switch (prog_type) {
14585         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
14586                 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||
14587                     env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG ||
14588                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME ||
14589                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME ||
14590                     env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME ||
14591                     env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME)
14592                         range = tnum_range(1, 1);
14593                 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND ||
14594                     env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND)
14595                         range = tnum_range(0, 3);
14596                 break;
14597         case BPF_PROG_TYPE_CGROUP_SKB:
14598                 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {
14599                         range = tnum_range(0, 3);
14600                         enforce_attach_type_range = tnum_range(2, 3);
14601                 }
14602                 break;
14603         case BPF_PROG_TYPE_CGROUP_SOCK:
14604         case BPF_PROG_TYPE_SOCK_OPS:
14605         case BPF_PROG_TYPE_CGROUP_DEVICE:
14606         case BPF_PROG_TYPE_CGROUP_SYSCTL:
14607         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
14608                 break;
14609         case BPF_PROG_TYPE_RAW_TRACEPOINT:
14610                 if (!env->prog->aux->attach_btf_id)
14611                         return 0;
14612                 range = tnum_const(0);
14613                 break;
14614         case BPF_PROG_TYPE_TRACING:
14615                 switch (env->prog->expected_attach_type) {
14616                 case BPF_TRACE_FENTRY:
14617                 case BPF_TRACE_FEXIT:
14618                         range = tnum_const(0);
14619                         break;
14620                 case BPF_TRACE_RAW_TP:
14621                 case BPF_MODIFY_RETURN:
14622                         return 0;
14623                 case BPF_TRACE_ITER:
14624                         break;
14625                 default:
14626                         return -ENOTSUPP;
14627                 }
14628                 break;
14629         case BPF_PROG_TYPE_SK_LOOKUP:
14630                 range = tnum_range(SK_DROP, SK_PASS);
14631                 break;
14632
14633         case BPF_PROG_TYPE_LSM:
14634                 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) {
14635                         /* Regular BPF_PROG_TYPE_LSM programs can return
14636                          * any value.
14637                          */
14638                         return 0;
14639                 }
14640                 if (!env->prog->aux->attach_func_proto->type) {
14641                         /* Make sure programs that attach to void
14642                          * hooks don't try to modify return value.
14643                          */
14644                         range = tnum_range(1, 1);
14645                 }
14646                 break;
14647
14648         case BPF_PROG_TYPE_NETFILTER:
14649                 range = tnum_range(NF_DROP, NF_ACCEPT);
14650                 break;
14651         case BPF_PROG_TYPE_EXT:
14652                 /* freplace program can return anything as its return value
14653                  * depends on the to-be-replaced kernel func or bpf program.
14654                  */
14655         default:
14656                 return 0;
14657         }
14658
14659         if (reg->type != SCALAR_VALUE) {
14660                 verbose(env, "At program exit the register R0 is not a known value (%s)\n",
14661                         reg_type_str(env, reg->type));
14662                 return -EINVAL;
14663         }
14664
14665         if (!tnum_in(range, reg->var_off)) {
14666                 verbose_invalid_scalar(env, reg, &range, "program exit", "R0");
14667                 if (prog->expected_attach_type == BPF_LSM_CGROUP &&
14668                     prog_type == BPF_PROG_TYPE_LSM &&
14669                     !prog->aux->attach_func_proto->type)
14670                         verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n");
14671                 return -EINVAL;
14672         }
14673
14674         if (!tnum_is_unknown(enforce_attach_type_range) &&
14675             tnum_in(enforce_attach_type_range, reg->var_off))
14676                 env->prog->enforce_expected_attach_type = 1;
14677         return 0;
14678 }
14679
14680 /* non-recursive DFS pseudo code
14681  * 1  procedure DFS-iterative(G,v):
14682  * 2      label v as discovered
14683  * 3      let S be a stack
14684  * 4      S.push(v)
14685  * 5      while S is not empty
14686  * 6            t <- S.peek()
14687  * 7            if t is what we're looking for:
14688  * 8                return t
14689  * 9            for all edges e in G.adjacentEdges(t) do
14690  * 10               if edge e is already labelled
14691  * 11                   continue with the next edge
14692  * 12               w <- G.adjacentVertex(t,e)
14693  * 13               if vertex w is not discovered and not explored
14694  * 14                   label e as tree-edge
14695  * 15                   label w as discovered
14696  * 16                   S.push(w)
14697  * 17                   continue at 5
14698  * 18               else if vertex w is discovered
14699  * 19                   label e as back-edge
14700  * 20               else
14701  * 21                   // vertex w is explored
14702  * 22                   label e as forward- or cross-edge
14703  * 23           label t as explored
14704  * 24           S.pop()
14705  *
14706  * convention:
14707  * 0x10 - discovered
14708  * 0x11 - discovered and fall-through edge labelled
14709  * 0x12 - discovered and fall-through and branch edges labelled
14710  * 0x20 - explored
14711  */
14712
14713 enum {
14714         DISCOVERED = 0x10,
14715         EXPLORED = 0x20,
14716         FALLTHROUGH = 1,
14717         BRANCH = 2,
14718 };
14719
14720 static u32 state_htab_size(struct bpf_verifier_env *env)
14721 {
14722         return env->prog->len;
14723 }
14724
14725 static struct bpf_verifier_state_list **explored_state(
14726                                         struct bpf_verifier_env *env,
14727                                         int idx)
14728 {
14729         struct bpf_verifier_state *cur = env->cur_state;
14730         struct bpf_func_state *state = cur->frame[cur->curframe];
14731
14732         return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)];
14733 }
14734
14735 static void mark_prune_point(struct bpf_verifier_env *env, int idx)
14736 {
14737         env->insn_aux_data[idx].prune_point = true;
14738 }
14739
14740 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx)
14741 {
14742         return env->insn_aux_data[insn_idx].prune_point;
14743 }
14744
14745 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx)
14746 {
14747         env->insn_aux_data[idx].force_checkpoint = true;
14748 }
14749
14750 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx)
14751 {
14752         return env->insn_aux_data[insn_idx].force_checkpoint;
14753 }
14754
14755
14756 enum {
14757         DONE_EXPLORING = 0,
14758         KEEP_EXPLORING = 1,
14759 };
14760
14761 /* t, w, e - match pseudo-code above:
14762  * t - index of current instruction
14763  * w - next instruction
14764  * e - edge
14765  */
14766 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
14767 {
14768         int *insn_stack = env->cfg.insn_stack;
14769         int *insn_state = env->cfg.insn_state;
14770
14771         if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH))
14772                 return DONE_EXPLORING;
14773
14774         if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH))
14775                 return DONE_EXPLORING;
14776
14777         if (w < 0 || w >= env->prog->len) {
14778                 verbose_linfo(env, t, "%d: ", t);
14779                 verbose(env, "jump out of range from insn %d to %d\n", t, w);
14780                 return -EINVAL;
14781         }
14782
14783         if (e == BRANCH) {
14784                 /* mark branch target for state pruning */
14785                 mark_prune_point(env, w);
14786                 mark_jmp_point(env, w);
14787         }
14788
14789         if (insn_state[w] == 0) {
14790                 /* tree-edge */
14791                 insn_state[t] = DISCOVERED | e;
14792                 insn_state[w] = DISCOVERED;
14793                 if (env->cfg.cur_stack >= env->prog->len)
14794                         return -E2BIG;
14795                 insn_stack[env->cfg.cur_stack++] = w;
14796                 return KEEP_EXPLORING;
14797         } else if ((insn_state[w] & 0xF0) == DISCOVERED) {
14798                 if (env->bpf_capable)
14799                         return DONE_EXPLORING;
14800                 verbose_linfo(env, t, "%d: ", t);
14801                 verbose_linfo(env, w, "%d: ", w);
14802                 verbose(env, "back-edge from insn %d to %d\n", t, w);
14803                 return -EINVAL;
14804         } else if (insn_state[w] == EXPLORED) {
14805                 /* forward- or cross-edge */
14806                 insn_state[t] = DISCOVERED | e;
14807         } else {
14808                 verbose(env, "insn state internal bug\n");
14809                 return -EFAULT;
14810         }
14811         return DONE_EXPLORING;
14812 }
14813
14814 static int visit_func_call_insn(int t, struct bpf_insn *insns,
14815                                 struct bpf_verifier_env *env,
14816                                 bool visit_callee)
14817 {
14818         int ret, insn_sz;
14819
14820         insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1;
14821         ret = push_insn(t, t + insn_sz, FALLTHROUGH, env);
14822         if (ret)
14823                 return ret;
14824
14825         mark_prune_point(env, t + insn_sz);
14826         /* when we exit from subprog, we need to record non-linear history */
14827         mark_jmp_point(env, t + insn_sz);
14828
14829         if (visit_callee) {
14830                 mark_prune_point(env, t);
14831                 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env);
14832         }
14833         return ret;
14834 }
14835
14836 /* Visits the instruction at index t and returns one of the following:
14837  *  < 0 - an error occurred
14838  *  DONE_EXPLORING - the instruction was fully explored
14839  *  KEEP_EXPLORING - there is still work to be done before it is fully explored
14840  */
14841 static int visit_insn(int t, struct bpf_verifier_env *env)
14842 {
14843         struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t];
14844         int ret, off, insn_sz;
14845
14846         if (bpf_pseudo_func(insn))
14847                 return visit_func_call_insn(t, insns, env, true);
14848
14849         /* All non-branch instructions have a single fall-through edge. */
14850         if (BPF_CLASS(insn->code) != BPF_JMP &&
14851             BPF_CLASS(insn->code) != BPF_JMP32) {
14852                 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
14853                 return push_insn(t, t + insn_sz, FALLTHROUGH, env);
14854         }
14855
14856         switch (BPF_OP(insn->code)) {
14857         case BPF_EXIT:
14858                 return DONE_EXPLORING;
14859
14860         case BPF_CALL:
14861                 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback)
14862                         /* Mark this call insn as a prune point to trigger
14863                          * is_state_visited() check before call itself is
14864                          * processed by __check_func_call(). Otherwise new
14865                          * async state will be pushed for further exploration.
14866                          */
14867                         mark_prune_point(env, t);
14868                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
14869                         struct bpf_kfunc_call_arg_meta meta;
14870
14871                         ret = fetch_kfunc_meta(env, insn, &meta, NULL);
14872                         if (ret == 0 && is_iter_next_kfunc(&meta)) {
14873                                 mark_prune_point(env, t);
14874                                 /* Checking and saving state checkpoints at iter_next() call
14875                                  * is crucial for fast convergence of open-coded iterator loop
14876                                  * logic, so we need to force it. If we don't do that,
14877                                  * is_state_visited() might skip saving a checkpoint, causing
14878                                  * unnecessarily long sequence of not checkpointed
14879                                  * instructions and jumps, leading to exhaustion of jump
14880                                  * history buffer, and potentially other undesired outcomes.
14881                                  * It is expected that with correct open-coded iterators
14882                                  * convergence will happen quickly, so we don't run a risk of
14883                                  * exhausting memory.
14884                                  */
14885                                 mark_force_checkpoint(env, t);
14886                         }
14887                 }
14888                 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL);
14889
14890         case BPF_JA:
14891                 if (BPF_SRC(insn->code) != BPF_K)
14892                         return -EINVAL;
14893
14894                 if (BPF_CLASS(insn->code) == BPF_JMP)
14895                         off = insn->off;
14896                 else
14897                         off = insn->imm;
14898
14899                 /* unconditional jump with single edge */
14900                 ret = push_insn(t, t + off + 1, FALLTHROUGH, env);
14901                 if (ret)
14902                         return ret;
14903
14904                 mark_prune_point(env, t + off + 1);
14905                 mark_jmp_point(env, t + off + 1);
14906
14907                 return ret;
14908
14909         default:
14910                 /* conditional jump with two edges */
14911                 mark_prune_point(env, t);
14912
14913                 ret = push_insn(t, t + 1, FALLTHROUGH, env);
14914                 if (ret)
14915                         return ret;
14916
14917                 return push_insn(t, t + insn->off + 1, BRANCH, env);
14918         }
14919 }
14920
14921 /* non-recursive depth-first-search to detect loops in BPF program
14922  * loop == back-edge in directed graph
14923  */
14924 static int check_cfg(struct bpf_verifier_env *env)
14925 {
14926         int insn_cnt = env->prog->len;
14927         int *insn_stack, *insn_state;
14928         int ret = 0;
14929         int i;
14930
14931         insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14932         if (!insn_state)
14933                 return -ENOMEM;
14934
14935         insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL);
14936         if (!insn_stack) {
14937                 kvfree(insn_state);
14938                 return -ENOMEM;
14939         }
14940
14941         insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */
14942         insn_stack[0] = 0; /* 0 is the first instruction */
14943         env->cfg.cur_stack = 1;
14944
14945         while (env->cfg.cur_stack > 0) {
14946                 int t = insn_stack[env->cfg.cur_stack - 1];
14947
14948                 ret = visit_insn(t, env);
14949                 switch (ret) {
14950                 case DONE_EXPLORING:
14951                         insn_state[t] = EXPLORED;
14952                         env->cfg.cur_stack--;
14953                         break;
14954                 case KEEP_EXPLORING:
14955                         break;
14956                 default:
14957                         if (ret > 0) {
14958                                 verbose(env, "visit_insn internal bug\n");
14959                                 ret = -EFAULT;
14960                         }
14961                         goto err_free;
14962                 }
14963         }
14964
14965         if (env->cfg.cur_stack < 0) {
14966                 verbose(env, "pop stack internal bug\n");
14967                 ret = -EFAULT;
14968                 goto err_free;
14969         }
14970
14971         for (i = 0; i < insn_cnt; i++) {
14972                 struct bpf_insn *insn = &env->prog->insnsi[i];
14973
14974                 if (insn_state[i] != EXPLORED) {
14975                         verbose(env, "unreachable insn %d\n", i);
14976                         ret = -EINVAL;
14977                         goto err_free;
14978                 }
14979                 if (bpf_is_ldimm64(insn)) {
14980                         if (insn_state[i + 1] != 0) {
14981                                 verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
14982                                 ret = -EINVAL;
14983                                 goto err_free;
14984                         }
14985                         i++; /* skip second half of ldimm64 */
14986                 }
14987         }
14988         ret = 0; /* cfg looks good */
14989
14990 err_free:
14991         kvfree(insn_state);
14992         kvfree(insn_stack);
14993         env->cfg.insn_state = env->cfg.insn_stack = NULL;
14994         return ret;
14995 }
14996
14997 static int check_abnormal_return(struct bpf_verifier_env *env)
14998 {
14999         int i;
15000
15001         for (i = 1; i < env->subprog_cnt; i++) {
15002                 if (env->subprog_info[i].has_ld_abs) {
15003                         verbose(env, "LD_ABS is not allowed in subprogs without BTF\n");
15004                         return -EINVAL;
15005                 }
15006                 if (env->subprog_info[i].has_tail_call) {
15007                         verbose(env, "tail_call is not allowed in subprogs without BTF\n");
15008                         return -EINVAL;
15009                 }
15010         }
15011         return 0;
15012 }
15013
15014 /* The minimum supported BTF func info size */
15015 #define MIN_BPF_FUNCINFO_SIZE   8
15016 #define MAX_FUNCINFO_REC_SIZE   252
15017
15018 static int check_btf_func(struct bpf_verifier_env *env,
15019                           const union bpf_attr *attr,
15020                           bpfptr_t uattr)
15021 {
15022         const struct btf_type *type, *func_proto, *ret_type;
15023         u32 i, nfuncs, urec_size, min_size;
15024         u32 krec_size = sizeof(struct bpf_func_info);
15025         struct bpf_func_info *krecord;
15026         struct bpf_func_info_aux *info_aux = NULL;
15027         struct bpf_prog *prog;
15028         const struct btf *btf;
15029         bpfptr_t urecord;
15030         u32 prev_offset = 0;
15031         bool scalar_return;
15032         int ret = -ENOMEM;
15033
15034         nfuncs = attr->func_info_cnt;
15035         if (!nfuncs) {
15036                 if (check_abnormal_return(env))
15037                         return -EINVAL;
15038                 return 0;
15039         }
15040
15041         if (nfuncs != env->subprog_cnt) {
15042                 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n");
15043                 return -EINVAL;
15044         }
15045
15046         urec_size = attr->func_info_rec_size;
15047         if (urec_size < MIN_BPF_FUNCINFO_SIZE ||
15048             urec_size > MAX_FUNCINFO_REC_SIZE ||
15049             urec_size % sizeof(u32)) {
15050                 verbose(env, "invalid func info rec size %u\n", urec_size);
15051                 return -EINVAL;
15052         }
15053
15054         prog = env->prog;
15055         btf = prog->aux->btf;
15056
15057         urecord = make_bpfptr(attr->func_info, uattr.is_kernel);
15058         min_size = min_t(u32, krec_size, urec_size);
15059
15060         krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN);
15061         if (!krecord)
15062                 return -ENOMEM;
15063         info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN);
15064         if (!info_aux)
15065                 goto err_free;
15066
15067         for (i = 0; i < nfuncs; i++) {
15068                 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size);
15069                 if (ret) {
15070                         if (ret == -E2BIG) {
15071                                 verbose(env, "nonzero tailing record in func info");
15072                                 /* set the size kernel expects so loader can zero
15073                                  * out the rest of the record.
15074                                  */
15075                                 if (copy_to_bpfptr_offset(uattr,
15076                                                           offsetof(union bpf_attr, func_info_rec_size),
15077                                                           &min_size, sizeof(min_size)))
15078                                         ret = -EFAULT;
15079                         }
15080                         goto err_free;
15081                 }
15082
15083                 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) {
15084                         ret = -EFAULT;
15085                         goto err_free;
15086                 }
15087
15088                 /* check insn_off */
15089                 ret = -EINVAL;
15090                 if (i == 0) {
15091                         if (krecord[i].insn_off) {
15092                                 verbose(env,
15093                                         "nonzero insn_off %u for the first func info record",
15094                                         krecord[i].insn_off);
15095                                 goto err_free;
15096                         }
15097                 } else if (krecord[i].insn_off <= prev_offset) {
15098                         verbose(env,
15099                                 "same or smaller insn offset (%u) than previous func info record (%u)",
15100                                 krecord[i].insn_off, prev_offset);
15101                         goto err_free;
15102                 }
15103
15104                 if (env->subprog_info[i].start != krecord[i].insn_off) {
15105                         verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n");
15106                         goto err_free;
15107                 }
15108
15109                 /* check type_id */
15110                 type = btf_type_by_id(btf, krecord[i].type_id);
15111                 if (!type || !btf_type_is_func(type)) {
15112                         verbose(env, "invalid type id %d in func info",
15113                                 krecord[i].type_id);
15114                         goto err_free;
15115                 }
15116                 info_aux[i].linkage = BTF_INFO_VLEN(type->info);
15117
15118                 func_proto = btf_type_by_id(btf, type->type);
15119                 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto)))
15120                         /* btf_func_check() already verified it during BTF load */
15121                         goto err_free;
15122                 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL);
15123                 scalar_return =
15124                         btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type);
15125                 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) {
15126                         verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n");
15127                         goto err_free;
15128                 }
15129                 if (i && !scalar_return && env->subprog_info[i].has_tail_call) {
15130                         verbose(env, "tail_call is only allowed in functions that return 'int'.\n");
15131                         goto err_free;
15132                 }
15133
15134                 prev_offset = krecord[i].insn_off;
15135                 bpfptr_add(&urecord, urec_size);
15136         }
15137
15138         prog->aux->func_info = krecord;
15139         prog->aux->func_info_cnt = nfuncs;
15140         prog->aux->func_info_aux = info_aux;
15141         return 0;
15142
15143 err_free:
15144         kvfree(krecord);
15145         kfree(info_aux);
15146         return ret;
15147 }
15148
15149 static void adjust_btf_func(struct bpf_verifier_env *env)
15150 {
15151         struct bpf_prog_aux *aux = env->prog->aux;
15152         int i;
15153
15154         if (!aux->func_info)
15155                 return;
15156
15157         for (i = 0; i < env->subprog_cnt; i++)
15158                 aux->func_info[i].insn_off = env->subprog_info[i].start;
15159 }
15160
15161 #define MIN_BPF_LINEINFO_SIZE   offsetofend(struct bpf_line_info, line_col)
15162 #define MAX_LINEINFO_REC_SIZE   MAX_FUNCINFO_REC_SIZE
15163
15164 static int check_btf_line(struct bpf_verifier_env *env,
15165                           const union bpf_attr *attr,
15166                           bpfptr_t uattr)
15167 {
15168         u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0;
15169         struct bpf_subprog_info *sub;
15170         struct bpf_line_info *linfo;
15171         struct bpf_prog *prog;
15172         const struct btf *btf;
15173         bpfptr_t ulinfo;
15174         int err;
15175
15176         nr_linfo = attr->line_info_cnt;
15177         if (!nr_linfo)
15178                 return 0;
15179         if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info))
15180                 return -EINVAL;
15181
15182         rec_size = attr->line_info_rec_size;
15183         if (rec_size < MIN_BPF_LINEINFO_SIZE ||
15184             rec_size > MAX_LINEINFO_REC_SIZE ||
15185             rec_size & (sizeof(u32) - 1))
15186                 return -EINVAL;
15187
15188         /* Need to zero it in case the userspace may
15189          * pass in a smaller bpf_line_info object.
15190          */
15191         linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info),
15192                          GFP_KERNEL | __GFP_NOWARN);
15193         if (!linfo)
15194                 return -ENOMEM;
15195
15196         prog = env->prog;
15197         btf = prog->aux->btf;
15198
15199         s = 0;
15200         sub = env->subprog_info;
15201         ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel);
15202         expected_size = sizeof(struct bpf_line_info);
15203         ncopy = min_t(u32, expected_size, rec_size);
15204         for (i = 0; i < nr_linfo; i++) {
15205                 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size);
15206                 if (err) {
15207                         if (err == -E2BIG) {
15208                                 verbose(env, "nonzero tailing record in line_info");
15209                                 if (copy_to_bpfptr_offset(uattr,
15210                                                           offsetof(union bpf_attr, line_info_rec_size),
15211                                                           &expected_size, sizeof(expected_size)))
15212                                         err = -EFAULT;
15213                         }
15214                         goto err_free;
15215                 }
15216
15217                 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) {
15218                         err = -EFAULT;
15219                         goto err_free;
15220                 }
15221
15222                 /*
15223                  * Check insn_off to ensure
15224                  * 1) strictly increasing AND
15225                  * 2) bounded by prog->len
15226                  *
15227                  * The linfo[0].insn_off == 0 check logically falls into
15228                  * the later "missing bpf_line_info for func..." case
15229                  * because the first linfo[0].insn_off must be the
15230                  * first sub also and the first sub must have
15231                  * subprog_info[0].start == 0.
15232                  */
15233                 if ((i && linfo[i].insn_off <= prev_offset) ||
15234                     linfo[i].insn_off >= prog->len) {
15235                         verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n",
15236                                 i, linfo[i].insn_off, prev_offset,
15237                                 prog->len);
15238                         err = -EINVAL;
15239                         goto err_free;
15240                 }
15241
15242                 if (!prog->insnsi[linfo[i].insn_off].code) {
15243                         verbose(env,
15244                                 "Invalid insn code at line_info[%u].insn_off\n",
15245                                 i);
15246                         err = -EINVAL;
15247                         goto err_free;
15248                 }
15249
15250                 if (!btf_name_by_offset(btf, linfo[i].line_off) ||
15251                     !btf_name_by_offset(btf, linfo[i].file_name_off)) {
15252                         verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i);
15253                         err = -EINVAL;
15254                         goto err_free;
15255                 }
15256
15257                 if (s != env->subprog_cnt) {
15258                         if (linfo[i].insn_off == sub[s].start) {
15259                                 sub[s].linfo_idx = i;
15260                                 s++;
15261                         } else if (sub[s].start < linfo[i].insn_off) {
15262                                 verbose(env, "missing bpf_line_info for func#%u\n", s);
15263                                 err = -EINVAL;
15264                                 goto err_free;
15265                         }
15266                 }
15267
15268                 prev_offset = linfo[i].insn_off;
15269                 bpfptr_add(&ulinfo, rec_size);
15270         }
15271
15272         if (s != env->subprog_cnt) {
15273                 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n",
15274                         env->subprog_cnt - s, s);
15275                 err = -EINVAL;
15276                 goto err_free;
15277         }
15278
15279         prog->aux->linfo = linfo;
15280         prog->aux->nr_linfo = nr_linfo;
15281
15282         return 0;
15283
15284 err_free:
15285         kvfree(linfo);
15286         return err;
15287 }
15288
15289 #define MIN_CORE_RELO_SIZE      sizeof(struct bpf_core_relo)
15290 #define MAX_CORE_RELO_SIZE      MAX_FUNCINFO_REC_SIZE
15291
15292 static int check_core_relo(struct bpf_verifier_env *env,
15293                            const union bpf_attr *attr,
15294                            bpfptr_t uattr)
15295 {
15296         u32 i, nr_core_relo, ncopy, expected_size, rec_size;
15297         struct bpf_core_relo core_relo = {};
15298         struct bpf_prog *prog = env->prog;
15299         const struct btf *btf = prog->aux->btf;
15300         struct bpf_core_ctx ctx = {
15301                 .log = &env->log,
15302                 .btf = btf,
15303         };
15304         bpfptr_t u_core_relo;
15305         int err;
15306
15307         nr_core_relo = attr->core_relo_cnt;
15308         if (!nr_core_relo)
15309                 return 0;
15310         if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo))
15311                 return -EINVAL;
15312
15313         rec_size = attr->core_relo_rec_size;
15314         if (rec_size < MIN_CORE_RELO_SIZE ||
15315             rec_size > MAX_CORE_RELO_SIZE ||
15316             rec_size % sizeof(u32))
15317                 return -EINVAL;
15318
15319         u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel);
15320         expected_size = sizeof(struct bpf_core_relo);
15321         ncopy = min_t(u32, expected_size, rec_size);
15322
15323         /* Unlike func_info and line_info, copy and apply each CO-RE
15324          * relocation record one at a time.
15325          */
15326         for (i = 0; i < nr_core_relo; i++) {
15327                 /* future proofing when sizeof(bpf_core_relo) changes */
15328                 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size);
15329                 if (err) {
15330                         if (err == -E2BIG) {
15331                                 verbose(env, "nonzero tailing record in core_relo");
15332                                 if (copy_to_bpfptr_offset(uattr,
15333                                                           offsetof(union bpf_attr, core_relo_rec_size),
15334                                                           &expected_size, sizeof(expected_size)))
15335                                         err = -EFAULT;
15336                         }
15337                         break;
15338                 }
15339
15340                 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) {
15341                         err = -EFAULT;
15342                         break;
15343                 }
15344
15345                 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) {
15346                         verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n",
15347                                 i, core_relo.insn_off, prog->len);
15348                         err = -EINVAL;
15349                         break;
15350                 }
15351
15352                 err = bpf_core_apply(&ctx, &core_relo, i,
15353                                      &prog->insnsi[core_relo.insn_off / 8]);
15354                 if (err)
15355                         break;
15356                 bpfptr_add(&u_core_relo, rec_size);
15357         }
15358         return err;
15359 }
15360
15361 static int check_btf_info(struct bpf_verifier_env *env,
15362                           const union bpf_attr *attr,
15363                           bpfptr_t uattr)
15364 {
15365         struct btf *btf;
15366         int err;
15367
15368         if (!attr->func_info_cnt && !attr->line_info_cnt) {
15369                 if (check_abnormal_return(env))
15370                         return -EINVAL;
15371                 return 0;
15372         }
15373
15374         btf = btf_get_by_fd(attr->prog_btf_fd);
15375         if (IS_ERR(btf))
15376                 return PTR_ERR(btf);
15377         if (btf_is_kernel(btf)) {
15378                 btf_put(btf);
15379                 return -EACCES;
15380         }
15381         env->prog->aux->btf = btf;
15382
15383         err = check_btf_func(env, attr, uattr);
15384         if (err)
15385                 return err;
15386
15387         err = check_btf_line(env, attr, uattr);
15388         if (err)
15389                 return err;
15390
15391         err = check_core_relo(env, attr, uattr);
15392         if (err)
15393                 return err;
15394
15395         return 0;
15396 }
15397
15398 /* check %cur's range satisfies %old's */
15399 static bool range_within(struct bpf_reg_state *old,
15400                          struct bpf_reg_state *cur)
15401 {
15402         return old->umin_value <= cur->umin_value &&
15403                old->umax_value >= cur->umax_value &&
15404                old->smin_value <= cur->smin_value &&
15405                old->smax_value >= cur->smax_value &&
15406                old->u32_min_value <= cur->u32_min_value &&
15407                old->u32_max_value >= cur->u32_max_value &&
15408                old->s32_min_value <= cur->s32_min_value &&
15409                old->s32_max_value >= cur->s32_max_value;
15410 }
15411
15412 /* If in the old state two registers had the same id, then they need to have
15413  * the same id in the new state as well.  But that id could be different from
15414  * the old state, so we need to track the mapping from old to new ids.
15415  * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent
15416  * regs with old id 5 must also have new id 9 for the new state to be safe.  But
15417  * regs with a different old id could still have new id 9, we don't care about
15418  * that.
15419  * So we look through our idmap to see if this old id has been seen before.  If
15420  * so, we require the new id to match; otherwise, we add the id pair to the map.
15421  */
15422 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15423 {
15424         struct bpf_id_pair *map = idmap->map;
15425         unsigned int i;
15426
15427         /* either both IDs should be set or both should be zero */
15428         if (!!old_id != !!cur_id)
15429                 return false;
15430
15431         if (old_id == 0) /* cur_id == 0 as well */
15432                 return true;
15433
15434         for (i = 0; i < BPF_ID_MAP_SIZE; i++) {
15435                 if (!map[i].old) {
15436                         /* Reached an empty slot; haven't seen this id before */
15437                         map[i].old = old_id;
15438                         map[i].cur = cur_id;
15439                         return true;
15440                 }
15441                 if (map[i].old == old_id)
15442                         return map[i].cur == cur_id;
15443                 if (map[i].cur == cur_id)
15444                         return false;
15445         }
15446         /* We ran out of idmap slots, which should be impossible */
15447         WARN_ON_ONCE(1);
15448         return false;
15449 }
15450
15451 /* Similar to check_ids(), but allocate a unique temporary ID
15452  * for 'old_id' or 'cur_id' of zero.
15453  * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid.
15454  */
15455 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap)
15456 {
15457         old_id = old_id ? old_id : ++idmap->tmp_id_gen;
15458         cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen;
15459
15460         return check_ids(old_id, cur_id, idmap);
15461 }
15462
15463 static void clean_func_state(struct bpf_verifier_env *env,
15464                              struct bpf_func_state *st)
15465 {
15466         enum bpf_reg_liveness live;
15467         int i, j;
15468
15469         for (i = 0; i < BPF_REG_FP; i++) {
15470                 live = st->regs[i].live;
15471                 /* liveness must not touch this register anymore */
15472                 st->regs[i].live |= REG_LIVE_DONE;
15473                 if (!(live & REG_LIVE_READ))
15474                         /* since the register is unused, clear its state
15475                          * to make further comparison simpler
15476                          */
15477                         __mark_reg_not_init(env, &st->regs[i]);
15478         }
15479
15480         for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) {
15481                 live = st->stack[i].spilled_ptr.live;
15482                 /* liveness must not touch this stack slot anymore */
15483                 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE;
15484                 if (!(live & REG_LIVE_READ)) {
15485                         __mark_reg_not_init(env, &st->stack[i].spilled_ptr);
15486                         for (j = 0; j < BPF_REG_SIZE; j++)
15487                                 st->stack[i].slot_type[j] = STACK_INVALID;
15488                 }
15489         }
15490 }
15491
15492 static void clean_verifier_state(struct bpf_verifier_env *env,
15493                                  struct bpf_verifier_state *st)
15494 {
15495         int i;
15496
15497         if (st->frame[0]->regs[0].live & REG_LIVE_DONE)
15498                 /* all regs in this state in all frames were already marked */
15499                 return;
15500
15501         for (i = 0; i <= st->curframe; i++)
15502                 clean_func_state(env, st->frame[i]);
15503 }
15504
15505 /* the parentage chains form a tree.
15506  * the verifier states are added to state lists at given insn and
15507  * pushed into state stack for future exploration.
15508  * when the verifier reaches bpf_exit insn some of the verifer states
15509  * stored in the state lists have their final liveness state already,
15510  * but a lot of states will get revised from liveness point of view when
15511  * the verifier explores other branches.
15512  * Example:
15513  * 1: r0 = 1
15514  * 2: if r1 == 100 goto pc+1
15515  * 3: r0 = 2
15516  * 4: exit
15517  * when the verifier reaches exit insn the register r0 in the state list of
15518  * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch
15519  * of insn 2 and goes exploring further. At the insn 4 it will walk the
15520  * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ.
15521  *
15522  * Since the verifier pushes the branch states as it sees them while exploring
15523  * the program the condition of walking the branch instruction for the second
15524  * time means that all states below this branch were already explored and
15525  * their final liveness marks are already propagated.
15526  * Hence when the verifier completes the search of state list in is_state_visited()
15527  * we can call this clean_live_states() function to mark all liveness states
15528  * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state'
15529  * will not be used.
15530  * This function also clears the registers and stack for states that !READ
15531  * to simplify state merging.
15532  *
15533  * Important note here that walking the same branch instruction in the callee
15534  * doesn't meant that the states are DONE. The verifier has to compare
15535  * the callsites
15536  */
15537 static void clean_live_states(struct bpf_verifier_env *env, int insn,
15538                               struct bpf_verifier_state *cur)
15539 {
15540         struct bpf_verifier_state_list *sl;
15541         int i;
15542
15543         sl = *explored_state(env, insn);
15544         while (sl) {
15545                 if (sl->state.branches)
15546                         goto next;
15547                 if (sl->state.insn_idx != insn ||
15548                     sl->state.curframe != cur->curframe)
15549                         goto next;
15550                 for (i = 0; i <= cur->curframe; i++)
15551                         if (sl->state.frame[i]->callsite != cur->frame[i]->callsite)
15552                                 goto next;
15553                 clean_verifier_state(env, &sl->state);
15554 next:
15555                 sl = sl->next;
15556         }
15557 }
15558
15559 static bool regs_exact(const struct bpf_reg_state *rold,
15560                        const struct bpf_reg_state *rcur,
15561                        struct bpf_idmap *idmap)
15562 {
15563         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15564                check_ids(rold->id, rcur->id, idmap) &&
15565                check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15566 }
15567
15568 /* Returns true if (rold safe implies rcur safe) */
15569 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold,
15570                     struct bpf_reg_state *rcur, struct bpf_idmap *idmap)
15571 {
15572         if (!(rold->live & REG_LIVE_READ))
15573                 /* explored state didn't use this */
15574                 return true;
15575         if (rold->type == NOT_INIT)
15576                 /* explored state can't have used this */
15577                 return true;
15578         if (rcur->type == NOT_INIT)
15579                 return false;
15580
15581         /* Enforce that register types have to match exactly, including their
15582          * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general
15583          * rule.
15584          *
15585          * One can make a point that using a pointer register as unbounded
15586          * SCALAR would be technically acceptable, but this could lead to
15587          * pointer leaks because scalars are allowed to leak while pointers
15588          * are not. We could make this safe in special cases if root is
15589          * calling us, but it's probably not worth the hassle.
15590          *
15591          * Also, register types that are *not* MAYBE_NULL could technically be
15592          * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE
15593          * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point
15594          * to the same map).
15595          * However, if the old MAYBE_NULL register then got NULL checked,
15596          * doing so could have affected others with the same id, and we can't
15597          * check for that because we lost the id when we converted to
15598          * a non-MAYBE_NULL variant.
15599          * So, as a general rule we don't allow mixing MAYBE_NULL and
15600          * non-MAYBE_NULL registers as well.
15601          */
15602         if (rold->type != rcur->type)
15603                 return false;
15604
15605         switch (base_type(rold->type)) {
15606         case SCALAR_VALUE:
15607                 if (env->explore_alu_limits) {
15608                         /* explore_alu_limits disables tnum_in() and range_within()
15609                          * logic and requires everything to be strict
15610                          */
15611                         return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 &&
15612                                check_scalar_ids(rold->id, rcur->id, idmap);
15613                 }
15614                 if (!rold->precise)
15615                         return true;
15616                 /* Why check_ids() for scalar registers?
15617                  *
15618                  * Consider the following BPF code:
15619                  *   1: r6 = ... unbound scalar, ID=a ...
15620                  *   2: r7 = ... unbound scalar, ID=b ...
15621                  *   3: if (r6 > r7) goto +1
15622                  *   4: r6 = r7
15623                  *   5: if (r6 > X) goto ...
15624                  *   6: ... memory operation using r7 ...
15625                  *
15626                  * First verification path is [1-6]:
15627                  * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7;
15628                  * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark
15629                  *   r7 <= X, because r6 and r7 share same id.
15630                  * Next verification path is [1-4, 6].
15631                  *
15632                  * Instruction (6) would be reached in two states:
15633                  *   I.  r6{.id=b}, r7{.id=b} via path 1-6;
15634                  *   II. r6{.id=a}, r7{.id=b} via path 1-4, 6.
15635                  *
15636                  * Use check_ids() to distinguish these states.
15637                  * ---
15638                  * Also verify that new value satisfies old value range knowledge.
15639                  */
15640                 return range_within(rold, rcur) &&
15641                        tnum_in(rold->var_off, rcur->var_off) &&
15642                        check_scalar_ids(rold->id, rcur->id, idmap);
15643         case PTR_TO_MAP_KEY:
15644         case PTR_TO_MAP_VALUE:
15645         case PTR_TO_MEM:
15646         case PTR_TO_BUF:
15647         case PTR_TO_TP_BUFFER:
15648                 /* If the new min/max/var_off satisfy the old ones and
15649                  * everything else matches, we are OK.
15650                  */
15651                 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 &&
15652                        range_within(rold, rcur) &&
15653                        tnum_in(rold->var_off, rcur->var_off) &&
15654                        check_ids(rold->id, rcur->id, idmap) &&
15655                        check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap);
15656         case PTR_TO_PACKET_META:
15657         case PTR_TO_PACKET:
15658                 /* We must have at least as much range as the old ptr
15659                  * did, so that any accesses which were safe before are
15660                  * still safe.  This is true even if old range < old off,
15661                  * since someone could have accessed through (ptr - k), or
15662                  * even done ptr -= k in a register, to get a safe access.
15663                  */
15664                 if (rold->range > rcur->range)
15665                         return false;
15666                 /* If the offsets don't match, we can't trust our alignment;
15667                  * nor can we be sure that we won't fall out of range.
15668                  */
15669                 if (rold->off != rcur->off)
15670                         return false;
15671                 /* id relations must be preserved */
15672                 if (!check_ids(rold->id, rcur->id, idmap))
15673                         return false;
15674                 /* new val must satisfy old val knowledge */
15675                 return range_within(rold, rcur) &&
15676                        tnum_in(rold->var_off, rcur->var_off);
15677         case PTR_TO_STACK:
15678                 /* two stack pointers are equal only if they're pointing to
15679                  * the same stack frame, since fp-8 in foo != fp-8 in bar
15680                  */
15681                 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno;
15682         default:
15683                 return regs_exact(rold, rcur, idmap);
15684         }
15685 }
15686
15687 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old,
15688                       struct bpf_func_state *cur, struct bpf_idmap *idmap)
15689 {
15690         int i, spi;
15691
15692         /* walk slots of the explored stack and ignore any additional
15693          * slots in the current stack, since explored(safe) state
15694          * didn't use them
15695          */
15696         for (i = 0; i < old->allocated_stack; i++) {
15697                 struct bpf_reg_state *old_reg, *cur_reg;
15698
15699                 spi = i / BPF_REG_SIZE;
15700
15701                 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) {
15702                         i += BPF_REG_SIZE - 1;
15703                         /* explored state didn't use this */
15704                         continue;
15705                 }
15706
15707                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID)
15708                         continue;
15709
15710                 if (env->allow_uninit_stack &&
15711                     old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC)
15712                         continue;
15713
15714                 /* explored stack has more populated slots than current stack
15715                  * and these slots were used
15716                  */
15717                 if (i >= cur->allocated_stack)
15718                         return false;
15719
15720                 /* if old state was safe with misc data in the stack
15721                  * it will be safe with zero-initialized stack.
15722                  * The opposite is not true
15723                  */
15724                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC &&
15725                     cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO)
15726                         continue;
15727                 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] !=
15728                     cur->stack[spi].slot_type[i % BPF_REG_SIZE])
15729                         /* Ex: old explored (safe) state has STACK_SPILL in
15730                          * this stack slot, but current has STACK_MISC ->
15731                          * this verifier states are not equivalent,
15732                          * return false to continue verification of this path
15733                          */
15734                         return false;
15735                 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1)
15736                         continue;
15737                 /* Both old and cur are having same slot_type */
15738                 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) {
15739                 case STACK_SPILL:
15740                         /* when explored and current stack slot are both storing
15741                          * spilled registers, check that stored pointers types
15742                          * are the same as well.
15743                          * Ex: explored safe path could have stored
15744                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8}
15745                          * but current path has stored:
15746                          * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16}
15747                          * such verifier states are not equivalent.
15748                          * return false to continue verification of this path
15749                          */
15750                         if (!regsafe(env, &old->stack[spi].spilled_ptr,
15751                                      &cur->stack[spi].spilled_ptr, idmap))
15752                                 return false;
15753                         break;
15754                 case STACK_DYNPTR:
15755                         old_reg = &old->stack[spi].spilled_ptr;
15756                         cur_reg = &cur->stack[spi].spilled_ptr;
15757                         if (old_reg->dynptr.type != cur_reg->dynptr.type ||
15758                             old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot ||
15759                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15760                                 return false;
15761                         break;
15762                 case STACK_ITER:
15763                         old_reg = &old->stack[spi].spilled_ptr;
15764                         cur_reg = &cur->stack[spi].spilled_ptr;
15765                         /* iter.depth is not compared between states as it
15766                          * doesn't matter for correctness and would otherwise
15767                          * prevent convergence; we maintain it only to prevent
15768                          * infinite loop check triggering, see
15769                          * iter_active_depths_differ()
15770                          */
15771                         if (old_reg->iter.btf != cur_reg->iter.btf ||
15772                             old_reg->iter.btf_id != cur_reg->iter.btf_id ||
15773                             old_reg->iter.state != cur_reg->iter.state ||
15774                             /* ignore {old_reg,cur_reg}->iter.depth, see above */
15775                             !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap))
15776                                 return false;
15777                         break;
15778                 case STACK_MISC:
15779                 case STACK_ZERO:
15780                 case STACK_INVALID:
15781                         continue;
15782                 /* Ensure that new unhandled slot types return false by default */
15783                 default:
15784                         return false;
15785                 }
15786         }
15787         return true;
15788 }
15789
15790 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur,
15791                     struct bpf_idmap *idmap)
15792 {
15793         int i;
15794
15795         if (old->acquired_refs != cur->acquired_refs)
15796                 return false;
15797
15798         for (i = 0; i < old->acquired_refs; i++) {
15799                 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap))
15800                         return false;
15801         }
15802
15803         return true;
15804 }
15805
15806 /* compare two verifier states
15807  *
15808  * all states stored in state_list are known to be valid, since
15809  * verifier reached 'bpf_exit' instruction through them
15810  *
15811  * this function is called when verifier exploring different branches of
15812  * execution popped from the state stack. If it sees an old state that has
15813  * more strict register state and more strict stack state then this execution
15814  * branch doesn't need to be explored further, since verifier already
15815  * concluded that more strict state leads to valid finish.
15816  *
15817  * Therefore two states are equivalent if register state is more conservative
15818  * and explored stack state is more conservative than the current one.
15819  * Example:
15820  *       explored                   current
15821  * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC)
15822  * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC)
15823  *
15824  * In other words if current stack state (one being explored) has more
15825  * valid slots than old one that already passed validation, it means
15826  * the verifier can stop exploring and conclude that current state is valid too
15827  *
15828  * Similarly with registers. If explored state has register type as invalid
15829  * whereas register type in current state is meaningful, it means that
15830  * the current state will reach 'bpf_exit' instruction safely
15831  */
15832 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old,
15833                               struct bpf_func_state *cur)
15834 {
15835         int i;
15836
15837         for (i = 0; i < MAX_BPF_REG; i++)
15838                 if (!regsafe(env, &old->regs[i], &cur->regs[i],
15839                              &env->idmap_scratch))
15840                         return false;
15841
15842         if (!stacksafe(env, old, cur, &env->idmap_scratch))
15843                 return false;
15844
15845         if (!refsafe(old, cur, &env->idmap_scratch))
15846                 return false;
15847
15848         return true;
15849 }
15850
15851 static bool states_equal(struct bpf_verifier_env *env,
15852                          struct bpf_verifier_state *old,
15853                          struct bpf_verifier_state *cur)
15854 {
15855         int i;
15856
15857         if (old->curframe != cur->curframe)
15858                 return false;
15859
15860         env->idmap_scratch.tmp_id_gen = env->id_gen;
15861         memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map));
15862
15863         /* Verification state from speculative execution simulation
15864          * must never prune a non-speculative execution one.
15865          */
15866         if (old->speculative && !cur->speculative)
15867                 return false;
15868
15869         if (old->active_lock.ptr != cur->active_lock.ptr)
15870                 return false;
15871
15872         /* Old and cur active_lock's have to be either both present
15873          * or both absent.
15874          */
15875         if (!!old->active_lock.id != !!cur->active_lock.id)
15876                 return false;
15877
15878         if (old->active_lock.id &&
15879             !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch))
15880                 return false;
15881
15882         if (old->active_rcu_lock != cur->active_rcu_lock)
15883                 return false;
15884
15885         /* for states to be equal callsites have to be the same
15886          * and all frame states need to be equivalent
15887          */
15888         for (i = 0; i <= old->curframe; i++) {
15889                 if (old->frame[i]->callsite != cur->frame[i]->callsite)
15890                         return false;
15891                 if (!func_states_equal(env, old->frame[i], cur->frame[i]))
15892                         return false;
15893         }
15894         return true;
15895 }
15896
15897 /* Return 0 if no propagation happened. Return negative error code if error
15898  * happened. Otherwise, return the propagated bit.
15899  */
15900 static int propagate_liveness_reg(struct bpf_verifier_env *env,
15901                                   struct bpf_reg_state *reg,
15902                                   struct bpf_reg_state *parent_reg)
15903 {
15904         u8 parent_flag = parent_reg->live & REG_LIVE_READ;
15905         u8 flag = reg->live & REG_LIVE_READ;
15906         int err;
15907
15908         /* When comes here, read flags of PARENT_REG or REG could be any of
15909          * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need
15910          * of propagation if PARENT_REG has strongest REG_LIVE_READ64.
15911          */
15912         if (parent_flag == REG_LIVE_READ64 ||
15913             /* Or if there is no read flag from REG. */
15914             !flag ||
15915             /* Or if the read flag from REG is the same as PARENT_REG. */
15916             parent_flag == flag)
15917                 return 0;
15918
15919         err = mark_reg_read(env, reg, parent_reg, flag);
15920         if (err)
15921                 return err;
15922
15923         return flag;
15924 }
15925
15926 /* A write screens off any subsequent reads; but write marks come from the
15927  * straight-line code between a state and its parent.  When we arrive at an
15928  * equivalent state (jump target or such) we didn't arrive by the straight-line
15929  * code, so read marks in the state must propagate to the parent regardless
15930  * of the state's write marks. That's what 'parent == state->parent' comparison
15931  * in mark_reg_read() is for.
15932  */
15933 static int propagate_liveness(struct bpf_verifier_env *env,
15934                               const struct bpf_verifier_state *vstate,
15935                               struct bpf_verifier_state *vparent)
15936 {
15937         struct bpf_reg_state *state_reg, *parent_reg;
15938         struct bpf_func_state *state, *parent;
15939         int i, frame, err = 0;
15940
15941         if (vparent->curframe != vstate->curframe) {
15942                 WARN(1, "propagate_live: parent frame %d current frame %d\n",
15943                      vparent->curframe, vstate->curframe);
15944                 return -EFAULT;
15945         }
15946         /* Propagate read liveness of registers... */
15947         BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG);
15948         for (frame = 0; frame <= vstate->curframe; frame++) {
15949                 parent = vparent->frame[frame];
15950                 state = vstate->frame[frame];
15951                 parent_reg = parent->regs;
15952                 state_reg = state->regs;
15953                 /* We don't need to worry about FP liveness, it's read-only */
15954                 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) {
15955                         err = propagate_liveness_reg(env, &state_reg[i],
15956                                                      &parent_reg[i]);
15957                         if (err < 0)
15958                                 return err;
15959                         if (err == REG_LIVE_READ64)
15960                                 mark_insn_zext(env, &parent_reg[i]);
15961                 }
15962
15963                 /* Propagate stack slots. */
15964                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE &&
15965                             i < parent->allocated_stack / BPF_REG_SIZE; i++) {
15966                         parent_reg = &parent->stack[i].spilled_ptr;
15967                         state_reg = &state->stack[i].spilled_ptr;
15968                         err = propagate_liveness_reg(env, state_reg,
15969                                                      parent_reg);
15970                         if (err < 0)
15971                                 return err;
15972                 }
15973         }
15974         return 0;
15975 }
15976
15977 /* find precise scalars in the previous equivalent state and
15978  * propagate them into the current state
15979  */
15980 static int propagate_precision(struct bpf_verifier_env *env,
15981                                const struct bpf_verifier_state *old)
15982 {
15983         struct bpf_reg_state *state_reg;
15984         struct bpf_func_state *state;
15985         int i, err = 0, fr;
15986         bool first;
15987
15988         for (fr = old->curframe; fr >= 0; fr--) {
15989                 state = old->frame[fr];
15990                 state_reg = state->regs;
15991                 first = true;
15992                 for (i = 0; i < BPF_REG_FP; i++, state_reg++) {
15993                         if (state_reg->type != SCALAR_VALUE ||
15994                             !state_reg->precise ||
15995                             !(state_reg->live & REG_LIVE_READ))
15996                                 continue;
15997                         if (env->log.level & BPF_LOG_LEVEL2) {
15998                                 if (first)
15999                                         verbose(env, "frame %d: propagating r%d", fr, i);
16000                                 else
16001                                         verbose(env, ",r%d", i);
16002                         }
16003                         bt_set_frame_reg(&env->bt, fr, i);
16004                         first = false;
16005                 }
16006
16007                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16008                         if (!is_spilled_reg(&state->stack[i]))
16009                                 continue;
16010                         state_reg = &state->stack[i].spilled_ptr;
16011                         if (state_reg->type != SCALAR_VALUE ||
16012                             !state_reg->precise ||
16013                             !(state_reg->live & REG_LIVE_READ))
16014                                 continue;
16015                         if (env->log.level & BPF_LOG_LEVEL2) {
16016                                 if (first)
16017                                         verbose(env, "frame %d: propagating fp%d",
16018                                                 fr, (-i - 1) * BPF_REG_SIZE);
16019                                 else
16020                                         verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE);
16021                         }
16022                         bt_set_frame_slot(&env->bt, fr, i);
16023                         first = false;
16024                 }
16025                 if (!first)
16026                         verbose(env, "\n");
16027         }
16028
16029         err = mark_chain_precision_batch(env);
16030         if (err < 0)
16031                 return err;
16032
16033         return 0;
16034 }
16035
16036 static bool states_maybe_looping(struct bpf_verifier_state *old,
16037                                  struct bpf_verifier_state *cur)
16038 {
16039         struct bpf_func_state *fold, *fcur;
16040         int i, fr = cur->curframe;
16041
16042         if (old->curframe != fr)
16043                 return false;
16044
16045         fold = old->frame[fr];
16046         fcur = cur->frame[fr];
16047         for (i = 0; i < MAX_BPF_REG; i++)
16048                 if (memcmp(&fold->regs[i], &fcur->regs[i],
16049                            offsetof(struct bpf_reg_state, parent)))
16050                         return false;
16051         return true;
16052 }
16053
16054 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx)
16055 {
16056         return env->insn_aux_data[insn_idx].is_iter_next;
16057 }
16058
16059 /* is_state_visited() handles iter_next() (see process_iter_next_call() for
16060  * terminology) calls specially: as opposed to bounded BPF loops, it *expects*
16061  * states to match, which otherwise would look like an infinite loop. So while
16062  * iter_next() calls are taken care of, we still need to be careful and
16063  * prevent erroneous and too eager declaration of "ininite loop", when
16064  * iterators are involved.
16065  *
16066  * Here's a situation in pseudo-BPF assembly form:
16067  *
16068  *   0: again:                          ; set up iter_next() call args
16069  *   1:   r1 = &it                      ; <CHECKPOINT HERE>
16070  *   2:   call bpf_iter_num_next        ; this is iter_next() call
16071  *   3:   if r0 == 0 goto done
16072  *   4:   ... something useful here ...
16073  *   5:   goto again                    ; another iteration
16074  *   6: done:
16075  *   7:   r1 = &it
16076  *   8:   call bpf_iter_num_destroy     ; clean up iter state
16077  *   9:   exit
16078  *
16079  * This is a typical loop. Let's assume that we have a prune point at 1:,
16080  * before we get to `call bpf_iter_num_next` (e.g., because of that `goto
16081  * again`, assuming other heuristics don't get in a way).
16082  *
16083  * When we first time come to 1:, let's say we have some state X. We proceed
16084  * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit.
16085  * Now we come back to validate that forked ACTIVE state. We proceed through
16086  * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we
16087  * are converging. But the problem is that we don't know that yet, as this
16088  * convergence has to happen at iter_next() call site only. So if nothing is
16089  * done, at 1: verifier will use bounded loop logic and declare infinite
16090  * looping (and would be *technically* correct, if not for iterator's
16091  * "eventual sticky NULL" contract, see process_iter_next_call()). But we
16092  * don't want that. So what we do in process_iter_next_call() when we go on
16093  * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's
16094  * a different iteration. So when we suspect an infinite loop, we additionally
16095  * check if any of the *ACTIVE* iterator states depths differ. If yes, we
16096  * pretend we are not looping and wait for next iter_next() call.
16097  *
16098  * This only applies to ACTIVE state. In DRAINED state we don't expect to
16099  * loop, because that would actually mean infinite loop, as DRAINED state is
16100  * "sticky", and so we'll keep returning into the same instruction with the
16101  * same state (at least in one of possible code paths).
16102  *
16103  * This approach allows to keep infinite loop heuristic even in the face of
16104  * active iterator. E.g., C snippet below is and will be detected as
16105  * inifintely looping:
16106  *
16107  *   struct bpf_iter_num it;
16108  *   int *p, x;
16109  *
16110  *   bpf_iter_num_new(&it, 0, 10);
16111  *   while ((p = bpf_iter_num_next(&t))) {
16112  *       x = p;
16113  *       while (x--) {} // <<-- infinite loop here
16114  *   }
16115  *
16116  */
16117 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur)
16118 {
16119         struct bpf_reg_state *slot, *cur_slot;
16120         struct bpf_func_state *state;
16121         int i, fr;
16122
16123         for (fr = old->curframe; fr >= 0; fr--) {
16124                 state = old->frame[fr];
16125                 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) {
16126                         if (state->stack[i].slot_type[0] != STACK_ITER)
16127                                 continue;
16128
16129                         slot = &state->stack[i].spilled_ptr;
16130                         if (slot->iter.state != BPF_ITER_STATE_ACTIVE)
16131                                 continue;
16132
16133                         cur_slot = &cur->frame[fr]->stack[i].spilled_ptr;
16134                         if (cur_slot->iter.depth != slot->iter.depth)
16135                                 return true;
16136                 }
16137         }
16138         return false;
16139 }
16140
16141 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx)
16142 {
16143         struct bpf_verifier_state_list *new_sl;
16144         struct bpf_verifier_state_list *sl, **pprev;
16145         struct bpf_verifier_state *cur = env->cur_state, *new;
16146         int i, j, err, states_cnt = 0;
16147         bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx);
16148         bool add_new_state = force_new_state;
16149
16150         /* bpf progs typically have pruning point every 4 instructions
16151          * http://vger.kernel.org/bpfconf2019.html#session-1
16152          * Do not add new state for future pruning if the verifier hasn't seen
16153          * at least 2 jumps and at least 8 instructions.
16154          * This heuristics helps decrease 'total_states' and 'peak_states' metric.
16155          * In tests that amounts to up to 50% reduction into total verifier
16156          * memory consumption and 20% verifier time speedup.
16157          */
16158         if (env->jmps_processed - env->prev_jmps_processed >= 2 &&
16159             env->insn_processed - env->prev_insn_processed >= 8)
16160                 add_new_state = true;
16161
16162         pprev = explored_state(env, insn_idx);
16163         sl = *pprev;
16164
16165         clean_live_states(env, insn_idx, cur);
16166
16167         while (sl) {
16168                 states_cnt++;
16169                 if (sl->state.insn_idx != insn_idx)
16170                         goto next;
16171
16172                 if (sl->state.branches) {
16173                         struct bpf_func_state *frame = sl->state.frame[sl->state.curframe];
16174
16175                         if (frame->in_async_callback_fn &&
16176                             frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) {
16177                                 /* Different async_entry_cnt means that the verifier is
16178                                  * processing another entry into async callback.
16179                                  * Seeing the same state is not an indication of infinite
16180                                  * loop or infinite recursion.
16181                                  * But finding the same state doesn't mean that it's safe
16182                                  * to stop processing the current state. The previous state
16183                                  * hasn't yet reached bpf_exit, since state.branches > 0.
16184                                  * Checking in_async_callback_fn alone is not enough either.
16185                                  * Since the verifier still needs to catch infinite loops
16186                                  * inside async callbacks.
16187                                  */
16188                                 goto skip_inf_loop_check;
16189                         }
16190                         /* BPF open-coded iterators loop detection is special.
16191                          * states_maybe_looping() logic is too simplistic in detecting
16192                          * states that *might* be equivalent, because it doesn't know
16193                          * about ID remapping, so don't even perform it.
16194                          * See process_iter_next_call() and iter_active_depths_differ()
16195                          * for overview of the logic. When current and one of parent
16196                          * states are detected as equivalent, it's a good thing: we prove
16197                          * convergence and can stop simulating further iterations.
16198                          * It's safe to assume that iterator loop will finish, taking into
16199                          * account iter_next() contract of eventually returning
16200                          * sticky NULL result.
16201                          */
16202                         if (is_iter_next_insn(env, insn_idx)) {
16203                                 if (states_equal(env, &sl->state, cur)) {
16204                                         struct bpf_func_state *cur_frame;
16205                                         struct bpf_reg_state *iter_state, *iter_reg;
16206                                         int spi;
16207
16208                                         cur_frame = cur->frame[cur->curframe];
16209                                         /* btf_check_iter_kfuncs() enforces that
16210                                          * iter state pointer is always the first arg
16211                                          */
16212                                         iter_reg = &cur_frame->regs[BPF_REG_1];
16213                                         /* current state is valid due to states_equal(),
16214                                          * so we can assume valid iter and reg state,
16215                                          * no need for extra (re-)validations
16216                                          */
16217                                         spi = __get_spi(iter_reg->off + iter_reg->var_off.value);
16218                                         iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr;
16219                                         if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE)
16220                                                 goto hit;
16221                                 }
16222                                 goto skip_inf_loop_check;
16223                         }
16224                         /* attempt to detect infinite loop to avoid unnecessary doomed work */
16225                         if (states_maybe_looping(&sl->state, cur) &&
16226                             states_equal(env, &sl->state, cur) &&
16227                             !iter_active_depths_differ(&sl->state, cur)) {
16228                                 verbose_linfo(env, insn_idx, "; ");
16229                                 verbose(env, "infinite loop detected at insn %d\n", insn_idx);
16230                                 return -EINVAL;
16231                         }
16232                         /* if the verifier is processing a loop, avoid adding new state
16233                          * too often, since different loop iterations have distinct
16234                          * states and may not help future pruning.
16235                          * This threshold shouldn't be too low to make sure that
16236                          * a loop with large bound will be rejected quickly.
16237                          * The most abusive loop will be:
16238                          * r1 += 1
16239                          * if r1 < 1000000 goto pc-2
16240                          * 1M insn_procssed limit / 100 == 10k peak states.
16241                          * This threshold shouldn't be too high either, since states
16242                          * at the end of the loop are likely to be useful in pruning.
16243                          */
16244 skip_inf_loop_check:
16245                         if (!force_new_state &&
16246                             env->jmps_processed - env->prev_jmps_processed < 20 &&
16247                             env->insn_processed - env->prev_insn_processed < 100)
16248                                 add_new_state = false;
16249                         goto miss;
16250                 }
16251                 if (states_equal(env, &sl->state, cur)) {
16252 hit:
16253                         sl->hit_cnt++;
16254                         /* reached equivalent register/stack state,
16255                          * prune the search.
16256                          * Registers read by the continuation are read by us.
16257                          * If we have any write marks in env->cur_state, they
16258                          * will prevent corresponding reads in the continuation
16259                          * from reaching our parent (an explored_state).  Our
16260                          * own state will get the read marks recorded, but
16261                          * they'll be immediately forgotten as we're pruning
16262                          * this state and will pop a new one.
16263                          */
16264                         err = propagate_liveness(env, &sl->state, cur);
16265
16266                         /* if previous state reached the exit with precision and
16267                          * current state is equivalent to it (except precsion marks)
16268                          * the precision needs to be propagated back in
16269                          * the current state.
16270                          */
16271                         err = err ? : push_jmp_history(env, cur);
16272                         err = err ? : propagate_precision(env, &sl->state);
16273                         if (err)
16274                                 return err;
16275                         return 1;
16276                 }
16277 miss:
16278                 /* when new state is not going to be added do not increase miss count.
16279                  * Otherwise several loop iterations will remove the state
16280                  * recorded earlier. The goal of these heuristics is to have
16281                  * states from some iterations of the loop (some in the beginning
16282                  * and some at the end) to help pruning.
16283                  */
16284                 if (add_new_state)
16285                         sl->miss_cnt++;
16286                 /* heuristic to determine whether this state is beneficial
16287                  * to keep checking from state equivalence point of view.
16288                  * Higher numbers increase max_states_per_insn and verification time,
16289                  * but do not meaningfully decrease insn_processed.
16290                  */
16291                 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) {
16292                         /* the state is unlikely to be useful. Remove it to
16293                          * speed up verification
16294                          */
16295                         *pprev = sl->next;
16296                         if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) {
16297                                 u32 br = sl->state.branches;
16298
16299                                 WARN_ONCE(br,
16300                                           "BUG live_done but branches_to_explore %d\n",
16301                                           br);
16302                                 free_verifier_state(&sl->state, false);
16303                                 kfree(sl);
16304                                 env->peak_states--;
16305                         } else {
16306                                 /* cannot free this state, since parentage chain may
16307                                  * walk it later. Add it for free_list instead to
16308                                  * be freed at the end of verification
16309                                  */
16310                                 sl->next = env->free_list;
16311                                 env->free_list = sl;
16312                         }
16313                         sl = *pprev;
16314                         continue;
16315                 }
16316 next:
16317                 pprev = &sl->next;
16318                 sl = *pprev;
16319         }
16320
16321         if (env->max_states_per_insn < states_cnt)
16322                 env->max_states_per_insn = states_cnt;
16323
16324         if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES)
16325                 return 0;
16326
16327         if (!add_new_state)
16328                 return 0;
16329
16330         /* There were no equivalent states, remember the current one.
16331          * Technically the current state is not proven to be safe yet,
16332          * but it will either reach outer most bpf_exit (which means it's safe)
16333          * or it will be rejected. When there are no loops the verifier won't be
16334          * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx)
16335          * again on the way to bpf_exit.
16336          * When looping the sl->state.branches will be > 0 and this state
16337          * will not be considered for equivalence until branches == 0.
16338          */
16339         new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL);
16340         if (!new_sl)
16341                 return -ENOMEM;
16342         env->total_states++;
16343         env->peak_states++;
16344         env->prev_jmps_processed = env->jmps_processed;
16345         env->prev_insn_processed = env->insn_processed;
16346
16347         /* forget precise markings we inherited, see __mark_chain_precision */
16348         if (env->bpf_capable)
16349                 mark_all_scalars_imprecise(env, cur);
16350
16351         /* add new state to the head of linked list */
16352         new = &new_sl->state;
16353         err = copy_verifier_state(new, cur);
16354         if (err) {
16355                 free_verifier_state(new, false);
16356                 kfree(new_sl);
16357                 return err;
16358         }
16359         new->insn_idx = insn_idx;
16360         WARN_ONCE(new->branches != 1,
16361                   "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx);
16362
16363         cur->parent = new;
16364         cur->first_insn_idx = insn_idx;
16365         clear_jmp_history(cur);
16366         new_sl->next = *explored_state(env, insn_idx);
16367         *explored_state(env, insn_idx) = new_sl;
16368         /* connect new state to parentage chain. Current frame needs all
16369          * registers connected. Only r6 - r9 of the callers are alive (pushed
16370          * to the stack implicitly by JITs) so in callers' frames connect just
16371          * r6 - r9 as an optimization. Callers will have r1 - r5 connected to
16372          * the state of the call instruction (with WRITTEN set), and r0 comes
16373          * from callee with its full parentage chain, anyway.
16374          */
16375         /* clear write marks in current state: the writes we did are not writes
16376          * our child did, so they don't screen off its reads from us.
16377          * (There are no read marks in current state, because reads always mark
16378          * their parent and current state never has children yet.  Only
16379          * explored_states can get read marks.)
16380          */
16381         for (j = 0; j <= cur->curframe; j++) {
16382                 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++)
16383                         cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i];
16384                 for (i = 0; i < BPF_REG_FP; i++)
16385                         cur->frame[j]->regs[i].live = REG_LIVE_NONE;
16386         }
16387
16388         /* all stack frames are accessible from callee, clear them all */
16389         for (j = 0; j <= cur->curframe; j++) {
16390                 struct bpf_func_state *frame = cur->frame[j];
16391                 struct bpf_func_state *newframe = new->frame[j];
16392
16393                 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) {
16394                         frame->stack[i].spilled_ptr.live = REG_LIVE_NONE;
16395                         frame->stack[i].spilled_ptr.parent =
16396                                                 &newframe->stack[i].spilled_ptr;
16397                 }
16398         }
16399         return 0;
16400 }
16401
16402 /* Return true if it's OK to have the same insn return a different type. */
16403 static bool reg_type_mismatch_ok(enum bpf_reg_type type)
16404 {
16405         switch (base_type(type)) {
16406         case PTR_TO_CTX:
16407         case PTR_TO_SOCKET:
16408         case PTR_TO_SOCK_COMMON:
16409         case PTR_TO_TCP_SOCK:
16410         case PTR_TO_XDP_SOCK:
16411         case PTR_TO_BTF_ID:
16412                 return false;
16413         default:
16414                 return true;
16415         }
16416 }
16417
16418 /* If an instruction was previously used with particular pointer types, then we
16419  * need to be careful to avoid cases such as the below, where it may be ok
16420  * for one branch accessing the pointer, but not ok for the other branch:
16421  *
16422  * R1 = sock_ptr
16423  * goto X;
16424  * ...
16425  * R1 = some_other_valid_ptr;
16426  * goto X;
16427  * ...
16428  * R2 = *(u32 *)(R1 + 0);
16429  */
16430 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev)
16431 {
16432         return src != prev && (!reg_type_mismatch_ok(src) ||
16433                                !reg_type_mismatch_ok(prev));
16434 }
16435
16436 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type,
16437                              bool allow_trust_missmatch)
16438 {
16439         enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type;
16440
16441         if (*prev_type == NOT_INIT) {
16442                 /* Saw a valid insn
16443                  * dst_reg = *(u32 *)(src_reg + off)
16444                  * save type to validate intersecting paths
16445                  */
16446                 *prev_type = type;
16447         } else if (reg_type_mismatch(type, *prev_type)) {
16448                 /* Abuser program is trying to use the same insn
16449                  * dst_reg = *(u32*) (src_reg + off)
16450                  * with different pointer types:
16451                  * src_reg == ctx in one branch and
16452                  * src_reg == stack|map in some other branch.
16453                  * Reject it.
16454                  */
16455                 if (allow_trust_missmatch &&
16456                     base_type(type) == PTR_TO_BTF_ID &&
16457                     base_type(*prev_type) == PTR_TO_BTF_ID) {
16458                         /*
16459                          * Have to support a use case when one path through
16460                          * the program yields TRUSTED pointer while another
16461                          * is UNTRUSTED. Fallback to UNTRUSTED to generate
16462                          * BPF_PROBE_MEM/BPF_PROBE_MEMSX.
16463                          */
16464                         *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED;
16465                 } else {
16466                         verbose(env, "same insn cannot be used with different pointers\n");
16467                         return -EINVAL;
16468                 }
16469         }
16470
16471         return 0;
16472 }
16473
16474 static int do_check(struct bpf_verifier_env *env)
16475 {
16476         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
16477         struct bpf_verifier_state *state = env->cur_state;
16478         struct bpf_insn *insns = env->prog->insnsi;
16479         struct bpf_reg_state *regs;
16480         int insn_cnt = env->prog->len;
16481         bool do_print_state = false;
16482         int prev_insn_idx = -1;
16483
16484         for (;;) {
16485                 struct bpf_insn *insn;
16486                 u8 class;
16487                 int err;
16488
16489                 env->prev_insn_idx = prev_insn_idx;
16490                 if (env->insn_idx >= insn_cnt) {
16491                         verbose(env, "invalid insn idx %d insn_cnt %d\n",
16492                                 env->insn_idx, insn_cnt);
16493                         return -EFAULT;
16494                 }
16495
16496                 insn = &insns[env->insn_idx];
16497                 class = BPF_CLASS(insn->code);
16498
16499                 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
16500                         verbose(env,
16501                                 "BPF program is too large. Processed %d insn\n",
16502                                 env->insn_processed);
16503                         return -E2BIG;
16504                 }
16505
16506                 state->last_insn_idx = env->prev_insn_idx;
16507
16508                 if (is_prune_point(env, env->insn_idx)) {
16509                         err = is_state_visited(env, env->insn_idx);
16510                         if (err < 0)
16511                                 return err;
16512                         if (err == 1) {
16513                                 /* found equivalent state, can prune the search */
16514                                 if (env->log.level & BPF_LOG_LEVEL) {
16515                                         if (do_print_state)
16516                                                 verbose(env, "\nfrom %d to %d%s: safe\n",
16517                                                         env->prev_insn_idx, env->insn_idx,
16518                                                         env->cur_state->speculative ?
16519                                                         " (speculative execution)" : "");
16520                                         else
16521                                                 verbose(env, "%d: safe\n", env->insn_idx);
16522                                 }
16523                                 goto process_bpf_exit;
16524                         }
16525                 }
16526
16527                 if (is_jmp_point(env, env->insn_idx)) {
16528                         err = push_jmp_history(env, state);
16529                         if (err)
16530                                 return err;
16531                 }
16532
16533                 if (signal_pending(current))
16534                         return -EAGAIN;
16535
16536                 if (need_resched())
16537                         cond_resched();
16538
16539                 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
16540                         verbose(env, "\nfrom %d to %d%s:",
16541                                 env->prev_insn_idx, env->insn_idx,
16542                                 env->cur_state->speculative ?
16543                                 " (speculative execution)" : "");
16544                         print_verifier_state(env, state->frame[state->curframe], true);
16545                         do_print_state = false;
16546                 }
16547
16548                 if (env->log.level & BPF_LOG_LEVEL) {
16549                         const struct bpf_insn_cbs cbs = {
16550                                 .cb_call        = disasm_kfunc_name,
16551                                 .cb_print       = verbose,
16552                                 .private_data   = env,
16553                         };
16554
16555                         if (verifier_state_scratched(env))
16556                                 print_insn_state(env, state->frame[state->curframe]);
16557
16558                         verbose_linfo(env, env->insn_idx, "; ");
16559                         env->prev_log_pos = env->log.end_pos;
16560                         verbose(env, "%d: ", env->insn_idx);
16561                         print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
16562                         env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
16563                         env->prev_log_pos = env->log.end_pos;
16564                 }
16565
16566                 if (bpf_prog_is_offloaded(env->prog->aux)) {
16567                         err = bpf_prog_offload_verify_insn(env, env->insn_idx,
16568                                                            env->prev_insn_idx);
16569                         if (err)
16570                                 return err;
16571                 }
16572
16573                 regs = cur_regs(env);
16574                 sanitize_mark_insn_seen(env);
16575                 prev_insn_idx = env->insn_idx;
16576
16577                 if (class == BPF_ALU || class == BPF_ALU64) {
16578                         err = check_alu_op(env, insn);
16579                         if (err)
16580                                 return err;
16581
16582                 } else if (class == BPF_LDX) {
16583                         enum bpf_reg_type src_reg_type;
16584
16585                         /* check for reserved fields is already done */
16586
16587                         /* check src operand */
16588                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16589                         if (err)
16590                                 return err;
16591
16592                         err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
16593                         if (err)
16594                                 return err;
16595
16596                         src_reg_type = regs[insn->src_reg].type;
16597
16598                         /* check that memory (src_reg + off) is readable,
16599                          * the state of dst_reg will be updated by this func
16600                          */
16601                         err = check_mem_access(env, env->insn_idx, insn->src_reg,
16602                                                insn->off, BPF_SIZE(insn->code),
16603                                                BPF_READ, insn->dst_reg, false,
16604                                                BPF_MODE(insn->code) == BPF_MEMSX);
16605                         if (err)
16606                                 return err;
16607
16608                         err = save_aux_ptr_type(env, src_reg_type, true);
16609                         if (err)
16610                                 return err;
16611                 } else if (class == BPF_STX) {
16612                         enum bpf_reg_type dst_reg_type;
16613
16614                         if (BPF_MODE(insn->code) == BPF_ATOMIC) {
16615                                 err = check_atomic(env, env->insn_idx, insn);
16616                                 if (err)
16617                                         return err;
16618                                 env->insn_idx++;
16619                                 continue;
16620                         }
16621
16622                         if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) {
16623                                 verbose(env, "BPF_STX uses reserved fields\n");
16624                                 return -EINVAL;
16625                         }
16626
16627                         /* check src1 operand */
16628                         err = check_reg_arg(env, insn->src_reg, SRC_OP);
16629                         if (err)
16630                                 return err;
16631                         /* check src2 operand */
16632                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16633                         if (err)
16634                                 return err;
16635
16636                         dst_reg_type = regs[insn->dst_reg].type;
16637
16638                         /* check that memory (dst_reg + off) is writeable */
16639                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16640                                                insn->off, BPF_SIZE(insn->code),
16641                                                BPF_WRITE, insn->src_reg, false, false);
16642                         if (err)
16643                                 return err;
16644
16645                         err = save_aux_ptr_type(env, dst_reg_type, false);
16646                         if (err)
16647                                 return err;
16648                 } else if (class == BPF_ST) {
16649                         enum bpf_reg_type dst_reg_type;
16650
16651                         if (BPF_MODE(insn->code) != BPF_MEM ||
16652                             insn->src_reg != BPF_REG_0) {
16653                                 verbose(env, "BPF_ST uses reserved fields\n");
16654                                 return -EINVAL;
16655                         }
16656                         /* check src operand */
16657                         err = check_reg_arg(env, insn->dst_reg, SRC_OP);
16658                         if (err)
16659                                 return err;
16660
16661                         dst_reg_type = regs[insn->dst_reg].type;
16662
16663                         /* check that memory (dst_reg + off) is writeable */
16664                         err = check_mem_access(env, env->insn_idx, insn->dst_reg,
16665                                                insn->off, BPF_SIZE(insn->code),
16666                                                BPF_WRITE, -1, false, false);
16667                         if (err)
16668                                 return err;
16669
16670                         err = save_aux_ptr_type(env, dst_reg_type, false);
16671                         if (err)
16672                                 return err;
16673                 } else if (class == BPF_JMP || class == BPF_JMP32) {
16674                         u8 opcode = BPF_OP(insn->code);
16675
16676                         env->jmps_processed++;
16677                         if (opcode == BPF_CALL) {
16678                                 if (BPF_SRC(insn->code) != BPF_K ||
16679                                     (insn->src_reg != BPF_PSEUDO_KFUNC_CALL
16680                                      && insn->off != 0) ||
16681                                     (insn->src_reg != BPF_REG_0 &&
16682                                      insn->src_reg != BPF_PSEUDO_CALL &&
16683                                      insn->src_reg != BPF_PSEUDO_KFUNC_CALL) ||
16684                                     insn->dst_reg != BPF_REG_0 ||
16685                                     class == BPF_JMP32) {
16686                                         verbose(env, "BPF_CALL uses reserved fields\n");
16687                                         return -EINVAL;
16688                                 }
16689
16690                                 if (env->cur_state->active_lock.ptr) {
16691                                         if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) ||
16692                                             (insn->src_reg == BPF_PSEUDO_CALL) ||
16693                                             (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
16694                                              (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) {
16695                                                 verbose(env, "function calls are not allowed while holding a lock\n");
16696                                                 return -EINVAL;
16697                                         }
16698                                 }
16699                                 if (insn->src_reg == BPF_PSEUDO_CALL)
16700                                         err = check_func_call(env, insn, &env->insn_idx);
16701                                 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL)
16702                                         err = check_kfunc_call(env, insn, &env->insn_idx);
16703                                 else
16704                                         err = check_helper_call(env, insn, &env->insn_idx);
16705                                 if (err)
16706                                         return err;
16707
16708                                 mark_reg_scratched(env, BPF_REG_0);
16709                         } else if (opcode == BPF_JA) {
16710                                 if (BPF_SRC(insn->code) != BPF_K ||
16711                                     insn->src_reg != BPF_REG_0 ||
16712                                     insn->dst_reg != BPF_REG_0 ||
16713                                     (class == BPF_JMP && insn->imm != 0) ||
16714                                     (class == BPF_JMP32 && insn->off != 0)) {
16715                                         verbose(env, "BPF_JA uses reserved fields\n");
16716                                         return -EINVAL;
16717                                 }
16718
16719                                 if (class == BPF_JMP)
16720                                         env->insn_idx += insn->off + 1;
16721                                 else
16722                                         env->insn_idx += insn->imm + 1;
16723                                 continue;
16724
16725                         } else if (opcode == BPF_EXIT) {
16726                                 if (BPF_SRC(insn->code) != BPF_K ||
16727                                     insn->imm != 0 ||
16728                                     insn->src_reg != BPF_REG_0 ||
16729                                     insn->dst_reg != BPF_REG_0 ||
16730                                     class == BPF_JMP32) {
16731                                         verbose(env, "BPF_EXIT uses reserved fields\n");
16732                                         return -EINVAL;
16733                                 }
16734
16735                                 if (env->cur_state->active_lock.ptr &&
16736                                     !in_rbtree_lock_required_cb(env)) {
16737                                         verbose(env, "bpf_spin_unlock is missing\n");
16738                                         return -EINVAL;
16739                                 }
16740
16741                                 if (env->cur_state->active_rcu_lock &&
16742                                     !in_rbtree_lock_required_cb(env)) {
16743                                         verbose(env, "bpf_rcu_read_unlock is missing\n");
16744                                         return -EINVAL;
16745                                 }
16746
16747                                 /* We must do check_reference_leak here before
16748                                  * prepare_func_exit to handle the case when
16749                                  * state->curframe > 0, it may be a callback
16750                                  * function, for which reference_state must
16751                                  * match caller reference state when it exits.
16752                                  */
16753                                 err = check_reference_leak(env);
16754                                 if (err)
16755                                         return err;
16756
16757                                 if (state->curframe) {
16758                                         /* exit from nested function */
16759                                         err = prepare_func_exit(env, &env->insn_idx);
16760                                         if (err)
16761                                                 return err;
16762                                         do_print_state = true;
16763                                         continue;
16764                                 }
16765
16766                                 err = check_return_code(env);
16767                                 if (err)
16768                                         return err;
16769 process_bpf_exit:
16770                                 mark_verifier_state_scratched(env);
16771                                 update_branch_counts(env, env->cur_state);
16772                                 err = pop_stack(env, &prev_insn_idx,
16773                                                 &env->insn_idx, pop_log);
16774                                 if (err < 0) {
16775                                         if (err != -ENOENT)
16776                                                 return err;
16777                                         break;
16778                                 } else {
16779                                         do_print_state = true;
16780                                         continue;
16781                                 }
16782                         } else {
16783                                 err = check_cond_jmp_op(env, insn, &env->insn_idx);
16784                                 if (err)
16785                                         return err;
16786                         }
16787                 } else if (class == BPF_LD) {
16788                         u8 mode = BPF_MODE(insn->code);
16789
16790                         if (mode == BPF_ABS || mode == BPF_IND) {
16791                                 err = check_ld_abs(env, insn);
16792                                 if (err)
16793                                         return err;
16794
16795                         } else if (mode == BPF_IMM) {
16796                                 err = check_ld_imm(env, insn);
16797                                 if (err)
16798                                         return err;
16799
16800                                 env->insn_idx++;
16801                                 sanitize_mark_insn_seen(env);
16802                         } else {
16803                                 verbose(env, "invalid BPF_LD mode\n");
16804                                 return -EINVAL;
16805                         }
16806                 } else {
16807                         verbose(env, "unknown insn class %d\n", class);
16808                         return -EINVAL;
16809                 }
16810
16811                 env->insn_idx++;
16812         }
16813
16814         return 0;
16815 }
16816
16817 static int find_btf_percpu_datasec(struct btf *btf)
16818 {
16819         const struct btf_type *t;
16820         const char *tname;
16821         int i, n;
16822
16823         /*
16824          * Both vmlinux and module each have their own ".data..percpu"
16825          * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF
16826          * types to look at only module's own BTF types.
16827          */
16828         n = btf_nr_types(btf);
16829         if (btf_is_module(btf))
16830                 i = btf_nr_types(btf_vmlinux);
16831         else
16832                 i = 1;
16833
16834         for(; i < n; i++) {
16835                 t = btf_type_by_id(btf, i);
16836                 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
16837                         continue;
16838
16839                 tname = btf_name_by_offset(btf, t->name_off);
16840                 if (!strcmp(tname, ".data..percpu"))
16841                         return i;
16842         }
16843
16844         return -ENOENT;
16845 }
16846
16847 /* replace pseudo btf_id with kernel symbol address */
16848 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
16849                                struct bpf_insn *insn,
16850                                struct bpf_insn_aux_data *aux)
16851 {
16852         const struct btf_var_secinfo *vsi;
16853         const struct btf_type *datasec;
16854         struct btf_mod_pair *btf_mod;
16855         const struct btf_type *t;
16856         const char *sym_name;
16857         bool percpu = false;
16858         u32 type, id = insn->imm;
16859         struct btf *btf;
16860         s32 datasec_id;
16861         u64 addr;
16862         int i, btf_fd, err;
16863
16864         btf_fd = insn[1].imm;
16865         if (btf_fd) {
16866                 btf = btf_get_by_fd(btf_fd);
16867                 if (IS_ERR(btf)) {
16868                         verbose(env, "invalid module BTF object FD specified.\n");
16869                         return -EINVAL;
16870                 }
16871         } else {
16872                 if (!btf_vmlinux) {
16873                         verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
16874                         return -EINVAL;
16875                 }
16876                 btf = btf_vmlinux;
16877                 btf_get(btf);
16878         }
16879
16880         t = btf_type_by_id(btf, id);
16881         if (!t) {
16882                 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
16883                 err = -ENOENT;
16884                 goto err_put;
16885         }
16886
16887         if (!btf_type_is_var(t) && !btf_type_is_func(t)) {
16888                 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id);
16889                 err = -EINVAL;
16890                 goto err_put;
16891         }
16892
16893         sym_name = btf_name_by_offset(btf, t->name_off);
16894         addr = kallsyms_lookup_name(sym_name);
16895         if (!addr) {
16896                 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
16897                         sym_name);
16898                 err = -ENOENT;
16899                 goto err_put;
16900         }
16901         insn[0].imm = (u32)addr;
16902         insn[1].imm = addr >> 32;
16903
16904         if (btf_type_is_func(t)) {
16905                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16906                 aux->btf_var.mem_size = 0;
16907                 goto check_btf;
16908         }
16909
16910         datasec_id = find_btf_percpu_datasec(btf);
16911         if (datasec_id > 0) {
16912                 datasec = btf_type_by_id(btf, datasec_id);
16913                 for_each_vsi(i, datasec, vsi) {
16914                         if (vsi->type == id) {
16915                                 percpu = true;
16916                                 break;
16917                         }
16918                 }
16919         }
16920
16921         type = t->type;
16922         t = btf_type_skip_modifiers(btf, type, NULL);
16923         if (percpu) {
16924                 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU;
16925                 aux->btf_var.btf = btf;
16926                 aux->btf_var.btf_id = type;
16927         } else if (!btf_type_is_struct(t)) {
16928                 const struct btf_type *ret;
16929                 const char *tname;
16930                 u32 tsize;
16931
16932                 /* resolve the type size of ksym. */
16933                 ret = btf_resolve_size(btf, t, &tsize);
16934                 if (IS_ERR(ret)) {
16935                         tname = btf_name_by_offset(btf, t->name_off);
16936                         verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
16937                                 tname, PTR_ERR(ret));
16938                         err = -EINVAL;
16939                         goto err_put;
16940                 }
16941                 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY;
16942                 aux->btf_var.mem_size = tsize;
16943         } else {
16944                 aux->btf_var.reg_type = PTR_TO_BTF_ID;
16945                 aux->btf_var.btf = btf;
16946                 aux->btf_var.btf_id = type;
16947         }
16948 check_btf:
16949         /* check whether we recorded this BTF (and maybe module) already */
16950         for (i = 0; i < env->used_btf_cnt; i++) {
16951                 if (env->used_btfs[i].btf == btf) {
16952                         btf_put(btf);
16953                         return 0;
16954                 }
16955         }
16956
16957         if (env->used_btf_cnt >= MAX_USED_BTFS) {
16958                 err = -E2BIG;
16959                 goto err_put;
16960         }
16961
16962         btf_mod = &env->used_btfs[env->used_btf_cnt];
16963         btf_mod->btf = btf;
16964         btf_mod->module = NULL;
16965
16966         /* if we reference variables from kernel module, bump its refcount */
16967         if (btf_is_module(btf)) {
16968                 btf_mod->module = btf_try_get_module(btf);
16969                 if (!btf_mod->module) {
16970                         err = -ENXIO;
16971                         goto err_put;
16972                 }
16973         }
16974
16975         env->used_btf_cnt++;
16976
16977         return 0;
16978 err_put:
16979         btf_put(btf);
16980         return err;
16981 }
16982
16983 static bool is_tracing_prog_type(enum bpf_prog_type type)
16984 {
16985         switch (type) {
16986         case BPF_PROG_TYPE_KPROBE:
16987         case BPF_PROG_TYPE_TRACEPOINT:
16988         case BPF_PROG_TYPE_PERF_EVENT:
16989         case BPF_PROG_TYPE_RAW_TRACEPOINT:
16990         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
16991                 return true;
16992         default:
16993                 return false;
16994         }
16995 }
16996
16997 static int check_map_prog_compatibility(struct bpf_verifier_env *env,
16998                                         struct bpf_map *map,
16999                                         struct bpf_prog *prog)
17000
17001 {
17002         enum bpf_prog_type prog_type = resolve_prog_type(prog);
17003
17004         if (btf_record_has_field(map->record, BPF_LIST_HEAD) ||
17005             btf_record_has_field(map->record, BPF_RB_ROOT)) {
17006                 if (is_tracing_prog_type(prog_type)) {
17007                         verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n");
17008                         return -EINVAL;
17009                 }
17010         }
17011
17012         if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
17013                 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) {
17014                         verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n");
17015                         return -EINVAL;
17016                 }
17017
17018                 if (is_tracing_prog_type(prog_type)) {
17019                         verbose(env, "tracing progs cannot use bpf_spin_lock yet\n");
17020                         return -EINVAL;
17021                 }
17022         }
17023
17024         if (btf_record_has_field(map->record, BPF_TIMER)) {
17025                 if (is_tracing_prog_type(prog_type)) {
17026                         verbose(env, "tracing progs cannot use bpf_timer yet\n");
17027                         return -EINVAL;
17028                 }
17029         }
17030
17031         if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) &&
17032             !bpf_offload_prog_map_match(prog, map)) {
17033                 verbose(env, "offload device mismatch between prog and map\n");
17034                 return -EINVAL;
17035         }
17036
17037         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
17038                 verbose(env, "bpf_struct_ops map cannot be used in prog\n");
17039                 return -EINVAL;
17040         }
17041
17042         if (prog->aux->sleepable)
17043                 switch (map->map_type) {
17044                 case BPF_MAP_TYPE_HASH:
17045                 case BPF_MAP_TYPE_LRU_HASH:
17046                 case BPF_MAP_TYPE_ARRAY:
17047                 case BPF_MAP_TYPE_PERCPU_HASH:
17048                 case BPF_MAP_TYPE_PERCPU_ARRAY:
17049                 case BPF_MAP_TYPE_LRU_PERCPU_HASH:
17050                 case BPF_MAP_TYPE_ARRAY_OF_MAPS:
17051                 case BPF_MAP_TYPE_HASH_OF_MAPS:
17052                 case BPF_MAP_TYPE_RINGBUF:
17053                 case BPF_MAP_TYPE_USER_RINGBUF:
17054                 case BPF_MAP_TYPE_INODE_STORAGE:
17055                 case BPF_MAP_TYPE_SK_STORAGE:
17056                 case BPF_MAP_TYPE_TASK_STORAGE:
17057                 case BPF_MAP_TYPE_CGRP_STORAGE:
17058                         break;
17059                 default:
17060                         verbose(env,
17061                                 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n");
17062                         return -EINVAL;
17063                 }
17064
17065         return 0;
17066 }
17067
17068 static bool bpf_map_is_cgroup_storage(struct bpf_map *map)
17069 {
17070         return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE ||
17071                 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE);
17072 }
17073
17074 /* find and rewrite pseudo imm in ld_imm64 instructions:
17075  *
17076  * 1. if it accesses map FD, replace it with actual map pointer.
17077  * 2. if it accesses btf_id of a VAR, replace it with pointer to the var.
17078  *
17079  * NOTE: btf_vmlinux is required for converting pseudo btf_id.
17080  */
17081 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env)
17082 {
17083         struct bpf_insn *insn = env->prog->insnsi;
17084         int insn_cnt = env->prog->len;
17085         int i, j, err;
17086
17087         err = bpf_prog_calc_tag(env->prog);
17088         if (err)
17089                 return err;
17090
17091         for (i = 0; i < insn_cnt; i++, insn++) {
17092                 if (BPF_CLASS(insn->code) == BPF_LDX &&
17093                     ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) ||
17094                     insn->imm != 0)) {
17095                         verbose(env, "BPF_LDX uses reserved fields\n");
17096                         return -EINVAL;
17097                 }
17098
17099                 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
17100                         struct bpf_insn_aux_data *aux;
17101                         struct bpf_map *map;
17102                         struct fd f;
17103                         u64 addr;
17104                         u32 fd;
17105
17106                         if (i == insn_cnt - 1 || insn[1].code != 0 ||
17107                             insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||
17108                             insn[1].off != 0) {
17109                                 verbose(env, "invalid bpf_ld_imm64 insn\n");
17110                                 return -EINVAL;
17111                         }
17112
17113                         if (insn[0].src_reg == 0)
17114                                 /* valid generic load 64-bit imm */
17115                                 goto next_insn;
17116
17117                         if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) {
17118                                 aux = &env->insn_aux_data[i];
17119                                 err = check_pseudo_btf_id(env, insn, aux);
17120                                 if (err)
17121                                         return err;
17122                                 goto next_insn;
17123                         }
17124
17125                         if (insn[0].src_reg == BPF_PSEUDO_FUNC) {
17126                                 aux = &env->insn_aux_data[i];
17127                                 aux->ptr_type = PTR_TO_FUNC;
17128                                 goto next_insn;
17129                         }
17130
17131                         /* In final convert_pseudo_ld_imm64() step, this is
17132                          * converted into regular 64-bit imm load insn.
17133                          */
17134                         switch (insn[0].src_reg) {
17135                         case BPF_PSEUDO_MAP_VALUE:
17136                         case BPF_PSEUDO_MAP_IDX_VALUE:
17137                                 break;
17138                         case BPF_PSEUDO_MAP_FD:
17139                         case BPF_PSEUDO_MAP_IDX:
17140                                 if (insn[1].imm == 0)
17141                                         break;
17142                                 fallthrough;
17143                         default:
17144                                 verbose(env, "unrecognized bpf_ld_imm64 insn\n");
17145                                 return -EINVAL;
17146                         }
17147
17148                         switch (insn[0].src_reg) {
17149                         case BPF_PSEUDO_MAP_IDX_VALUE:
17150                         case BPF_PSEUDO_MAP_IDX:
17151                                 if (bpfptr_is_null(env->fd_array)) {
17152                                         verbose(env, "fd_idx without fd_array is invalid\n");
17153                                         return -EPROTO;
17154                                 }
17155                                 if (copy_from_bpfptr_offset(&fd, env->fd_array,
17156                                                             insn[0].imm * sizeof(fd),
17157                                                             sizeof(fd)))
17158                                         return -EFAULT;
17159                                 break;
17160                         default:
17161                                 fd = insn[0].imm;
17162                                 break;
17163                         }
17164
17165                         f = fdget(fd);
17166                         map = __bpf_map_get(f);
17167                         if (IS_ERR(map)) {
17168                                 verbose(env, "fd %d is not pointing to valid bpf_map\n",
17169                                         insn[0].imm);
17170                                 return PTR_ERR(map);
17171                         }
17172
17173                         err = check_map_prog_compatibility(env, map, env->prog);
17174                         if (err) {
17175                                 fdput(f);
17176                                 return err;
17177                         }
17178
17179                         aux = &env->insn_aux_data[i];
17180                         if (insn[0].src_reg == BPF_PSEUDO_MAP_FD ||
17181                             insn[0].src_reg == BPF_PSEUDO_MAP_IDX) {
17182                                 addr = (unsigned long)map;
17183                         } else {
17184                                 u32 off = insn[1].imm;
17185
17186                                 if (off >= BPF_MAX_VAR_OFF) {
17187                                         verbose(env, "direct value offset of %u is not allowed\n", off);
17188                                         fdput(f);
17189                                         return -EINVAL;
17190                                 }
17191
17192                                 if (!map->ops->map_direct_value_addr) {
17193                                         verbose(env, "no direct value access support for this map type\n");
17194                                         fdput(f);
17195                                         return -EINVAL;
17196                                 }
17197
17198                                 err = map->ops->map_direct_value_addr(map, &addr, off);
17199                                 if (err) {
17200                                         verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n",
17201                                                 map->value_size, off);
17202                                         fdput(f);
17203                                         return err;
17204                                 }
17205
17206                                 aux->map_off = off;
17207                                 addr += off;
17208                         }
17209
17210                         insn[0].imm = (u32)addr;
17211                         insn[1].imm = addr >> 32;
17212
17213                         /* check whether we recorded this map already */
17214                         for (j = 0; j < env->used_map_cnt; j++) {
17215                                 if (env->used_maps[j] == map) {
17216                                         aux->map_index = j;
17217                                         fdput(f);
17218                                         goto next_insn;
17219                                 }
17220                         }
17221
17222                         if (env->used_map_cnt >= MAX_USED_MAPS) {
17223                                 fdput(f);
17224                                 return -E2BIG;
17225                         }
17226
17227                         /* hold the map. If the program is rejected by verifier,
17228                          * the map will be released by release_maps() or it
17229                          * will be used by the valid program until it's unloaded
17230                          * and all maps are released in free_used_maps()
17231                          */
17232                         bpf_map_inc(map);
17233
17234                         aux->map_index = env->used_map_cnt;
17235                         env->used_maps[env->used_map_cnt++] = map;
17236
17237                         if (bpf_map_is_cgroup_storage(map) &&
17238                             bpf_cgroup_storage_assign(env->prog->aux, map)) {
17239                                 verbose(env, "only one cgroup storage of each type is allowed\n");
17240                                 fdput(f);
17241                                 return -EBUSY;
17242                         }
17243
17244                         fdput(f);
17245 next_insn:
17246                         insn++;
17247                         i++;
17248                         continue;
17249                 }
17250
17251                 /* Basic sanity check before we invest more work here. */
17252                 if (!bpf_opcode_in_insntable(insn->code)) {
17253                         verbose(env, "unknown opcode %02x\n", insn->code);
17254                         return -EINVAL;
17255                 }
17256         }
17257
17258         /* now all pseudo BPF_LD_IMM64 instructions load valid
17259          * 'struct bpf_map *' into a register instead of user map_fd.
17260          * These pointers will be used later by verifier to validate map access.
17261          */
17262         return 0;
17263 }
17264
17265 /* drop refcnt of maps used by the rejected program */
17266 static void release_maps(struct bpf_verifier_env *env)
17267 {
17268         __bpf_free_used_maps(env->prog->aux, env->used_maps,
17269                              env->used_map_cnt);
17270 }
17271
17272 /* drop refcnt of maps used by the rejected program */
17273 static void release_btfs(struct bpf_verifier_env *env)
17274 {
17275         __bpf_free_used_btfs(env->prog->aux, env->used_btfs,
17276                              env->used_btf_cnt);
17277 }
17278
17279 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
17280 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
17281 {
17282         struct bpf_insn *insn = env->prog->insnsi;
17283         int insn_cnt = env->prog->len;
17284         int i;
17285
17286         for (i = 0; i < insn_cnt; i++, insn++) {
17287                 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW))
17288                         continue;
17289                 if (insn->src_reg == BPF_PSEUDO_FUNC)
17290                         continue;
17291                 insn->src_reg = 0;
17292         }
17293 }
17294
17295 /* single env->prog->insni[off] instruction was replaced with the range
17296  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
17297  * [0, off) and [off, end) to new locations, so the patched range stays zero
17298  */
17299 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
17300                                  struct bpf_insn_aux_data *new_data,
17301                                  struct bpf_prog *new_prog, u32 off, u32 cnt)
17302 {
17303         struct bpf_insn_aux_data *old_data = env->insn_aux_data;
17304         struct bpf_insn *insn = new_prog->insnsi;
17305         u32 old_seen = old_data[off].seen;
17306         u32 prog_len;
17307         int i;
17308
17309         /* aux info at OFF always needs adjustment, no matter fast path
17310          * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
17311          * original insn at old prog.
17312          */
17313         old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1);
17314
17315         if (cnt == 1)
17316                 return;
17317         prog_len = new_prog->len;
17318
17319         memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off);
17320         memcpy(new_data + off + cnt - 1, old_data + off,
17321                sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
17322         for (i = off; i < off + cnt - 1; i++) {
17323                 /* Expand insni[off]'s seen count to the patched range. */
17324                 new_data[i].seen = old_seen;
17325                 new_data[i].zext_dst = insn_has_def32(env, insn + i);
17326         }
17327         env->insn_aux_data = new_data;
17328         vfree(old_data);
17329 }
17330
17331 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
17332 {
17333         int i;
17334
17335         if (len == 1)
17336                 return;
17337         /* NOTE: fake 'exit' subprog should be updated as well. */
17338         for (i = 0; i <= env->subprog_cnt; i++) {
17339                 if (env->subprog_info[i].start <= off)
17340                         continue;
17341                 env->subprog_info[i].start += len - 1;
17342         }
17343 }
17344
17345 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len)
17346 {
17347         struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
17348         int i, sz = prog->aux->size_poke_tab;
17349         struct bpf_jit_poke_descriptor *desc;
17350
17351         for (i = 0; i < sz; i++) {
17352                 desc = &tab[i];
17353                 if (desc->insn_idx <= off)
17354                         continue;
17355                 desc->insn_idx += len - 1;
17356         }
17357 }
17358
17359 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
17360                                             const struct bpf_insn *patch, u32 len)
17361 {
17362         struct bpf_prog *new_prog;
17363         struct bpf_insn_aux_data *new_data = NULL;
17364
17365         if (len > 1) {
17366                 new_data = vzalloc(array_size(env->prog->len + len - 1,
17367                                               sizeof(struct bpf_insn_aux_data)));
17368                 if (!new_data)
17369                         return NULL;
17370         }
17371
17372         new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
17373         if (IS_ERR(new_prog)) {
17374                 if (PTR_ERR(new_prog) == -ERANGE)
17375                         verbose(env,
17376                                 "insn %d cannot be patched due to 16-bit range\n",
17377                                 env->insn_aux_data[off].orig_idx);
17378                 vfree(new_data);
17379                 return NULL;
17380         }
17381         adjust_insn_aux_data(env, new_data, new_prog, off, len);
17382         adjust_subprog_starts(env, off, len);
17383         adjust_poke_descs(new_prog, off, len);
17384         return new_prog;
17385 }
17386
17387 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
17388                                               u32 off, u32 cnt)
17389 {
17390         int i, j;
17391
17392         /* find first prog starting at or after off (first to remove) */
17393         for (i = 0; i < env->subprog_cnt; i++)
17394                 if (env->subprog_info[i].start >= off)
17395                         break;
17396         /* find first prog starting at or after off + cnt (first to stay) */
17397         for (j = i; j < env->subprog_cnt; j++)
17398                 if (env->subprog_info[j].start >= off + cnt)
17399                         break;
17400         /* if j doesn't start exactly at off + cnt, we are just removing
17401          * the front of previous prog
17402          */
17403         if (env->subprog_info[j].start != off + cnt)
17404                 j--;
17405
17406         if (j > i) {
17407                 struct bpf_prog_aux *aux = env->prog->aux;
17408                 int move;
17409
17410                 /* move fake 'exit' subprog as well */
17411                 move = env->subprog_cnt + 1 - j;
17412
17413                 memmove(env->subprog_info + i,
17414                         env->subprog_info + j,
17415                         sizeof(*env->subprog_info) * move);
17416                 env->subprog_cnt -= j - i;
17417
17418                 /* remove func_info */
17419                 if (aux->func_info) {
17420                         move = aux->func_info_cnt - j;
17421
17422                         memmove(aux->func_info + i,
17423                                 aux->func_info + j,
17424                                 sizeof(*aux->func_info) * move);
17425                         aux->func_info_cnt -= j - i;
17426                         /* func_info->insn_off is set after all code rewrites,
17427                          * in adjust_btf_func() - no need to adjust
17428                          */
17429                 }
17430         } else {
17431                 /* convert i from "first prog to remove" to "first to adjust" */
17432                 if (env->subprog_info[i].start == off)
17433                         i++;
17434         }
17435
17436         /* update fake 'exit' subprog as well */
17437         for (; i <= env->subprog_cnt; i++)
17438                 env->subprog_info[i].start -= cnt;
17439
17440         return 0;
17441 }
17442
17443 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
17444                                       u32 cnt)
17445 {
17446         struct bpf_prog *prog = env->prog;
17447         u32 i, l_off, l_cnt, nr_linfo;
17448         struct bpf_line_info *linfo;
17449
17450         nr_linfo = prog->aux->nr_linfo;
17451         if (!nr_linfo)
17452                 return 0;
17453
17454         linfo = prog->aux->linfo;
17455
17456         /* find first line info to remove, count lines to be removed */
17457         for (i = 0; i < nr_linfo; i++)
17458                 if (linfo[i].insn_off >= off)
17459                         break;
17460
17461         l_off = i;
17462         l_cnt = 0;
17463         for (; i < nr_linfo; i++)
17464                 if (linfo[i].insn_off < off + cnt)
17465                         l_cnt++;
17466                 else
17467                         break;
17468
17469         /* First live insn doesn't match first live linfo, it needs to "inherit"
17470          * last removed linfo.  prog is already modified, so prog->len == off
17471          * means no live instructions after (tail of the program was removed).
17472          */
17473         if (prog->len != off && l_cnt &&
17474             (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
17475                 l_cnt--;
17476                 linfo[--i].insn_off = off + cnt;
17477         }
17478
17479         /* remove the line info which refer to the removed instructions */
17480         if (l_cnt) {
17481                 memmove(linfo + l_off, linfo + i,
17482                         sizeof(*linfo) * (nr_linfo - i));
17483
17484                 prog->aux->nr_linfo -= l_cnt;
17485                 nr_linfo = prog->aux->nr_linfo;
17486         }
17487
17488         /* pull all linfo[i].insn_off >= off + cnt in by cnt */
17489         for (i = l_off; i < nr_linfo; i++)
17490                 linfo[i].insn_off -= cnt;
17491
17492         /* fix up all subprogs (incl. 'exit') which start >= off */
17493         for (i = 0; i <= env->subprog_cnt; i++)
17494                 if (env->subprog_info[i].linfo_idx > l_off) {
17495                         /* program may have started in the removed region but
17496                          * may not be fully removed
17497                          */
17498                         if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
17499                                 env->subprog_info[i].linfo_idx -= l_cnt;
17500                         else
17501                                 env->subprog_info[i].linfo_idx = l_off;
17502                 }
17503
17504         return 0;
17505 }
17506
17507 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
17508 {
17509         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17510         unsigned int orig_prog_len = env->prog->len;
17511         int err;
17512
17513         if (bpf_prog_is_offloaded(env->prog->aux))
17514                 bpf_prog_offload_remove_insns(env, off, cnt);
17515
17516         err = bpf_remove_insns(env->prog, off, cnt);
17517         if (err)
17518                 return err;
17519
17520         err = adjust_subprog_starts_after_remove(env, off, cnt);
17521         if (err)
17522                 return err;
17523
17524         err = bpf_adj_linfo_after_remove(env, off, cnt);
17525         if (err)
17526                 return err;
17527
17528         memmove(aux_data + off, aux_data + off + cnt,
17529                 sizeof(*aux_data) * (orig_prog_len - off - cnt));
17530
17531         return 0;
17532 }
17533
17534 /* The verifier does more data flow analysis than llvm and will not
17535  * explore branches that are dead at run time. Malicious programs can
17536  * have dead code too. Therefore replace all dead at-run-time code
17537  * with 'ja -1'.
17538  *
17539  * Just nops are not optimal, e.g. if they would sit at the end of the
17540  * program and through another bug we would manage to jump there, then
17541  * we'd execute beyond program memory otherwise. Returning exception
17542  * code also wouldn't work since we can have subprogs where the dead
17543  * code could be located.
17544  */
17545 static void sanitize_dead_code(struct bpf_verifier_env *env)
17546 {
17547         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17548         struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
17549         struct bpf_insn *insn = env->prog->insnsi;
17550         const int insn_cnt = env->prog->len;
17551         int i;
17552
17553         for (i = 0; i < insn_cnt; i++) {
17554                 if (aux_data[i].seen)
17555                         continue;
17556                 memcpy(insn + i, &trap, sizeof(trap));
17557                 aux_data[i].zext_dst = false;
17558         }
17559 }
17560
17561 static bool insn_is_cond_jump(u8 code)
17562 {
17563         u8 op;
17564
17565         op = BPF_OP(code);
17566         if (BPF_CLASS(code) == BPF_JMP32)
17567                 return op != BPF_JA;
17568
17569         if (BPF_CLASS(code) != BPF_JMP)
17570                 return false;
17571
17572         return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
17573 }
17574
17575 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
17576 {
17577         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17578         struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17579         struct bpf_insn *insn = env->prog->insnsi;
17580         const int insn_cnt = env->prog->len;
17581         int i;
17582
17583         for (i = 0; i < insn_cnt; i++, insn++) {
17584                 if (!insn_is_cond_jump(insn->code))
17585                         continue;
17586
17587                 if (!aux_data[i + 1].seen)
17588                         ja.off = insn->off;
17589                 else if (!aux_data[i + 1 + insn->off].seen)
17590                         ja.off = 0;
17591                 else
17592                         continue;
17593
17594                 if (bpf_prog_is_offloaded(env->prog->aux))
17595                         bpf_prog_offload_replace_insn(env, i, &ja);
17596
17597                 memcpy(insn, &ja, sizeof(ja));
17598         }
17599 }
17600
17601 static int opt_remove_dead_code(struct bpf_verifier_env *env)
17602 {
17603         struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
17604         int insn_cnt = env->prog->len;
17605         int i, err;
17606
17607         for (i = 0; i < insn_cnt; i++) {
17608                 int j;
17609
17610                 j = 0;
17611                 while (i + j < insn_cnt && !aux_data[i + j].seen)
17612                         j++;
17613                 if (!j)
17614                         continue;
17615
17616                 err = verifier_remove_insns(env, i, j);
17617                 if (err)
17618                         return err;
17619                 insn_cnt = env->prog->len;
17620         }
17621
17622         return 0;
17623 }
17624
17625 static int opt_remove_nops(struct bpf_verifier_env *env)
17626 {
17627         const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
17628         struct bpf_insn *insn = env->prog->insnsi;
17629         int insn_cnt = env->prog->len;
17630         int i, err;
17631
17632         for (i = 0; i < insn_cnt; i++) {
17633                 if (memcmp(&insn[i], &ja, sizeof(ja)))
17634                         continue;
17635
17636                 err = verifier_remove_insns(env, i, 1);
17637                 if (err)
17638                         return err;
17639                 insn_cnt--;
17640                 i--;
17641         }
17642
17643         return 0;
17644 }
17645
17646 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
17647                                          const union bpf_attr *attr)
17648 {
17649         struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4];
17650         struct bpf_insn_aux_data *aux = env->insn_aux_data;
17651         int i, patch_len, delta = 0, len = env->prog->len;
17652         struct bpf_insn *insns = env->prog->insnsi;
17653         struct bpf_prog *new_prog;
17654         bool rnd_hi32;
17655
17656         rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
17657         zext_patch[1] = BPF_ZEXT_REG(0);
17658         rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
17659         rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
17660         rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
17661         for (i = 0; i < len; i++) {
17662                 int adj_idx = i + delta;
17663                 struct bpf_insn insn;
17664                 int load_reg;
17665
17666                 insn = insns[adj_idx];
17667                 load_reg = insn_def_regno(&insn);
17668                 if (!aux[adj_idx].zext_dst) {
17669                         u8 code, class;
17670                         u32 imm_rnd;
17671
17672                         if (!rnd_hi32)
17673                                 continue;
17674
17675                         code = insn.code;
17676                         class = BPF_CLASS(code);
17677                         if (load_reg == -1)
17678                                 continue;
17679
17680                         /* NOTE: arg "reg" (the fourth one) is only used for
17681                          *       BPF_STX + SRC_OP, so it is safe to pass NULL
17682                          *       here.
17683                          */
17684                         if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) {
17685                                 if (class == BPF_LD &&
17686                                     BPF_MODE(code) == BPF_IMM)
17687                                         i++;
17688                                 continue;
17689                         }
17690
17691                         /* ctx load could be transformed into wider load. */
17692                         if (class == BPF_LDX &&
17693                             aux[adj_idx].ptr_type == PTR_TO_CTX)
17694                                 continue;
17695
17696                         imm_rnd = get_random_u32();
17697                         rnd_hi32_patch[0] = insn;
17698                         rnd_hi32_patch[1].imm = imm_rnd;
17699                         rnd_hi32_patch[3].dst_reg = load_reg;
17700                         patch = rnd_hi32_patch;
17701                         patch_len = 4;
17702                         goto apply_patch_buffer;
17703                 }
17704
17705                 /* Add in an zero-extend instruction if a) the JIT has requested
17706                  * it or b) it's a CMPXCHG.
17707                  *
17708                  * The latter is because: BPF_CMPXCHG always loads a value into
17709                  * R0, therefore always zero-extends. However some archs'
17710                  * equivalent instruction only does this load when the
17711                  * comparison is successful. This detail of CMPXCHG is
17712                  * orthogonal to the general zero-extension behaviour of the
17713                  * CPU, so it's treated independently of bpf_jit_needs_zext.
17714                  */
17715                 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
17716                         continue;
17717
17718                 /* Zero-extension is done by the caller. */
17719                 if (bpf_pseudo_kfunc_call(&insn))
17720                         continue;
17721
17722                 if (WARN_ON(load_reg == -1)) {
17723                         verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n");
17724                         return -EFAULT;
17725                 }
17726
17727                 zext_patch[0] = insn;
17728                 zext_patch[1].dst_reg = load_reg;
17729                 zext_patch[1].src_reg = load_reg;
17730                 patch = zext_patch;
17731                 patch_len = 2;
17732 apply_patch_buffer:
17733                 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
17734                 if (!new_prog)
17735                         return -ENOMEM;
17736                 env->prog = new_prog;
17737                 insns = new_prog->insnsi;
17738                 aux = env->insn_aux_data;
17739                 delta += patch_len - 1;
17740         }
17741
17742         return 0;
17743 }
17744
17745 /* convert load instructions that access fields of a context type into a
17746  * sequence of instructions that access fields of the underlying structure:
17747  *     struct __sk_buff    -> struct sk_buff
17748  *     struct bpf_sock_ops -> struct sock
17749  */
17750 static int convert_ctx_accesses(struct bpf_verifier_env *env)
17751 {
17752         const struct bpf_verifier_ops *ops = env->ops;
17753         int i, cnt, size, ctx_field_size, delta = 0;
17754         const int insn_cnt = env->prog->len;
17755         struct bpf_insn insn_buf[16], *insn;
17756         u32 target_size, size_default, off;
17757         struct bpf_prog *new_prog;
17758         enum bpf_access_type type;
17759         bool is_narrower_load;
17760
17761         if (ops->gen_prologue || env->seen_direct_write) {
17762                 if (!ops->gen_prologue) {
17763                         verbose(env, "bpf verifier is misconfigured\n");
17764                         return -EINVAL;
17765                 }
17766                 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
17767                                         env->prog);
17768                 if (cnt >= ARRAY_SIZE(insn_buf)) {
17769                         verbose(env, "bpf verifier is misconfigured\n");
17770                         return -EINVAL;
17771                 } else if (cnt) {
17772                         new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt);
17773                         if (!new_prog)
17774                                 return -ENOMEM;
17775
17776                         env->prog = new_prog;
17777                         delta += cnt - 1;
17778                 }
17779         }
17780
17781         if (bpf_prog_is_offloaded(env->prog->aux))
17782                 return 0;
17783
17784         insn = env->prog->insnsi + delta;
17785
17786         for (i = 0; i < insn_cnt; i++, insn++) {
17787                 bpf_convert_ctx_access_t convert_ctx_access;
17788                 u8 mode;
17789
17790                 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
17791                     insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
17792                     insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
17793                     insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
17794                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
17795                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
17796                     insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
17797                         type = BPF_READ;
17798                 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
17799                            insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
17800                            insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
17801                            insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
17802                            insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
17803                            insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
17804                            insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
17805                            insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
17806                         type = BPF_WRITE;
17807                 } else {
17808                         continue;
17809                 }
17810
17811                 if (type == BPF_WRITE &&
17812                     env->insn_aux_data[i + delta].sanitize_stack_spill) {
17813                         struct bpf_insn patch[] = {
17814                                 *insn,
17815                                 BPF_ST_NOSPEC(),
17816                         };
17817
17818                         cnt = ARRAY_SIZE(patch);
17819                         new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt);
17820                         if (!new_prog)
17821                                 return -ENOMEM;
17822
17823                         delta    += cnt - 1;
17824                         env->prog = new_prog;
17825                         insn      = new_prog->insnsi + i + delta;
17826                         continue;
17827                 }
17828
17829                 switch ((int)env->insn_aux_data[i + delta].ptr_type) {
17830                 case PTR_TO_CTX:
17831                         if (!ops->convert_ctx_access)
17832                                 continue;
17833                         convert_ctx_access = ops->convert_ctx_access;
17834                         break;
17835                 case PTR_TO_SOCKET:
17836                 case PTR_TO_SOCK_COMMON:
17837                         convert_ctx_access = bpf_sock_convert_ctx_access;
17838                         break;
17839                 case PTR_TO_TCP_SOCK:
17840                         convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
17841                         break;
17842                 case PTR_TO_XDP_SOCK:
17843                         convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
17844                         break;
17845                 case PTR_TO_BTF_ID:
17846                 case PTR_TO_BTF_ID | PTR_UNTRUSTED:
17847                 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike
17848                  * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot
17849                  * be said once it is marked PTR_UNTRUSTED, hence we must handle
17850                  * any faults for loads into such types. BPF_WRITE is disallowed
17851                  * for this case.
17852                  */
17853                 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED:
17854                         if (type == BPF_READ) {
17855                                 if (BPF_MODE(insn->code) == BPF_MEM)
17856                                         insn->code = BPF_LDX | BPF_PROBE_MEM |
17857                                                      BPF_SIZE((insn)->code);
17858                                 else
17859                                         insn->code = BPF_LDX | BPF_PROBE_MEMSX |
17860                                                      BPF_SIZE((insn)->code);
17861                                 env->prog->aux->num_exentries++;
17862                         }
17863                         continue;
17864                 default:
17865                         continue;
17866                 }
17867
17868                 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
17869                 size = BPF_LDST_BYTES(insn);
17870                 mode = BPF_MODE(insn->code);
17871
17872                 /* If the read access is a narrower load of the field,
17873                  * convert to a 4/8-byte load, to minimum program type specific
17874                  * convert_ctx_access changes. If conversion is successful,
17875                  * we will apply proper mask to the result.
17876                  */
17877                 is_narrower_load = size < ctx_field_size;
17878                 size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
17879                 off = insn->off;
17880                 if (is_narrower_load) {
17881                         u8 size_code;
17882
17883                         if (type == BPF_WRITE) {
17884                                 verbose(env, "bpf verifier narrow ctx access misconfigured\n");
17885                                 return -EINVAL;
17886                         }
17887
17888                         size_code = BPF_H;
17889                         if (ctx_field_size == 4)
17890                                 size_code = BPF_W;
17891                         else if (ctx_field_size == 8)
17892                                 size_code = BPF_DW;
17893
17894                         insn->off = off & ~(size_default - 1);
17895                         insn->code = BPF_LDX | BPF_MEM | size_code;
17896                 }
17897
17898                 target_size = 0;
17899                 cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
17900                                          &target_size);
17901                 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) ||
17902                     (ctx_field_size && !target_size)) {
17903                         verbose(env, "bpf verifier is misconfigured\n");
17904                         return -EINVAL;
17905                 }
17906
17907                 if (is_narrower_load && size < target_size) {
17908                         u8 shift = bpf_ctx_narrow_access_offset(
17909                                 off, size, size_default) * 8;
17910                         if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) {
17911                                 verbose(env, "bpf verifier narrow ctx load misconfigured\n");
17912                                 return -EINVAL;
17913                         }
17914                         if (ctx_field_size <= 4) {
17915                                 if (shift)
17916                                         insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
17917                                                                         insn->dst_reg,
17918                                                                         shift);
17919                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17920                                                                 (1 << size * 8) - 1);
17921                         } else {
17922                                 if (shift)
17923                                         insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
17924                                                                         insn->dst_reg,
17925                                                                         shift);
17926                                 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
17927                                                                 (1ULL << size * 8) - 1);
17928                         }
17929                 }
17930                 if (mode == BPF_MEMSX)
17931                         insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
17932                                                        insn->dst_reg, insn->dst_reg,
17933                                                        size * 8, 0);
17934
17935                 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
17936                 if (!new_prog)
17937                         return -ENOMEM;
17938
17939                 delta += cnt - 1;
17940
17941                 /* keep walking new program and skip insns we just inserted */
17942                 env->prog = new_prog;
17943                 insn      = new_prog->insnsi + i + delta;
17944         }
17945
17946         return 0;
17947 }
17948
17949 static int jit_subprogs(struct bpf_verifier_env *env)
17950 {
17951         struct bpf_prog *prog = env->prog, **func, *tmp;
17952         int i, j, subprog_start, subprog_end = 0, len, subprog;
17953         struct bpf_map *map_ptr;
17954         struct bpf_insn *insn;
17955         void *old_bpf_func;
17956         int err, num_exentries;
17957
17958         if (env->subprog_cnt <= 1)
17959                 return 0;
17960
17961         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
17962                 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
17963                         continue;
17964
17965                 /* Upon error here we cannot fall back to interpreter but
17966                  * need a hard reject of the program. Thus -EFAULT is
17967                  * propagated in any case.
17968                  */
17969                 subprog = find_subprog(env, i + insn->imm + 1);
17970                 if (subprog < 0) {
17971                         WARN_ONCE(1, "verifier bug. No program starts at insn %d\n",
17972                                   i + insn->imm + 1);
17973                         return -EFAULT;
17974                 }
17975                 /* temporarily remember subprog id inside insn instead of
17976                  * aux_data, since next loop will split up all insns into funcs
17977                  */
17978                 insn->off = subprog;
17979                 /* remember original imm in case JIT fails and fallback
17980                  * to interpreter will be needed
17981                  */
17982                 env->insn_aux_data[i].call_imm = insn->imm;
17983                 /* point imm to __bpf_call_base+1 from JITs point of view */
17984                 insn->imm = 1;
17985                 if (bpf_pseudo_func(insn))
17986                         /* jit (e.g. x86_64) may emit fewer instructions
17987                          * if it learns a u32 imm is the same as a u64 imm.
17988                          * Force a non zero here.
17989                          */
17990                         insn[1].imm = 1;
17991         }
17992
17993         err = bpf_prog_alloc_jited_linfo(prog);
17994         if (err)
17995                 goto out_undo_insn;
17996
17997         err = -ENOMEM;
17998         func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);
17999         if (!func)
18000                 goto out_undo_insn;
18001
18002         for (i = 0; i < env->subprog_cnt; i++) {
18003                 subprog_start = subprog_end;
18004                 subprog_end = env->subprog_info[i + 1].start;
18005
18006                 len = subprog_end - subprog_start;
18007                 /* bpf_prog_run() doesn't call subprogs directly,
18008                  * hence main prog stats include the runtime of subprogs.
18009                  * subprogs don't have IDs and not reachable via prog_get_next_id
18010                  * func[i]->stats will never be accessed and stays NULL
18011                  */
18012                 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
18013                 if (!func[i])
18014                         goto out_free;
18015                 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
18016                        len * sizeof(struct bpf_insn));
18017                 func[i]->type = prog->type;
18018                 func[i]->len = len;
18019                 if (bpf_prog_calc_tag(func[i]))
18020                         goto out_free;
18021                 func[i]->is_func = 1;
18022                 func[i]->aux->func_idx = i;
18023                 /* Below members will be freed only at prog->aux */
18024                 func[i]->aux->btf = prog->aux->btf;
18025                 func[i]->aux->func_info = prog->aux->func_info;
18026                 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
18027                 func[i]->aux->poke_tab = prog->aux->poke_tab;
18028                 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
18029
18030                 for (j = 0; j < prog->aux->size_poke_tab; j++) {
18031                         struct bpf_jit_poke_descriptor *poke;
18032
18033                         poke = &prog->aux->poke_tab[j];
18034                         if (poke->insn_idx < subprog_end &&
18035                             poke->insn_idx >= subprog_start)
18036                                 poke->aux = func[i]->aux;
18037                 }
18038
18039                 func[i]->aux->name[0] = 'F';
18040                 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
18041                 func[i]->jit_requested = 1;
18042                 func[i]->blinding_requested = prog->blinding_requested;
18043                 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
18044                 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
18045                 func[i]->aux->linfo = prog->aux->linfo;
18046                 func[i]->aux->nr_linfo = prog->aux->nr_linfo;
18047                 func[i]->aux->jited_linfo = prog->aux->jited_linfo;
18048                 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
18049                 num_exentries = 0;
18050                 insn = func[i]->insnsi;
18051                 for (j = 0; j < func[i]->len; j++, insn++) {
18052                         if (BPF_CLASS(insn->code) == BPF_LDX &&
18053                             (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
18054                              BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
18055                                 num_exentries++;
18056                 }
18057                 func[i]->aux->num_exentries = num_exentries;
18058                 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
18059                 func[i] = bpf_int_jit_compile(func[i]);
18060                 if (!func[i]->jited) {
18061                         err = -ENOTSUPP;
18062                         goto out_free;
18063                 }
18064                 cond_resched();
18065         }
18066
18067         /* at this point all bpf functions were successfully JITed
18068          * now populate all bpf_calls with correct addresses and
18069          * run last pass of JIT
18070          */
18071         for (i = 0; i < env->subprog_cnt; i++) {
18072                 insn = func[i]->insnsi;
18073                 for (j = 0; j < func[i]->len; j++, insn++) {
18074                         if (bpf_pseudo_func(insn)) {
18075                                 subprog = insn->off;
18076                                 insn[0].imm = (u32)(long)func[subprog]->bpf_func;
18077                                 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
18078                                 continue;
18079                         }
18080                         if (!bpf_pseudo_call(insn))
18081                                 continue;
18082                         subprog = insn->off;
18083                         insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
18084                 }
18085
18086                 /* we use the aux data to keep a list of the start addresses
18087                  * of the JITed images for each function in the program
18088                  *
18089                  * for some architectures, such as powerpc64, the imm field
18090                  * might not be large enough to hold the offset of the start
18091                  * address of the callee's JITed image from __bpf_call_base
18092                  *
18093                  * in such cases, we can lookup the start address of a callee
18094                  * by using its subprog id, available from the off field of
18095                  * the call instruction, as an index for this list
18096                  */
18097                 func[i]->aux->func = func;
18098                 func[i]->aux->func_cnt = env->subprog_cnt;
18099         }
18100         for (i = 0; i < env->subprog_cnt; i++) {
18101                 old_bpf_func = func[i]->bpf_func;
18102                 tmp = bpf_int_jit_compile(func[i]);
18103                 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
18104                         verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
18105                         err = -ENOTSUPP;
18106                         goto out_free;
18107                 }
18108                 cond_resched();
18109         }
18110
18111         /* finally lock prog and jit images for all functions and
18112          * populate kallsysm. Begin at the first subprogram, since
18113          * bpf_prog_load will add the kallsyms for the main program.
18114          */
18115         for (i = 1; i < env->subprog_cnt; i++) {
18116                 bpf_prog_lock_ro(func[i]);
18117                 bpf_prog_kallsyms_add(func[i]);
18118         }
18119
18120         /* Last step: make now unused interpreter insns from main
18121          * prog consistent for later dump requests, so they can
18122          * later look the same as if they were interpreted only.
18123          */
18124         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18125                 if (bpf_pseudo_func(insn)) {
18126                         insn[0].imm = env->insn_aux_data[i].call_imm;
18127                         insn[1].imm = insn->off;
18128                         insn->off = 0;
18129                         continue;
18130                 }
18131                 if (!bpf_pseudo_call(insn))
18132                         continue;
18133                 insn->off = env->insn_aux_data[i].call_imm;
18134                 subprog = find_subprog(env, i + insn->off + 1);
18135                 insn->imm = subprog;
18136         }
18137
18138         prog->jited = 1;
18139         prog->bpf_func = func[0]->bpf_func;
18140         prog->jited_len = func[0]->jited_len;
18141         prog->aux->extable = func[0]->aux->extable;
18142         prog->aux->num_exentries = func[0]->aux->num_exentries;
18143         prog->aux->func = func;
18144         prog->aux->func_cnt = env->subprog_cnt;
18145         bpf_prog_jit_attempt_done(prog);
18146         return 0;
18147 out_free:
18148         /* We failed JIT'ing, so at this point we need to unregister poke
18149          * descriptors from subprogs, so that kernel is not attempting to
18150          * patch it anymore as we're freeing the subprog JIT memory.
18151          */
18152         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18153                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18154                 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
18155         }
18156         /* At this point we're guaranteed that poke descriptors are not
18157          * live anymore. We can just unlink its descriptor table as it's
18158          * released with the main prog.
18159          */
18160         for (i = 0; i < env->subprog_cnt; i++) {
18161                 if (!func[i])
18162                         continue;
18163                 func[i]->aux->poke_tab = NULL;
18164                 bpf_jit_free(func[i]);
18165         }
18166         kfree(func);
18167 out_undo_insn:
18168         /* cleanup main prog to be interpreted */
18169         prog->jit_requested = 0;
18170         prog->blinding_requested = 0;
18171         for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
18172                 if (!bpf_pseudo_call(insn))
18173                         continue;
18174                 insn->off = 0;
18175                 insn->imm = env->insn_aux_data[i].call_imm;
18176         }
18177         bpf_prog_jit_attempt_done(prog);
18178         return err;
18179 }
18180
18181 static int fixup_call_args(struct bpf_verifier_env *env)
18182 {
18183 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18184         struct bpf_prog *prog = env->prog;
18185         struct bpf_insn *insn = prog->insnsi;
18186         bool has_kfunc_call = bpf_prog_has_kfunc_call(prog);
18187         int i, depth;
18188 #endif
18189         int err = 0;
18190
18191         if (env->prog->jit_requested &&
18192             !bpf_prog_is_offloaded(env->prog->aux)) {
18193                 err = jit_subprogs(env);
18194                 if (err == 0)
18195                         return 0;
18196                 if (err == -EFAULT)
18197                         return err;
18198         }
18199 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
18200         if (has_kfunc_call) {
18201                 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n");
18202                 return -EINVAL;
18203         }
18204         if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
18205                 /* When JIT fails the progs with bpf2bpf calls and tail_calls
18206                  * have to be rejected, since interpreter doesn't support them yet.
18207                  */
18208                 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
18209                 return -EINVAL;
18210         }
18211         for (i = 0; i < prog->len; i++, insn++) {
18212                 if (bpf_pseudo_func(insn)) {
18213                         /* When JIT fails the progs with callback calls
18214                          * have to be rejected, since interpreter doesn't support them yet.
18215                          */
18216                         verbose(env, "callbacks are not allowed in non-JITed programs\n");
18217                         return -EINVAL;
18218                 }
18219
18220                 if (!bpf_pseudo_call(insn))
18221                         continue;
18222                 depth = get_callee_stack_depth(env, insn, i);
18223                 if (depth < 0)
18224                         return depth;
18225                 bpf_patch_call_args(insn, depth);
18226         }
18227         err = 0;
18228 #endif
18229         return err;
18230 }
18231
18232 /* replace a generic kfunc with a specialized version if necessary */
18233 static void specialize_kfunc(struct bpf_verifier_env *env,
18234                              u32 func_id, u16 offset, unsigned long *addr)
18235 {
18236         struct bpf_prog *prog = env->prog;
18237         bool seen_direct_write;
18238         void *xdp_kfunc;
18239         bool is_rdonly;
18240
18241         if (bpf_dev_bound_kfunc_id(func_id)) {
18242                 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
18243                 if (xdp_kfunc) {
18244                         *addr = (unsigned long)xdp_kfunc;
18245                         return;
18246                 }
18247                 /* fallback to default kfunc when not supported by netdev */
18248         }
18249
18250         if (offset)
18251                 return;
18252
18253         if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
18254                 seen_direct_write = env->seen_direct_write;
18255                 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
18256
18257                 if (is_rdonly)
18258                         *addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
18259
18260                 /* restore env->seen_direct_write to its original value, since
18261                  * may_access_direct_pkt_data mutates it
18262                  */
18263                 env->seen_direct_write = seen_direct_write;
18264         }
18265 }
18266
18267 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
18268                                             u16 struct_meta_reg,
18269                                             u16 node_offset_reg,
18270                                             struct bpf_insn *insn,
18271                                             struct bpf_insn *insn_buf,
18272                                             int *cnt)
18273 {
18274         struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta;
18275         struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) };
18276
18277         insn_buf[0] = addr[0];
18278         insn_buf[1] = addr[1];
18279         insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off);
18280         insn_buf[3] = *insn;
18281         *cnt = 4;
18282 }
18283
18284 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
18285                             struct bpf_insn *insn_buf, int insn_idx, int *cnt)
18286 {
18287         const struct bpf_kfunc_desc *desc;
18288
18289         if (!insn->imm) {
18290                 verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
18291                 return -EINVAL;
18292         }
18293
18294         *cnt = 0;
18295
18296         /* insn->imm has the btf func_id. Replace it with an offset relative to
18297          * __bpf_call_base, unless the JIT needs to call functions that are
18298          * further than 32 bits away (bpf_jit_supports_far_kfunc_call()).
18299          */
18300         desc = find_kfunc_desc(env->prog, insn->imm, insn->off);
18301         if (!desc) {
18302                 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n",
18303                         insn->imm);
18304                 return -EFAULT;
18305         }
18306
18307         if (!bpf_jit_supports_far_kfunc_call())
18308                 insn->imm = BPF_CALL_IMM(desc->addr);
18309         if (insn->off)
18310                 return 0;
18311         if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) {
18312                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18313                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18314                 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size;
18315
18316                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size);
18317                 insn_buf[1] = addr[0];
18318                 insn_buf[2] = addr[1];
18319                 insn_buf[3] = *insn;
18320                 *cnt = 4;
18321         } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] ||
18322                    desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) {
18323                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18324                 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) };
18325
18326                 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] &&
18327                     !kptr_struct_meta) {
18328                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18329                                 insn_idx);
18330                         return -EFAULT;
18331                 }
18332
18333                 insn_buf[0] = addr[0];
18334                 insn_buf[1] = addr[1];
18335                 insn_buf[2] = *insn;
18336                 *cnt = 3;
18337         } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] ||
18338                    desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] ||
18339                    desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18340                 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta;
18341                 int struct_meta_reg = BPF_REG_3;
18342                 int node_offset_reg = BPF_REG_4;
18343
18344                 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */
18345                 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) {
18346                         struct_meta_reg = BPF_REG_4;
18347                         node_offset_reg = BPF_REG_5;
18348                 }
18349
18350                 if (!kptr_struct_meta) {
18351                         verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n",
18352                                 insn_idx);
18353                         return -EFAULT;
18354                 }
18355
18356                 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg,
18357                                                 node_offset_reg, insn, insn_buf, cnt);
18358         } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] ||
18359                    desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) {
18360                 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
18361                 *cnt = 1;
18362         }
18363         return 0;
18364 }
18365
18366 /* Do various post-verification rewrites in a single program pass.
18367  * These rewrites simplify JIT and interpreter implementations.
18368  */
18369 static int do_misc_fixups(struct bpf_verifier_env *env)
18370 {
18371         struct bpf_prog *prog = env->prog;
18372         enum bpf_attach_type eatype = prog->expected_attach_type;
18373         enum bpf_prog_type prog_type = resolve_prog_type(prog);
18374         struct bpf_insn *insn = prog->insnsi;
18375         const struct bpf_func_proto *fn;
18376         const int insn_cnt = prog->len;
18377         const struct bpf_map_ops *ops;
18378         struct bpf_insn_aux_data *aux;
18379         struct bpf_insn insn_buf[16];
18380         struct bpf_prog *new_prog;
18381         struct bpf_map *map_ptr;
18382         int i, ret, cnt, delta = 0;
18383
18384         for (i = 0; i < insn_cnt; i++, insn++) {
18385                 /* Make divide-by-zero exceptions impossible. */
18386                 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
18387                     insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
18388                     insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
18389                     insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
18390                         bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
18391                         bool isdiv = BPF_OP(insn->code) == BPF_DIV;
18392                         struct bpf_insn *patchlet;
18393                         struct bpf_insn chk_and_div[] = {
18394                                 /* [R,W]x div 0 -> 0 */
18395                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18396                                              BPF_JNE | BPF_K, insn->src_reg,
18397                                              0, 2, 0),
18398                                 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg),
18399                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18400                                 *insn,
18401                         };
18402                         struct bpf_insn chk_and_mod[] = {
18403                                 /* [R,W]x mod 0 -> [R,W]x */
18404                                 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
18405                                              BPF_JEQ | BPF_K, insn->src_reg,
18406                                              0, 1 + (is64 ? 0 : 1), 0),
18407                                 *insn,
18408                                 BPF_JMP_IMM(BPF_JA, 0, 0, 1),
18409                                 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg),
18410                         };
18411
18412                         patchlet = isdiv ? chk_and_div : chk_and_mod;
18413                         cnt = isdiv ? ARRAY_SIZE(chk_and_div) :
18414                                       ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0);
18415
18416                         new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt);
18417                         if (!new_prog)
18418                                 return -ENOMEM;
18419
18420                         delta    += cnt - 1;
18421                         env->prog = prog = new_prog;
18422                         insn      = new_prog->insnsi + i + delta;
18423                         continue;
18424                 }
18425
18426                 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
18427                 if (BPF_CLASS(insn->code) == BPF_LD &&
18428                     (BPF_MODE(insn->code) == BPF_ABS ||
18429                      BPF_MODE(insn->code) == BPF_IND)) {
18430                         cnt = env->ops->gen_ld_abs(insn, insn_buf);
18431                         if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18432                                 verbose(env, "bpf verifier is misconfigured\n");
18433                                 return -EINVAL;
18434                         }
18435
18436                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18437                         if (!new_prog)
18438                                 return -ENOMEM;
18439
18440                         delta    += cnt - 1;
18441                         env->prog = prog = new_prog;
18442                         insn      = new_prog->insnsi + i + delta;
18443                         continue;
18444                 }
18445
18446                 /* Rewrite pointer arithmetic to mitigate speculation attacks. */
18447                 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
18448                     insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
18449                         const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
18450                         const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
18451                         struct bpf_insn *patch = &insn_buf[0];
18452                         bool issrc, isneg, isimm;
18453                         u32 off_reg;
18454
18455                         aux = &env->insn_aux_data[i + delta];
18456                         if (!aux->alu_state ||
18457                             aux->alu_state == BPF_ALU_NON_POINTER)
18458                                 continue;
18459
18460                         isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
18461                         issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
18462                                 BPF_ALU_SANITIZE_SRC;
18463                         isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
18464
18465                         off_reg = issrc ? insn->src_reg : insn->dst_reg;
18466                         if (isimm) {
18467                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18468                         } else {
18469                                 if (isneg)
18470                                         *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18471                                 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
18472                                 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
18473                                 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
18474                                 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
18475                                 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
18476                                 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
18477                         }
18478                         if (!issrc)
18479                                 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
18480                         insn->src_reg = BPF_REG_AX;
18481                         if (isneg)
18482                                 insn->code = insn->code == code_add ?
18483                                              code_sub : code_add;
18484                         *patch++ = *insn;
18485                         if (issrc && isneg && !isimm)
18486                                 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
18487                         cnt = patch - insn_buf;
18488
18489                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18490                         if (!new_prog)
18491                                 return -ENOMEM;
18492
18493                         delta    += cnt - 1;
18494                         env->prog = prog = new_prog;
18495                         insn      = new_prog->insnsi + i + delta;
18496                         continue;
18497                 }
18498
18499                 if (insn->code != (BPF_JMP | BPF_CALL))
18500                         continue;
18501                 if (insn->src_reg == BPF_PSEUDO_CALL)
18502                         continue;
18503                 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
18504                         ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
18505                         if (ret)
18506                                 return ret;
18507                         if (cnt == 0)
18508                                 continue;
18509
18510                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18511                         if (!new_prog)
18512                                 return -ENOMEM;
18513
18514                         delta    += cnt - 1;
18515                         env->prog = prog = new_prog;
18516                         insn      = new_prog->insnsi + i + delta;
18517                         continue;
18518                 }
18519
18520                 if (insn->imm == BPF_FUNC_get_route_realm)
18521                         prog->dst_needed = 1;
18522                 if (insn->imm == BPF_FUNC_get_prandom_u32)
18523                         bpf_user_rnd_init_once();
18524                 if (insn->imm == BPF_FUNC_override_return)
18525                         prog->kprobe_override = 1;
18526                 if (insn->imm == BPF_FUNC_tail_call) {
18527                         /* If we tail call into other programs, we
18528                          * cannot make any assumptions since they can
18529                          * be replaced dynamically during runtime in
18530                          * the program array.
18531                          */
18532                         prog->cb_access = 1;
18533                         if (!allow_tail_call_in_subprogs(env))
18534                                 prog->aux->stack_depth = MAX_BPF_STACK;
18535                         prog->aux->max_pkt_offset = MAX_PACKET_OFF;
18536
18537                         /* mark bpf_tail_call as different opcode to avoid
18538                          * conditional branch in the interpreter for every normal
18539                          * call and to prevent accidental JITing by JIT compiler
18540                          * that doesn't support bpf_tail_call yet
18541                          */
18542                         insn->imm = 0;
18543                         insn->code = BPF_JMP | BPF_TAIL_CALL;
18544
18545                         aux = &env->insn_aux_data[i + delta];
18546                         if (env->bpf_capable && !prog->blinding_requested &&
18547                             prog->jit_requested &&
18548                             !bpf_map_key_poisoned(aux) &&
18549                             !bpf_map_ptr_poisoned(aux) &&
18550                             !bpf_map_ptr_unpriv(aux)) {
18551                                 struct bpf_jit_poke_descriptor desc = {
18552                                         .reason = BPF_POKE_REASON_TAIL_CALL,
18553                                         .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state),
18554                                         .tail_call.key = bpf_map_key_immediate(aux),
18555                                         .insn_idx = i + delta,
18556                                 };
18557
18558                                 ret = bpf_jit_add_poke_descriptor(prog, &desc);
18559                                 if (ret < 0) {
18560                                         verbose(env, "adding tail call poke descriptor failed\n");
18561                                         return ret;
18562                                 }
18563
18564                                 insn->imm = ret + 1;
18565                                 continue;
18566                         }
18567
18568                         if (!bpf_map_ptr_unpriv(aux))
18569                                 continue;
18570
18571                         /* instead of changing every JIT dealing with tail_call
18572                          * emit two extra insns:
18573                          * if (index >= max_entries) goto out;
18574                          * index &= array->index_mask;
18575                          * to avoid out-of-bounds cpu speculation
18576                          */
18577                         if (bpf_map_ptr_poisoned(aux)) {
18578                                 verbose(env, "tail_call abusing map_ptr\n");
18579                                 return -EINVAL;
18580                         }
18581
18582                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18583                         insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
18584                                                   map_ptr->max_entries, 2);
18585                         insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
18586                                                     container_of(map_ptr,
18587                                                                  struct bpf_array,
18588                                                                  map)->index_mask);
18589                         insn_buf[2] = *insn;
18590                         cnt = 3;
18591                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18592                         if (!new_prog)
18593                                 return -ENOMEM;
18594
18595                         delta    += cnt - 1;
18596                         env->prog = prog = new_prog;
18597                         insn      = new_prog->insnsi + i + delta;
18598                         continue;
18599                 }
18600
18601                 if (insn->imm == BPF_FUNC_timer_set_callback) {
18602                         /* The verifier will process callback_fn as many times as necessary
18603                          * with different maps and the register states prepared by
18604                          * set_timer_callback_state will be accurate.
18605                          *
18606                          * The following use case is valid:
18607                          *   map1 is shared by prog1, prog2, prog3.
18608                          *   prog1 calls bpf_timer_init for some map1 elements
18609                          *   prog2 calls bpf_timer_set_callback for some map1 elements.
18610                          *     Those that were not bpf_timer_init-ed will return -EINVAL.
18611                          *   prog3 calls bpf_timer_start for some map1 elements.
18612                          *     Those that were not both bpf_timer_init-ed and
18613                          *     bpf_timer_set_callback-ed will return -EINVAL.
18614                          */
18615                         struct bpf_insn ld_addrs[2] = {
18616                                 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux),
18617                         };
18618
18619                         insn_buf[0] = ld_addrs[0];
18620                         insn_buf[1] = ld_addrs[1];
18621                         insn_buf[2] = *insn;
18622                         cnt = 3;
18623
18624                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18625                         if (!new_prog)
18626                                 return -ENOMEM;
18627
18628                         delta    += cnt - 1;
18629                         env->prog = prog = new_prog;
18630                         insn      = new_prog->insnsi + i + delta;
18631                         goto patch_call_imm;
18632                 }
18633
18634                 if (is_storage_get_function(insn->imm)) {
18635                         if (!env->prog->aux->sleepable ||
18636                             env->insn_aux_data[i + delta].storage_get_func_atomic)
18637                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC);
18638                         else
18639                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL);
18640                         insn_buf[1] = *insn;
18641                         cnt = 2;
18642
18643                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18644                         if (!new_prog)
18645                                 return -ENOMEM;
18646
18647                         delta += cnt - 1;
18648                         env->prog = prog = new_prog;
18649                         insn = new_prog->insnsi + i + delta;
18650                         goto patch_call_imm;
18651                 }
18652
18653                 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
18654                  * and other inlining handlers are currently limited to 64 bit
18655                  * only.
18656                  */
18657                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18658                     (insn->imm == BPF_FUNC_map_lookup_elem ||
18659                      insn->imm == BPF_FUNC_map_update_elem ||
18660                      insn->imm == BPF_FUNC_map_delete_elem ||
18661                      insn->imm == BPF_FUNC_map_push_elem   ||
18662                      insn->imm == BPF_FUNC_map_pop_elem    ||
18663                      insn->imm == BPF_FUNC_map_peek_elem   ||
18664                      insn->imm == BPF_FUNC_redirect_map    ||
18665                      insn->imm == BPF_FUNC_for_each_map_elem ||
18666                      insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
18667                         aux = &env->insn_aux_data[i + delta];
18668                         if (bpf_map_ptr_poisoned(aux))
18669                                 goto patch_call_imm;
18670
18671                         map_ptr = BPF_MAP_PTR(aux->map_ptr_state);
18672                         ops = map_ptr->ops;
18673                         if (insn->imm == BPF_FUNC_map_lookup_elem &&
18674                             ops->map_gen_lookup) {
18675                                 cnt = ops->map_gen_lookup(map_ptr, insn_buf);
18676                                 if (cnt == -EOPNOTSUPP)
18677                                         goto patch_map_ops_generic;
18678                                 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) {
18679                                         verbose(env, "bpf verifier is misconfigured\n");
18680                                         return -EINVAL;
18681                                 }
18682
18683                                 new_prog = bpf_patch_insn_data(env, i + delta,
18684                                                                insn_buf, 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                         BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
18695                                      (void *(*)(struct bpf_map *map, void *key))NULL));
18696                         BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
18697                                      (long (*)(struct bpf_map *map, void *key))NULL));
18698                         BUILD_BUG_ON(!__same_type(ops->map_update_elem,
18699                                      (long (*)(struct bpf_map *map, void *key, void *value,
18700                                               u64 flags))NULL));
18701                         BUILD_BUG_ON(!__same_type(ops->map_push_elem,
18702                                      (long (*)(struct bpf_map *map, void *value,
18703                                               u64 flags))NULL));
18704                         BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
18705                                      (long (*)(struct bpf_map *map, void *value))NULL));
18706                         BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
18707                                      (long (*)(struct bpf_map *map, void *value))NULL));
18708                         BUILD_BUG_ON(!__same_type(ops->map_redirect,
18709                                      (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
18710                         BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
18711                                      (long (*)(struct bpf_map *map,
18712                                               bpf_callback_t callback_fn,
18713                                               void *callback_ctx,
18714                                               u64 flags))NULL));
18715                         BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
18716                                      (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
18717
18718 patch_map_ops_generic:
18719                         switch (insn->imm) {
18720                         case BPF_FUNC_map_lookup_elem:
18721                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
18722                                 continue;
18723                         case BPF_FUNC_map_update_elem:
18724                                 insn->imm = BPF_CALL_IMM(ops->map_update_elem);
18725                                 continue;
18726                         case BPF_FUNC_map_delete_elem:
18727                                 insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
18728                                 continue;
18729                         case BPF_FUNC_map_push_elem:
18730                                 insn->imm = BPF_CALL_IMM(ops->map_push_elem);
18731                                 continue;
18732                         case BPF_FUNC_map_pop_elem:
18733                                 insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
18734                                 continue;
18735                         case BPF_FUNC_map_peek_elem:
18736                                 insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
18737                                 continue;
18738                         case BPF_FUNC_redirect_map:
18739                                 insn->imm = BPF_CALL_IMM(ops->map_redirect);
18740                                 continue;
18741                         case BPF_FUNC_for_each_map_elem:
18742                                 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
18743                                 continue;
18744                         case BPF_FUNC_map_lookup_percpu_elem:
18745                                 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
18746                                 continue;
18747                         }
18748
18749                         goto patch_call_imm;
18750                 }
18751
18752                 /* Implement bpf_jiffies64 inline. */
18753                 if (prog->jit_requested && BITS_PER_LONG == 64 &&
18754                     insn->imm == BPF_FUNC_jiffies64) {
18755                         struct bpf_insn ld_jiffies_addr[2] = {
18756                                 BPF_LD_IMM64(BPF_REG_0,
18757                                              (unsigned long)&jiffies),
18758                         };
18759
18760                         insn_buf[0] = ld_jiffies_addr[0];
18761                         insn_buf[1] = ld_jiffies_addr[1];
18762                         insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
18763                                                   BPF_REG_0, 0);
18764                         cnt = 3;
18765
18766                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
18767                                                        cnt);
18768                         if (!new_prog)
18769                                 return -ENOMEM;
18770
18771                         delta    += cnt - 1;
18772                         env->prog = prog = new_prog;
18773                         insn      = new_prog->insnsi + i + delta;
18774                         continue;
18775                 }
18776
18777                 /* Implement bpf_get_func_arg inline. */
18778                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18779                     insn->imm == BPF_FUNC_get_func_arg) {
18780                         /* Load nr_args from ctx - 8 */
18781                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18782                         insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
18783                         insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
18784                         insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
18785                         insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
18786                         insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18787                         insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
18788                         insn_buf[7] = BPF_JMP_A(1);
18789                         insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
18790                         cnt = 9;
18791
18792                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18793                         if (!new_prog)
18794                                 return -ENOMEM;
18795
18796                         delta    += cnt - 1;
18797                         env->prog = prog = new_prog;
18798                         insn      = new_prog->insnsi + i + delta;
18799                         continue;
18800                 }
18801
18802                 /* Implement bpf_get_func_ret inline. */
18803                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18804                     insn->imm == BPF_FUNC_get_func_ret) {
18805                         if (eatype == BPF_TRACE_FEXIT ||
18806                             eatype == BPF_MODIFY_RETURN) {
18807                                 /* Load nr_args from ctx - 8 */
18808                                 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18809                                 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
18810                                 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
18811                                 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
18812                                 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
18813                                 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0);
18814                                 cnt = 6;
18815                         } else {
18816                                 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
18817                                 cnt = 1;
18818                         }
18819
18820                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
18821                         if (!new_prog)
18822                                 return -ENOMEM;
18823
18824                         delta    += cnt - 1;
18825                         env->prog = prog = new_prog;
18826                         insn      = new_prog->insnsi + i + delta;
18827                         continue;
18828                 }
18829
18830                 /* Implement get_func_arg_cnt inline. */
18831                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18832                     insn->imm == BPF_FUNC_get_func_arg_cnt) {
18833                         /* Load nr_args from ctx - 8 */
18834                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
18835
18836                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18837                         if (!new_prog)
18838                                 return -ENOMEM;
18839
18840                         env->prog = prog = new_prog;
18841                         insn      = new_prog->insnsi + i + delta;
18842                         continue;
18843                 }
18844
18845                 /* Implement bpf_get_func_ip inline. */
18846                 if (prog_type == BPF_PROG_TYPE_TRACING &&
18847                     insn->imm == BPF_FUNC_get_func_ip) {
18848                         /* Load IP address from ctx - 16 */
18849                         insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
18850
18851                         new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
18852                         if (!new_prog)
18853                                 return -ENOMEM;
18854
18855                         env->prog = prog = new_prog;
18856                         insn      = new_prog->insnsi + i + delta;
18857                         continue;
18858                 }
18859
18860 patch_call_imm:
18861                 fn = env->ops->get_func_proto(insn->imm, env->prog);
18862                 /* all functions that have prototype and verifier allowed
18863                  * programs to call them, must be real in-kernel functions
18864                  */
18865                 if (!fn->func) {
18866                         verbose(env,
18867                                 "kernel subsystem misconfigured func %s#%d\n",
18868                                 func_id_name(insn->imm), insn->imm);
18869                         return -EFAULT;
18870                 }
18871                 insn->imm = fn->func - __bpf_call_base;
18872         }
18873
18874         /* Since poke tab is now finalized, publish aux to tracker. */
18875         for (i = 0; i < prog->aux->size_poke_tab; i++) {
18876                 map_ptr = prog->aux->poke_tab[i].tail_call.map;
18877                 if (!map_ptr->ops->map_poke_track ||
18878                     !map_ptr->ops->map_poke_untrack ||
18879                     !map_ptr->ops->map_poke_run) {
18880                         verbose(env, "bpf verifier is misconfigured\n");
18881                         return -EINVAL;
18882                 }
18883
18884                 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
18885                 if (ret < 0) {
18886                         verbose(env, "tracking tail call prog failed\n");
18887                         return ret;
18888                 }
18889         }
18890
18891         sort_kfunc_descs_by_imm_off(env->prog);
18892
18893         return 0;
18894 }
18895
18896 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
18897                                         int position,
18898                                         s32 stack_base,
18899                                         u32 callback_subprogno,
18900                                         u32 *cnt)
18901 {
18902         s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
18903         s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
18904         s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
18905         int reg_loop_max = BPF_REG_6;
18906         int reg_loop_cnt = BPF_REG_7;
18907         int reg_loop_ctx = BPF_REG_8;
18908
18909         struct bpf_prog *new_prog;
18910         u32 callback_start;
18911         u32 call_insn_offset;
18912         s32 callback_offset;
18913
18914         /* This represents an inlined version of bpf_iter.c:bpf_loop,
18915          * be careful to modify this code in sync.
18916          */
18917         struct bpf_insn insn_buf[] = {
18918                 /* Return error and jump to the end of the patch if
18919                  * expected number of iterations is too big.
18920                  */
18921                 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2),
18922                 BPF_MOV32_IMM(BPF_REG_0, -E2BIG),
18923                 BPF_JMP_IMM(BPF_JA, 0, 0, 16),
18924                 /* spill R6, R7, R8 to use these as loop vars */
18925                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset),
18926                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset),
18927                 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset),
18928                 /* initialize loop vars */
18929                 BPF_MOV64_REG(reg_loop_max, BPF_REG_1),
18930                 BPF_MOV32_IMM(reg_loop_cnt, 0),
18931                 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3),
18932                 /* loop header,
18933                  * if reg_loop_cnt >= reg_loop_max skip the loop body
18934                  */
18935                 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5),
18936                 /* callback call,
18937                  * correct callback offset would be set after patching
18938                  */
18939                 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt),
18940                 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx),
18941                 BPF_CALL_REL(0),
18942                 /* increment loop counter */
18943                 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1),
18944                 /* jump to loop header if callback returned 0 */
18945                 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6),
18946                 /* return value of bpf_loop,
18947                  * set R0 to the number of iterations
18948                  */
18949                 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt),
18950                 /* restore original values of R6, R7, R8 */
18951                 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset),
18952                 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset),
18953                 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset),
18954         };
18955
18956         *cnt = ARRAY_SIZE(insn_buf);
18957         new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt);
18958         if (!new_prog)
18959                 return new_prog;
18960
18961         /* callback start is known only after patching */
18962         callback_start = env->subprog_info[callback_subprogno].start;
18963         /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
18964         call_insn_offset = position + 12;
18965         callback_offset = callback_start - call_insn_offset - 1;
18966         new_prog->insnsi[call_insn_offset].imm = callback_offset;
18967
18968         return new_prog;
18969 }
18970
18971 static bool is_bpf_loop_call(struct bpf_insn *insn)
18972 {
18973         return insn->code == (BPF_JMP | BPF_CALL) &&
18974                 insn->src_reg == 0 &&
18975                 insn->imm == BPF_FUNC_loop;
18976 }
18977
18978 /* For all sub-programs in the program (including main) check
18979  * insn_aux_data to see if there are bpf_loop calls that require
18980  * inlining. If such calls are found the calls are replaced with a
18981  * sequence of instructions produced by `inline_bpf_loop` function and
18982  * subprog stack_depth is increased by the size of 3 registers.
18983  * This stack space is used to spill values of the R6, R7, R8.  These
18984  * registers are used to store the loop bound, counter and context
18985  * variables.
18986  */
18987 static int optimize_bpf_loop(struct bpf_verifier_env *env)
18988 {
18989         struct bpf_subprog_info *subprogs = env->subprog_info;
18990         int i, cur_subprog = 0, cnt, delta = 0;
18991         struct bpf_insn *insn = env->prog->insnsi;
18992         int insn_cnt = env->prog->len;
18993         u16 stack_depth = subprogs[cur_subprog].stack_depth;
18994         u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
18995         u16 stack_depth_extra = 0;
18996
18997         for (i = 0; i < insn_cnt; i++, insn++) {
18998                 struct bpf_loop_inline_state *inline_state =
18999                         &env->insn_aux_data[i + delta].loop_inline_state;
19000
19001                 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
19002                         struct bpf_prog *new_prog;
19003
19004                         stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
19005                         new_prog = inline_bpf_loop(env,
19006                                                    i + delta,
19007                                                    -(stack_depth + stack_depth_extra),
19008                                                    inline_state->callback_subprogno,
19009                                                    &cnt);
19010                         if (!new_prog)
19011                                 return -ENOMEM;
19012
19013                         delta     += cnt - 1;
19014                         env->prog  = new_prog;
19015                         insn       = new_prog->insnsi + i + delta;
19016                 }
19017
19018                 if (subprogs[cur_subprog + 1].start == i + delta + 1) {
19019                         subprogs[cur_subprog].stack_depth += stack_depth_extra;
19020                         cur_subprog++;
19021                         stack_depth = subprogs[cur_subprog].stack_depth;
19022                         stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
19023                         stack_depth_extra = 0;
19024                 }
19025         }
19026
19027         env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19028
19029         return 0;
19030 }
19031
19032 static void free_states(struct bpf_verifier_env *env)
19033 {
19034         struct bpf_verifier_state_list *sl, *sln;
19035         int i;
19036
19037         sl = env->free_list;
19038         while (sl) {
19039                 sln = sl->next;
19040                 free_verifier_state(&sl->state, false);
19041                 kfree(sl);
19042                 sl = sln;
19043         }
19044         env->free_list = NULL;
19045
19046         if (!env->explored_states)
19047                 return;
19048
19049         for (i = 0; i < state_htab_size(env); i++) {
19050                 sl = env->explored_states[i];
19051
19052                 while (sl) {
19053                         sln = sl->next;
19054                         free_verifier_state(&sl->state, false);
19055                         kfree(sl);
19056                         sl = sln;
19057                 }
19058                 env->explored_states[i] = NULL;
19059         }
19060 }
19061
19062 static int do_check_common(struct bpf_verifier_env *env, int subprog)
19063 {
19064         bool pop_log = !(env->log.level & BPF_LOG_LEVEL2);
19065         struct bpf_verifier_state *state;
19066         struct bpf_reg_state *regs;
19067         int ret, i;
19068
19069         env->prev_linfo = NULL;
19070         env->pass_cnt++;
19071
19072         state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL);
19073         if (!state)
19074                 return -ENOMEM;
19075         state->curframe = 0;
19076         state->speculative = false;
19077         state->branches = 1;
19078         state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL);
19079         if (!state->frame[0]) {
19080                 kfree(state);
19081                 return -ENOMEM;
19082         }
19083         env->cur_state = state;
19084         init_func_state(env, state->frame[0],
19085                         BPF_MAIN_FUNC /* callsite */,
19086                         0 /* frameno */,
19087                         subprog);
19088         state->first_insn_idx = env->subprog_info[subprog].start;
19089         state->last_insn_idx = -1;
19090
19091         regs = state->frame[state->curframe]->regs;
19092         if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
19093                 ret = btf_prepare_func_args(env, subprog, regs);
19094                 if (ret)
19095                         goto out;
19096                 for (i = BPF_REG_1; i <= BPF_REG_5; i++) {
19097                         if (regs[i].type == PTR_TO_CTX)
19098                                 mark_reg_known_zero(env, regs, i);
19099                         else if (regs[i].type == SCALAR_VALUE)
19100                                 mark_reg_unknown(env, regs, i);
19101                         else if (base_type(regs[i].type) == PTR_TO_MEM) {
19102                                 const u32 mem_size = regs[i].mem_size;
19103
19104                                 mark_reg_known_zero(env, regs, i);
19105                                 regs[i].mem_size = mem_size;
19106                                 regs[i].id = ++env->id_gen;
19107                         }
19108                 }
19109         } else {
19110                 /* 1st arg to a function */
19111                 regs[BPF_REG_1].type = PTR_TO_CTX;
19112                 mark_reg_known_zero(env, regs, BPF_REG_1);
19113                 ret = btf_check_subprog_arg_match(env, subprog, regs);
19114                 if (ret == -EFAULT)
19115                         /* unlikely verifier bug. abort.
19116                          * ret == 0 and ret < 0 are sadly acceptable for
19117                          * main() function due to backward compatibility.
19118                          * Like socket filter program may be written as:
19119                          * int bpf_prog(struct pt_regs *ctx)
19120                          * and never dereference that ctx in the program.
19121                          * 'struct pt_regs' is a type mismatch for socket
19122                          * filter that should be using 'struct __sk_buff'.
19123                          */
19124                         goto out;
19125         }
19126
19127         ret = do_check(env);
19128 out:
19129         /* check for NULL is necessary, since cur_state can be freed inside
19130          * do_check() under memory pressure.
19131          */
19132         if (env->cur_state) {
19133                 free_verifier_state(env->cur_state, true);
19134                 env->cur_state = NULL;
19135         }
19136         while (!pop_stack(env, NULL, NULL, false));
19137         if (!ret && pop_log)
19138                 bpf_vlog_reset(&env->log, 0);
19139         free_states(env);
19140         return ret;
19141 }
19142
19143 /* Verify all global functions in a BPF program one by one based on their BTF.
19144  * All global functions must pass verification. Otherwise the whole program is rejected.
19145  * Consider:
19146  * int bar(int);
19147  * int foo(int f)
19148  * {
19149  *    return bar(f);
19150  * }
19151  * int bar(int b)
19152  * {
19153  *    ...
19154  * }
19155  * foo() will be verified first for R1=any_scalar_value. During verification it
19156  * will be assumed that bar() already verified successfully and call to bar()
19157  * from foo() will be checked for type match only. Later bar() will be verified
19158  * independently to check that it's safe for R1=any_scalar_value.
19159  */
19160 static int do_check_subprogs(struct bpf_verifier_env *env)
19161 {
19162         struct bpf_prog_aux *aux = env->prog->aux;
19163         int i, ret;
19164
19165         if (!aux->func_info)
19166                 return 0;
19167
19168         for (i = 1; i < env->subprog_cnt; i++) {
19169                 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL)
19170                         continue;
19171                 env->insn_idx = env->subprog_info[i].start;
19172                 WARN_ON_ONCE(env->insn_idx == 0);
19173                 ret = do_check_common(env, i);
19174                 if (ret) {
19175                         return ret;
19176                 } else if (env->log.level & BPF_LOG_LEVEL) {
19177                         verbose(env,
19178                                 "Func#%d is safe for any args that match its prototype\n",
19179                                 i);
19180                 }
19181         }
19182         return 0;
19183 }
19184
19185 static int do_check_main(struct bpf_verifier_env *env)
19186 {
19187         int ret;
19188
19189         env->insn_idx = 0;
19190         ret = do_check_common(env, 0);
19191         if (!ret)
19192                 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
19193         return ret;
19194 }
19195
19196
19197 static void print_verification_stats(struct bpf_verifier_env *env)
19198 {
19199         int i;
19200
19201         if (env->log.level & BPF_LOG_STATS) {
19202                 verbose(env, "verification time %lld usec\n",
19203                         div_u64(env->verification_time, 1000));
19204                 verbose(env, "stack depth ");
19205                 for (i = 0; i < env->subprog_cnt; i++) {
19206                         u32 depth = env->subprog_info[i].stack_depth;
19207
19208                         verbose(env, "%d", depth);
19209                         if (i + 1 < env->subprog_cnt)
19210                                 verbose(env, "+");
19211                 }
19212                 verbose(env, "\n");
19213         }
19214         verbose(env, "processed %d insns (limit %d) max_states_per_insn %d "
19215                 "total_states %d peak_states %d mark_read %d\n",
19216                 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS,
19217                 env->max_states_per_insn, env->total_states,
19218                 env->peak_states, env->longest_mark_read_walk);
19219 }
19220
19221 static int check_struct_ops_btf_id(struct bpf_verifier_env *env)
19222 {
19223         const struct btf_type *t, *func_proto;
19224         const struct bpf_struct_ops *st_ops;
19225         const struct btf_member *member;
19226         struct bpf_prog *prog = env->prog;
19227         u32 btf_id, member_idx;
19228         const char *mname;
19229
19230         if (!prog->gpl_compatible) {
19231                 verbose(env, "struct ops programs must have a GPL compatible license\n");
19232                 return -EINVAL;
19233         }
19234
19235         btf_id = prog->aux->attach_btf_id;
19236         st_ops = bpf_struct_ops_find(btf_id);
19237         if (!st_ops) {
19238                 verbose(env, "attach_btf_id %u is not a supported struct\n",
19239                         btf_id);
19240                 return -ENOTSUPP;
19241         }
19242
19243         t = st_ops->type;
19244         member_idx = prog->expected_attach_type;
19245         if (member_idx >= btf_type_vlen(t)) {
19246                 verbose(env, "attach to invalid member idx %u of struct %s\n",
19247                         member_idx, st_ops->name);
19248                 return -EINVAL;
19249         }
19250
19251         member = &btf_type_member(t)[member_idx];
19252         mname = btf_name_by_offset(btf_vmlinux, member->name_off);
19253         func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type,
19254                                                NULL);
19255         if (!func_proto) {
19256                 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n",
19257                         mname, member_idx, st_ops->name);
19258                 return -EINVAL;
19259         }
19260
19261         if (st_ops->check_member) {
19262                 int err = st_ops->check_member(t, member, prog);
19263
19264                 if (err) {
19265                         verbose(env, "attach to unsupported member %s of struct %s\n",
19266                                 mname, st_ops->name);
19267                         return err;
19268                 }
19269         }
19270
19271         prog->aux->attach_func_proto = func_proto;
19272         prog->aux->attach_func_name = mname;
19273         env->ops = st_ops->verifier_ops;
19274
19275         return 0;
19276 }
19277 #define SECURITY_PREFIX "security_"
19278
19279 static int check_attach_modify_return(unsigned long addr, const char *func_name)
19280 {
19281         if (within_error_injection_list(addr) ||
19282             !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1))
19283                 return 0;
19284
19285         return -EINVAL;
19286 }
19287
19288 /* list of non-sleepable functions that are otherwise on
19289  * ALLOW_ERROR_INJECTION list
19290  */
19291 BTF_SET_START(btf_non_sleepable_error_inject)
19292 /* Three functions below can be called from sleepable and non-sleepable context.
19293  * Assume non-sleepable from bpf safety point of view.
19294  */
19295 BTF_ID(func, __filemap_add_folio)
19296 BTF_ID(func, should_fail_alloc_page)
19297 BTF_ID(func, should_failslab)
19298 BTF_SET_END(btf_non_sleepable_error_inject)
19299
19300 static int check_non_sleepable_error_inject(u32 btf_id)
19301 {
19302         return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id);
19303 }
19304
19305 int bpf_check_attach_target(struct bpf_verifier_log *log,
19306                             const struct bpf_prog *prog,
19307                             const struct bpf_prog *tgt_prog,
19308                             u32 btf_id,
19309                             struct bpf_attach_target_info *tgt_info)
19310 {
19311         bool prog_extension = prog->type == BPF_PROG_TYPE_EXT;
19312         const char prefix[] = "btf_trace_";
19313         int ret = 0, subprog = -1, i;
19314         const struct btf_type *t;
19315         bool conservative = true;
19316         const char *tname;
19317         struct btf *btf;
19318         long addr = 0;
19319         struct module *mod = NULL;
19320
19321         if (!btf_id) {
19322                 bpf_log(log, "Tracing programs must provide btf_id\n");
19323                 return -EINVAL;
19324         }
19325         btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf;
19326         if (!btf) {
19327                 bpf_log(log,
19328                         "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n");
19329                 return -EINVAL;
19330         }
19331         t = btf_type_by_id(btf, btf_id);
19332         if (!t) {
19333                 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id);
19334                 return -EINVAL;
19335         }
19336         tname = btf_name_by_offset(btf, t->name_off);
19337         if (!tname) {
19338                 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id);
19339                 return -EINVAL;
19340         }
19341         if (tgt_prog) {
19342                 struct bpf_prog_aux *aux = tgt_prog->aux;
19343
19344                 if (bpf_prog_is_dev_bound(prog->aux) &&
19345                     !bpf_prog_dev_bound_match(prog, tgt_prog)) {
19346                         bpf_log(log, "Target program bound device mismatch");
19347                         return -EINVAL;
19348                 }
19349
19350                 for (i = 0; i < aux->func_info_cnt; i++)
19351                         if (aux->func_info[i].type_id == btf_id) {
19352                                 subprog = i;
19353                                 break;
19354                         }
19355                 if (subprog == -1) {
19356                         bpf_log(log, "Subprog %s doesn't exist\n", tname);
19357                         return -EINVAL;
19358                 }
19359                 conservative = aux->func_info_aux[subprog].unreliable;
19360                 if (prog_extension) {
19361                         if (conservative) {
19362                                 bpf_log(log,
19363                                         "Cannot replace static functions\n");
19364                                 return -EINVAL;
19365                         }
19366                         if (!prog->jit_requested) {
19367                                 bpf_log(log,
19368                                         "Extension programs should be JITed\n");
19369                                 return -EINVAL;
19370                         }
19371                 }
19372                 if (!tgt_prog->jited) {
19373                         bpf_log(log, "Can attach to only JITed progs\n");
19374                         return -EINVAL;
19375                 }
19376                 if (tgt_prog->type == prog->type) {
19377                         /* Cannot fentry/fexit another fentry/fexit program.
19378                          * Cannot attach program extension to another extension.
19379                          * It's ok to attach fentry/fexit to extension program.
19380                          */
19381                         bpf_log(log, "Cannot recursively attach\n");
19382                         return -EINVAL;
19383                 }
19384                 if (tgt_prog->type == BPF_PROG_TYPE_TRACING &&
19385                     prog_extension &&
19386                     (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY ||
19387                      tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) {
19388                         /* Program extensions can extend all program types
19389                          * except fentry/fexit. The reason is the following.
19390                          * The fentry/fexit programs are used for performance
19391                          * analysis, stats and can be attached to any program
19392                          * type except themselves. When extension program is
19393                          * replacing XDP function it is necessary to allow
19394                          * performance analysis of all functions. Both original
19395                          * XDP program and its program extension. Hence
19396                          * attaching fentry/fexit to BPF_PROG_TYPE_EXT is
19397                          * allowed. If extending of fentry/fexit was allowed it
19398                          * would be possible to create long call chain
19399                          * fentry->extension->fentry->extension beyond
19400                          * reasonable stack size. Hence extending fentry is not
19401                          * allowed.
19402                          */
19403                         bpf_log(log, "Cannot extend fentry/fexit\n");
19404                         return -EINVAL;
19405                 }
19406         } else {
19407                 if (prog_extension) {
19408                         bpf_log(log, "Cannot replace kernel functions\n");
19409                         return -EINVAL;
19410                 }
19411         }
19412
19413         switch (prog->expected_attach_type) {
19414         case BPF_TRACE_RAW_TP:
19415                 if (tgt_prog) {
19416                         bpf_log(log,
19417                                 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n");
19418                         return -EINVAL;
19419                 }
19420                 if (!btf_type_is_typedef(t)) {
19421                         bpf_log(log, "attach_btf_id %u is not a typedef\n",
19422                                 btf_id);
19423                         return -EINVAL;
19424                 }
19425                 if (strncmp(prefix, tname, sizeof(prefix) - 1)) {
19426                         bpf_log(log, "attach_btf_id %u points to wrong type name %s\n",
19427                                 btf_id, tname);
19428                         return -EINVAL;
19429                 }
19430                 tname += sizeof(prefix) - 1;
19431                 t = btf_type_by_id(btf, t->type);
19432                 if (!btf_type_is_ptr(t))
19433                         /* should never happen in valid vmlinux build */
19434                         return -EINVAL;
19435                 t = btf_type_by_id(btf, t->type);
19436                 if (!btf_type_is_func_proto(t))
19437                         /* should never happen in valid vmlinux build */
19438                         return -EINVAL;
19439
19440                 break;
19441         case BPF_TRACE_ITER:
19442                 if (!btf_type_is_func(t)) {
19443                         bpf_log(log, "attach_btf_id %u is not a function\n",
19444                                 btf_id);
19445                         return -EINVAL;
19446                 }
19447                 t = btf_type_by_id(btf, t->type);
19448                 if (!btf_type_is_func_proto(t))
19449                         return -EINVAL;
19450                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19451                 if (ret)
19452                         return ret;
19453                 break;
19454         default:
19455                 if (!prog_extension)
19456                         return -EINVAL;
19457                 fallthrough;
19458         case BPF_MODIFY_RETURN:
19459         case BPF_LSM_MAC:
19460         case BPF_LSM_CGROUP:
19461         case BPF_TRACE_FENTRY:
19462         case BPF_TRACE_FEXIT:
19463                 if (!btf_type_is_func(t)) {
19464                         bpf_log(log, "attach_btf_id %u is not a function\n",
19465                                 btf_id);
19466                         return -EINVAL;
19467                 }
19468                 if (prog_extension &&
19469                     btf_check_type_match(log, prog, btf, t))
19470                         return -EINVAL;
19471                 t = btf_type_by_id(btf, t->type);
19472                 if (!btf_type_is_func_proto(t))
19473                         return -EINVAL;
19474
19475                 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) &&
19476                     (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type ||
19477                      prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type))
19478                         return -EINVAL;
19479
19480                 if (tgt_prog && conservative)
19481                         t = NULL;
19482
19483                 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel);
19484                 if (ret < 0)
19485                         return ret;
19486
19487                 if (tgt_prog) {
19488                         if (subprog == 0)
19489                                 addr = (long) tgt_prog->bpf_func;
19490                         else
19491                                 addr = (long) tgt_prog->aux->func[subprog]->bpf_func;
19492                 } else {
19493                         if (btf_is_module(btf)) {
19494                                 mod = btf_try_get_module(btf);
19495                                 if (mod)
19496                                         addr = find_kallsyms_symbol_value(mod, tname);
19497                                 else
19498                                         addr = 0;
19499                         } else {
19500                                 addr = kallsyms_lookup_name(tname);
19501                         }
19502                         if (!addr) {
19503                                 module_put(mod);
19504                                 bpf_log(log,
19505                                         "The address of function %s cannot be found\n",
19506                                         tname);
19507                                 return -ENOENT;
19508                         }
19509                 }
19510
19511                 if (prog->aux->sleepable) {
19512                         ret = -EINVAL;
19513                         switch (prog->type) {
19514                         case BPF_PROG_TYPE_TRACING:
19515
19516                                 /* fentry/fexit/fmod_ret progs can be sleepable if they are
19517                                  * attached to ALLOW_ERROR_INJECTION and are not in denylist.
19518                                  */
19519                                 if (!check_non_sleepable_error_inject(btf_id) &&
19520                                     within_error_injection_list(addr))
19521                                         ret = 0;
19522                                 /* fentry/fexit/fmod_ret progs can also be sleepable if they are
19523                                  * in the fmodret id set with the KF_SLEEPABLE flag.
19524                                  */
19525                                 else {
19526                                         u32 *flags = btf_kfunc_is_modify_return(btf, btf_id,
19527                                                                                 prog);
19528
19529                                         if (flags && (*flags & KF_SLEEPABLE))
19530                                                 ret = 0;
19531                                 }
19532                                 break;
19533                         case BPF_PROG_TYPE_LSM:
19534                                 /* LSM progs check that they are attached to bpf_lsm_*() funcs.
19535                                  * Only some of them are sleepable.
19536                                  */
19537                                 if (bpf_lsm_is_sleepable_hook(btf_id))
19538                                         ret = 0;
19539                                 break;
19540                         default:
19541                                 break;
19542                         }
19543                         if (ret) {
19544                                 module_put(mod);
19545                                 bpf_log(log, "%s is not sleepable\n", tname);
19546                                 return ret;
19547                         }
19548                 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) {
19549                         if (tgt_prog) {
19550                                 module_put(mod);
19551                                 bpf_log(log, "can't modify return codes of BPF programs\n");
19552                                 return -EINVAL;
19553                         }
19554                         ret = -EINVAL;
19555                         if (btf_kfunc_is_modify_return(btf, btf_id, prog) ||
19556                             !check_attach_modify_return(addr, tname))
19557                                 ret = 0;
19558                         if (ret) {
19559                                 module_put(mod);
19560                                 bpf_log(log, "%s() is not modifiable\n", tname);
19561                                 return ret;
19562                         }
19563                 }
19564
19565                 break;
19566         }
19567         tgt_info->tgt_addr = addr;
19568         tgt_info->tgt_name = tname;
19569         tgt_info->tgt_type = t;
19570         tgt_info->tgt_mod = mod;
19571         return 0;
19572 }
19573
19574 BTF_SET_START(btf_id_deny)
19575 BTF_ID_UNUSED
19576 #ifdef CONFIG_SMP
19577 BTF_ID(func, migrate_disable)
19578 BTF_ID(func, migrate_enable)
19579 #endif
19580 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU
19581 BTF_ID(func, rcu_read_unlock_strict)
19582 #endif
19583 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE)
19584 BTF_ID(func, preempt_count_add)
19585 BTF_ID(func, preempt_count_sub)
19586 #endif
19587 #ifdef CONFIG_PREEMPT_RCU
19588 BTF_ID(func, __rcu_read_lock)
19589 BTF_ID(func, __rcu_read_unlock)
19590 #endif
19591 BTF_SET_END(btf_id_deny)
19592
19593 static bool can_be_sleepable(struct bpf_prog *prog)
19594 {
19595         if (prog->type == BPF_PROG_TYPE_TRACING) {
19596                 switch (prog->expected_attach_type) {
19597                 case BPF_TRACE_FENTRY:
19598                 case BPF_TRACE_FEXIT:
19599                 case BPF_MODIFY_RETURN:
19600                 case BPF_TRACE_ITER:
19601                         return true;
19602                 default:
19603                         return false;
19604                 }
19605         }
19606         return prog->type == BPF_PROG_TYPE_LSM ||
19607                prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ ||
19608                prog->type == BPF_PROG_TYPE_STRUCT_OPS;
19609 }
19610
19611 static int check_attach_btf_id(struct bpf_verifier_env *env)
19612 {
19613         struct bpf_prog *prog = env->prog;
19614         struct bpf_prog *tgt_prog = prog->aux->dst_prog;
19615         struct bpf_attach_target_info tgt_info = {};
19616         u32 btf_id = prog->aux->attach_btf_id;
19617         struct bpf_trampoline *tr;
19618         int ret;
19619         u64 key;
19620
19621         if (prog->type == BPF_PROG_TYPE_SYSCALL) {
19622                 if (prog->aux->sleepable)
19623                         /* attach_btf_id checked to be zero already */
19624                         return 0;
19625                 verbose(env, "Syscall programs can only be sleepable\n");
19626                 return -EINVAL;
19627         }
19628
19629         if (prog->aux->sleepable && !can_be_sleepable(prog)) {
19630                 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n");
19631                 return -EINVAL;
19632         }
19633
19634         if (prog->type == BPF_PROG_TYPE_STRUCT_OPS)
19635                 return check_struct_ops_btf_id(env);
19636
19637         if (prog->type != BPF_PROG_TYPE_TRACING &&
19638             prog->type != BPF_PROG_TYPE_LSM &&
19639             prog->type != BPF_PROG_TYPE_EXT)
19640                 return 0;
19641
19642         ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info);
19643         if (ret)
19644                 return ret;
19645
19646         if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) {
19647                 /* to make freplace equivalent to their targets, they need to
19648                  * inherit env->ops and expected_attach_type for the rest of the
19649                  * verification
19650                  */
19651                 env->ops = bpf_verifier_ops[tgt_prog->type];
19652                 prog->expected_attach_type = tgt_prog->expected_attach_type;
19653         }
19654
19655         /* store info about the attachment target that will be used later */
19656         prog->aux->attach_func_proto = tgt_info.tgt_type;
19657         prog->aux->attach_func_name = tgt_info.tgt_name;
19658         prog->aux->mod = tgt_info.tgt_mod;
19659
19660         if (tgt_prog) {
19661                 prog->aux->saved_dst_prog_type = tgt_prog->type;
19662                 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type;
19663         }
19664
19665         if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
19666                 prog->aux->attach_btf_trace = true;
19667                 return 0;
19668         } else if (prog->expected_attach_type == BPF_TRACE_ITER) {
19669                 if (!bpf_iter_prog_supported(prog))
19670                         return -EINVAL;
19671                 return 0;
19672         }
19673
19674         if (prog->type == BPF_PROG_TYPE_LSM) {
19675                 ret = bpf_lsm_verify_prog(&env->log, prog);
19676                 if (ret < 0)
19677                         return ret;
19678         } else if (prog->type == BPF_PROG_TYPE_TRACING &&
19679                    btf_id_set_contains(&btf_id_deny, btf_id)) {
19680                 return -EINVAL;
19681         }
19682
19683         key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id);
19684         tr = bpf_trampoline_get(key, &tgt_info);
19685         if (!tr)
19686                 return -ENOMEM;
19687
19688         if (tgt_prog && tgt_prog->aux->tail_call_reachable)
19689                 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX;
19690
19691         prog->aux->dst_trampoline = tr;
19692         return 0;
19693 }
19694
19695 struct btf *bpf_get_btf_vmlinux(void)
19696 {
19697         if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
19698                 mutex_lock(&bpf_verifier_lock);
19699                 if (!btf_vmlinux)
19700                         btf_vmlinux = btf_parse_vmlinux();
19701                 mutex_unlock(&bpf_verifier_lock);
19702         }
19703         return btf_vmlinux;
19704 }
19705
19706 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
19707 {
19708         u64 start_time = ktime_get_ns();
19709         struct bpf_verifier_env *env;
19710         int i, len, ret = -EINVAL, err;
19711         u32 log_true_size;
19712         bool is_priv;
19713
19714         /* no program is valid */
19715         if (ARRAY_SIZE(bpf_verifier_ops) == 0)
19716                 return -EINVAL;
19717
19718         /* 'struct bpf_verifier_env' can be global, but since it's not small,
19719          * allocate/free it every time bpf_check() is called
19720          */
19721         env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL);
19722         if (!env)
19723                 return -ENOMEM;
19724
19725         env->bt.env = env;
19726
19727         len = (*prog)->len;
19728         env->insn_aux_data =
19729                 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len));
19730         ret = -ENOMEM;
19731         if (!env->insn_aux_data)
19732                 goto err_free_env;
19733         for (i = 0; i < len; i++)
19734                 env->insn_aux_data[i].orig_idx = i;
19735         env->prog = *prog;
19736         env->ops = bpf_verifier_ops[env->prog->type];
19737         env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel);
19738         is_priv = bpf_capable();
19739
19740         bpf_get_btf_vmlinux();
19741
19742         /* grab the mutex to protect few globals used by verifier */
19743         if (!is_priv)
19744                 mutex_lock(&bpf_verifier_lock);
19745
19746         /* user could have requested verbose verifier output
19747          * and supplied buffer to store the verification trace
19748          */
19749         ret = bpf_vlog_init(&env->log, attr->log_level,
19750                             (char __user *) (unsigned long) attr->log_buf,
19751                             attr->log_size);
19752         if (ret)
19753                 goto err_unlock;
19754
19755         mark_verifier_state_clean(env);
19756
19757         if (IS_ERR(btf_vmlinux)) {
19758                 /* Either gcc or pahole or kernel are broken. */
19759                 verbose(env, "in-kernel BTF is malformed\n");
19760                 ret = PTR_ERR(btf_vmlinux);
19761                 goto skip_full_check;
19762         }
19763
19764         env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT);
19765         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS))
19766                 env->strict_alignment = true;
19767         if (attr->prog_flags & BPF_F_ANY_ALIGNMENT)
19768                 env->strict_alignment = false;
19769
19770         env->allow_ptr_leaks = bpf_allow_ptr_leaks();
19771         env->allow_uninit_stack = bpf_allow_uninit_stack();
19772         env->bypass_spec_v1 = bpf_bypass_spec_v1();
19773         env->bypass_spec_v4 = bpf_bypass_spec_v4();
19774         env->bpf_capable = bpf_capable();
19775
19776         if (is_priv)
19777                 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ;
19778
19779         env->explored_states = kvcalloc(state_htab_size(env),
19780                                        sizeof(struct bpf_verifier_state_list *),
19781                                        GFP_USER);
19782         ret = -ENOMEM;
19783         if (!env->explored_states)
19784                 goto skip_full_check;
19785
19786         ret = add_subprog_and_kfunc(env);
19787         if (ret < 0)
19788                 goto skip_full_check;
19789
19790         ret = check_subprogs(env);
19791         if (ret < 0)
19792                 goto skip_full_check;
19793
19794         ret = check_btf_info(env, attr, uattr);
19795         if (ret < 0)
19796                 goto skip_full_check;
19797
19798         ret = check_attach_btf_id(env);
19799         if (ret)
19800                 goto skip_full_check;
19801
19802         ret = resolve_pseudo_ldimm64(env);
19803         if (ret < 0)
19804                 goto skip_full_check;
19805
19806         if (bpf_prog_is_offloaded(env->prog->aux)) {
19807                 ret = bpf_prog_offload_verifier_prep(env->prog);
19808                 if (ret)
19809                         goto skip_full_check;
19810         }
19811
19812         ret = check_cfg(env);
19813         if (ret < 0)
19814                 goto skip_full_check;
19815
19816         ret = do_check_subprogs(env);
19817         ret = ret ?: do_check_main(env);
19818
19819         if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
19820                 ret = bpf_prog_offload_finalize(env);
19821
19822 skip_full_check:
19823         kvfree(env->explored_states);
19824
19825         if (ret == 0)
19826                 ret = check_max_stack_depth(env);
19827
19828         /* instruction rewrites happen after this point */
19829         if (ret == 0)
19830                 ret = optimize_bpf_loop(env);
19831
19832         if (is_priv) {
19833                 if (ret == 0)
19834                         opt_hard_wire_dead_code_branches(env);
19835                 if (ret == 0)
19836                         ret = opt_remove_dead_code(env);
19837                 if (ret == 0)
19838                         ret = opt_remove_nops(env);
19839         } else {
19840                 if (ret == 0)
19841                         sanitize_dead_code(env);
19842         }
19843
19844         if (ret == 0)
19845                 /* program is valid, convert *(u32*)(ctx + off) accesses */
19846                 ret = convert_ctx_accesses(env);
19847
19848         if (ret == 0)
19849                 ret = do_misc_fixups(env);
19850
19851         /* do 32-bit optimization after insn patching has done so those patched
19852          * insns could be handled correctly.
19853          */
19854         if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) {
19855                 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr);
19856                 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret
19857                                                                      : false;
19858         }
19859
19860         if (ret == 0)
19861                 ret = fixup_call_args(env);
19862
19863         env->verification_time = ktime_get_ns() - start_time;
19864         print_verification_stats(env);
19865         env->prog->aux->verified_insns = env->insn_processed;
19866
19867         /* preserve original error even if log finalization is successful */
19868         err = bpf_vlog_finalize(&env->log, &log_true_size);
19869         if (err)
19870                 ret = err;
19871
19872         if (uattr_size >= offsetofend(union bpf_attr, log_true_size) &&
19873             copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size),
19874                                   &log_true_size, sizeof(log_true_size))) {
19875                 ret = -EFAULT;
19876                 goto err_release_maps;
19877         }
19878
19879         if (ret)
19880                 goto err_release_maps;
19881
19882         if (env->used_map_cnt) {
19883                 /* if program passed verifier, update used_maps in bpf_prog_info */
19884                 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
19885                                                           sizeof(env->used_maps[0]),
19886                                                           GFP_KERNEL);
19887
19888                 if (!env->prog->aux->used_maps) {
19889                         ret = -ENOMEM;
19890                         goto err_release_maps;
19891                 }
19892
19893                 memcpy(env->prog->aux->used_maps, env->used_maps,
19894                        sizeof(env->used_maps[0]) * env->used_map_cnt);
19895                 env->prog->aux->used_map_cnt = env->used_map_cnt;
19896         }
19897         if (env->used_btf_cnt) {
19898                 /* if program passed verifier, update used_btfs in bpf_prog_aux */
19899                 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
19900                                                           sizeof(env->used_btfs[0]),
19901                                                           GFP_KERNEL);
19902                 if (!env->prog->aux->used_btfs) {
19903                         ret = -ENOMEM;
19904                         goto err_release_maps;
19905                 }
19906
19907                 memcpy(env->prog->aux->used_btfs, env->used_btfs,
19908                        sizeof(env->used_btfs[0]) * env->used_btf_cnt);
19909                 env->prog->aux->used_btf_cnt = env->used_btf_cnt;
19910         }
19911         if (env->used_map_cnt || env->used_btf_cnt) {
19912                 /* program is valid. Convert pseudo bpf_ld_imm64 into generic
19913                  * bpf_ld_imm64 instructions
19914                  */
19915                 convert_pseudo_ld_imm64(env);
19916         }
19917
19918         adjust_btf_func(env);
19919
19920 err_release_maps:
19921         if (!env->prog->aux->used_maps)
19922                 /* if we didn't copy map pointers into bpf_prog_info, release
19923                  * them now. Otherwise free_used_maps() will release them.
19924                  */
19925                 release_maps(env);
19926         if (!env->prog->aux->used_btfs)
19927                 release_btfs(env);
19928
19929         /* extension progs temporarily inherit the attach_type of their targets
19930            for verification purposes, so set it back to zero before returning
19931          */
19932         if (env->prog->type == BPF_PROG_TYPE_EXT)
19933                 env->prog->expected_attach_type = 0;
19934
19935         *prog = env->prog;
19936 err_unlock:
19937         if (!is_priv)
19938                 mutex_unlock(&bpf_verifier_lock);
19939         vfree(env->insn_aux_data);
19940 err_free_env:
19941         kfree(env);
19942         return ret;
19943 }